From 86f562f5b607313f595ceca093e4ab72299dfe3f Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Wed, 7 Oct 2026 11:33:40 +0300 Subject: [PATCH] feat(identity): enforce shared session and browser request security --- api/README.en.md | 24 ++--- api/README.md | 24 ++--- backend/README.en.md | 4 +- backend/README.md | 4 +- .../email_verification_test.go | 3 + backend/integration_test/registration_test.go | 83 +++++++++++++++- backend/integration_test/session_http_test.go | 54 ++++++++++- .../http/identity_confirmation_test.go | 5 +- .../http/identity_registration_test.go | 94 ++++++++++++++++++- .../internal/adapter/primary/http/router.go | 5 +- .../primary/http/security_contract_test.go | 55 +++++++++++ .../http/v1/{handler_test.go => api_test.go} | 0 .../internal/adapter/primary/http/v1/auth.go | 19 ++-- .../adapter/primary/http/v1/identity.go | 30 +++--- .../adapter/primary/http/v1/principal.go | 14 ++- .../adapter/primary/http/v1/security.go | 20 ++-- .../adapter/primary/http/v1/session.go | 33 +++---- .../adapter/primary/http/v1/session_test.go | 55 ++++++++--- backend/internal/bootstrap/identity.go | 5 +- docs/en/ARCHITECTURE.md | 4 +- docs/en/DEPLOY.md | 6 +- docs/ru/ARCHITECTURE.md | 4 +- docs/ru/DEPLOY.md | 6 +- 23 files changed, 430 insertions(+), 121 deletions(-) rename backend/internal/adapter/primary/http/v1/{handler_test.go => api_test.go} (100%) diff --git a/api/README.en.md b/api/README.en.md index 086335f..e20b7a6 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -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`, `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. +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. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Other protected operations pass the boundary but answer 501 `not_implemented` after request validation until their business handlers exist. Frontend registration and confirmation screens remain placeholders. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -140,7 +140,7 @@ Sessions and CSRF: - 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`). +- Every unsafe public identity operation requires exactly one `Origin` header matching `APP_PUBLIC_URL`, including `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`. Unsafe operations protected by a session also require the session-bound CSRF token. Origin checks do not use `Host` or forwarded headers. 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. @@ -148,11 +148,11 @@ How the generated server (ogen v1.24.0) evaluates the schemes, and how `v1.Sessi - 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. -- 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. +- Implemented mapping: `HandleSessionCookie` authenticates every operation whose contract requires `sessionCookie`; missing, unknown, expired, revoked, or unverified sessions leave the requirement unsatisfied and answer 401 `unauthenticated`. For protected unsafe operations, `HandleSessionCsrf` checks the exact Origin and the token for that same session. Without a verified principal the result is 401; with one, a missing or wrong Origin or CSRF token is 403 `csrf_check_failed`. A 401 from `Logout` also clears the cookie, while a 403 leaves a valid session intact. ### Catalog and questionnaire -The `catalog` and `candidate` tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The operations are in the contract; their business logic is not implemented yet, so the catalog answers 501 `not_implemented` and the questionnaire answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). +The `catalog` and `candidate` tags cover the specialization catalog and the candidate questionnaire (PRD FR03). The catalog is public and answers 501 `not_implemented` until its handler exists. The questionnaire is protected: a guest answers 401 `unauthenticated`, while a valid session passes the security boundary and reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -180,7 +180,7 @@ Questionnaire: ### Candidate profile -The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD). The operations are in the contract and the business logic is not implemented yet, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` once a session is accepted and the schema is valid. +The `candidate` tag also describes the private candidate profile that the candidate fills in by hand (FR02 in the PRD). The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -238,7 +238,7 @@ Open questions for the product owner and legal: ### Assessment -The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). +The `assessment` tag covers the assessment attempts of the current candidate (PRD FR04 and FR05): availability, start and resume, answers including the code practice, finalization, and the result. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -315,7 +315,7 @@ Planned, additive: a short approach description of up to 1500 characters next to ### Needs -The `need` tag covers the hiring needs of an organization (PRD FR08, with the versions of FR10): requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). +The `need` tag covers the hiring needs of an organization (PRD FR08, with the versions of FR10): requirements with their confirmation state and provenance, immutable versions, readiness, and category recommendations. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -382,7 +382,7 @@ Planned, additive: reading and comparing versions, exclusions, the market range ### Support cases -The `support` tag covers the cases of the current account (PRD FR18, with the manual assessment of FR04 and C3): questions to support, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). +The `support` tag covers the cases of the current account (PRD FR18, with the manual assessment of FR04 and C3): questions to support, complaints, appeals of a grade or an anti-cheat decision, and manual assessment requests. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -448,7 +448,7 @@ Planned contract changes (new enum values; like the catalog codes, generated cli ### Invitations and contact grants -The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). +The `invitation` tag covers invitations from an organization to one candidate (PRD FR12, with the salary rules of FR13 and the consent C4): drafts with complete terms, immutable terms versions, sending, the candidate's inbox, the view, acceptance with C4, structured declines, withdrawal, cancellation, and the contact grant. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -530,7 +530,7 @@ No new problem code is added: the `ProblemCode` enum is copied byte-for-byte int ### Consents -The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. The read operation is in the contract; its handler is not implemented yet, so it answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind it exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)). +The `consent` tag covers the consent ledger of the current account (PRD FR01, FR12, and 7.3): the independent consents C1-C5 with their text versions, sources, states, and revocations. The read operation is in the contract but its handler is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented`. The storage behind it exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#consent-ledger)). | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -548,7 +548,7 @@ No new problem code is added: the contract reuses `validation_failed` and `unaut ### Organizations -The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract; their business logic is not implemented yet, so every one answers 401 `unauthenticated` until sessions exist (`v1.DenyAllSecurity`). The storage behind them exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned as part of organization management and access control. +The `organization` tag covers the organizations of employer accounts and the memberships that give an account its role in them (PRD FR07, 2.2, and 6.4): the profile with its public contacts and representatives, the verification level that only the server sets, and the active organization context. The operations are in the contract, but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. The storage behind them exists (see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#organizations-and-memberships)); creating, editing, and the membership checks of the other operations are planned as part of organization management and access control. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -613,7 +613,7 @@ No new problem code is added: the contract reuses `validation_failed`, `unauthen ### Candidate visibility -The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD). The operations are in the contract but their business logic is not implemented, so each answers 401 `unauthenticated` while there are no sessions (`v1.DenyAllSecurity`), and 501 `not_implemented` after an accepted session and a valid request. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)). +The tag `privacy` describes what organizations may see of the current candidate: the publication of the anonymous card, the search status, the organizations the candidate hides the profile from, a preview, and two histories (FR02 and FR12 in the PRD). The operations are in the contract but their business logic is not implemented: a guest answers 401 `unauthenticated`, and a request with a verified session reaches 501 `not_implemented` after request validation. Unsafe protected operations also require the session-bound CSRF token and exact Origin. The storage behind them exists (migration 00015, see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#candidate-visibility)). | Method and path | operationId | Protection | Success | Specific errors | | --- | --- | --- | --- | --- | diff --git a/api/README.md b/api/README.md index 489178c..19502a6 100644 --- a/api/README.md +++ b/api/README.md @@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Identity: сессии, cookie и CSRF -Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session security разрешает только последние три защищенные операции; остальные операции, требующие сессию, остаются закрытыми с 401 `unauthenticated`. Экраны регистрации и подтверждения во frontend остаются заглушками. +Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Остальные защищенные операции проходят эту границу, но отвечают 501 `not_implemented` после проверки запроса, пока для них нет бизнес-обработчиков. Экраны регистрации и подтверждения во frontend остаются заглушками. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -140,7 +140,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Реализованные операции сессии: 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`). +- Каждая небезопасная публичная identity-операция требует ровно один заголовок `Origin`, совпадающий с `APP_PUBLIC_URL`, включая `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail` и `Login`. Небезопасные защищенные операции также требуют session-bound CSRF-токен. Проверка Origin не использует `Host` или forwarded headers. Публичные identity-операции ограничены по частоте (429 с `Retry-After`). - Ответы с сессией или аккаунтом несут `Cache-Control: no-store`. - Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию. @@ -148,11 +148,11 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом. - Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`. -- Реализованное отображение: `HandleSessionCookie` аутентифицирует только `GetCurrentSession`, `GetCurrentAccount` и `Logout`; для отсутствующей, неизвестной, истекшей или отозванной сессии проверка не выполнена. `HandleSessionCsrf` проверяет Origin и токен только для `Logout`; без principal отказ остается 401, неверный Origin или CSRF с действующим principal дает 403 `csrf_check_failed`. Другие protected operations не проходят allowlist и остаются 401 `unauthenticated`. 401 от `Logout` также очищает cookie. +- Реализованное отображение: `HandleSessionCookie` аутентифицирует каждую операцию, для которой контракт требует `sessionCookie`; отсутствующая, неизвестная, истекшая, отозванная или неподтвержденная сессия отвечает 401 `unauthenticated`. Для небезопасных защищенных операций `HandleSessionCsrf` проверяет точный Origin и токен той же сессии. Без подтвержденного principal результат - 401; с ним отсутствующий или неверный Origin либо CSRF дает 403 `csrf_check_failed`. Ответ 401 от `Logout` также очищает cookie, а 403 сохраняет действующую сессию. ### Каталог и анкета -Теги `catalog` и `candidate` описывают каталог специализаций и анкету кандидата (FR03 в PRD). Операции есть в контракте, бизнес-логика еще не реализована: каталог отвечает 501 `not_implemented`, а анкета - 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`). +Теги `catalog` и `candidate` описывают каталог специализаций и анкету кандидата (FR03 в PRD). Каталог публичный и отвечает 501 `not_implemented`, пока не появится его обработчик. Анкета защищена: гость получает 401 `unauthenticated`, а запрос с действующей сессией проходит security boundary и после проверки запроса достигает 501 `not_implemented`. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -180,7 +180,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Профиль кандидата -Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD). Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидной схемы - 501 `not_implemented`. +Тег `candidate` описывает и приватный профиль кандидата, который кандидат заполняет вручную (FR02 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -238,7 +238,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Оценка -Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`). +Тег `assessment` описывает попытки оценки текущего кандидата (FR04 и FR05 в PRD): доступность, старт и возобновление, ответы вместе с кодовой практикой, завершение и результат. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -315,7 +315,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Потребности -Тег `need` описывает потребности организации в найме (FR08 в PRD, с версиями из FR10): требования с состоянием подтверждения и происхождением, неизменяемые версии, готовность и рекомендации категорий. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`). +Тег `need` описывает потребности организации в найме (FR08 в PRD, с версиями из FR10): требования с состоянием подтверждения и происхождением, неизменяемые версии, готовность и рекомендации категорий. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -382,7 +382,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Обращения -Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции есть в контракте, бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`). +Тег `support` описывает обращения текущего аккаунта (FR18 в PRD, с ручной оценкой из FR04 и C3): вопросы в поддержку, жалобы, апелляции грейда и античит-решения, запросы ручной оценки. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -448,7 +448,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Приглашения и контактные разрешения -Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Операции есть в контракте; их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока нет сессий (`v1.DenyAllSecurity`). +Тег `invitation` описывает приглашения организации одному кандидату (FR12 в PRD, с правилами вилки FR13 и согласием C4): черновики с полными условиями, неизменяемые версии условий, отправку, входящие кандидата, просмотр, принятие с C4, структурированный отказ, отзыв, отмену участия и контактное разрешение (grant). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -530,7 +530,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Согласия -Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован, поэтому до появления сессий она отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ней уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)). +Тег `consent` описывает журнал согласий текущего аккаунта (FR01, FR12 и 7.3 в PRD): независимые согласия C1-C5 с версиями текстов, источниками, состояниями и отзывами. Операция чтения есть в контракте, но ее обработчик еще не реализован: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented`. Хранение за ней уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#журнал-согласий)). | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -548,7 +548,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Организации -Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому до появления сессий каждая отвечает 401 `unauthenticated` (`v1.DenyAllSecurity`). Хранение за ними уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в управлении организациями и контроле доступа. +Тег `organization` описывает организации аккаунтов работодателя и членства, которые дают аккаунту роль в них (FR07, 2.2 и 6.4 в PRD): профиль с публичными контактами и представителями, уровень проверки, который задает только сервер, и активный контекст организации. Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. Хранение за ними уже есть (см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#организации-и-членства)); создание, редактирование и проверки членства в остальных операциях запланированы в управлении организациями и контроле доступа. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -613,7 +613,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Видимость кандидата -Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована, поэтому каждая отвечает 401 `unauthenticated`, пока сессий нет (`v1.DenyAllSecurity`), а после принятой сессии и валидного запроса - 501 `not_implemented`. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)). +Тег `privacy` описывает, что организации могут видеть о текущем кандидате: публикацию анонимной карточки, статус поиска, организации, от которых кандидат скрывает профиль, предпросмотр и две истории (FR02 и FR12 в PRD). Операции есть в контракте, но их бизнес-логика еще не реализована: гость получает 401 `unauthenticated`, а запрос с подтвержденной сессией достигает 501 `not_implemented` после проверки запроса. Небезопасные защищенные операции также требуют session-bound CSRF-токен и точный Origin. Хранение за ними уже есть (миграция 00015, см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#видимость-кандидата)). | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | diff --git a/backend/README.en.md b/backend/README.en.md index 99dc906..8c13be5 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -14,11 +14,11 @@ From the repository root, `make -C backend check` runs the main checks and `make ## Server sessions -The implemented operations are email-and-password login, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current`, and `DELETE /api/v1/identity/sessions/current`. Other operations that require a session remain unavailable. Only accounts with a verified email can sign in. An unknown email and an incorrect password return the same `401 invalid_credentials`; correct credentials for an unverified account return `403 email_not_verified`. +Registration, email confirmation, login, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current`, and `DELETE /api/v1/identity/sessions/current` are implemented. The session boundary authenticates every operation protected by the OpenAPI contract; handwritten handlers can read a principal containing the user ID and verified-email state resolved from the PostgreSQL session. Unknown, expired, revoked, or unverified sessions answer `401 unauthenticated`. Other protected business operations currently answer 501 after the security boundary and request validation succeed. An unknown email and an incorrect password return the same `401 invalid_credentials`; correct credentials for an unverified account return `403 email_not_verified` at login. Sessions are stored in PostgreSQL. The browser receives a `__Host-lincodex_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/`, and no `Domain`; the database stores only the token hash. The default idle timeout is 24 hours and the absolute lifetime is 168 hours. Configure them with `IDENTITY_SESSION_IDLE_TIMEOUT` and `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; the idle timeout cannot exceed the absolute lifetime. -Login and logout require exactly one `Origin` header whose value exactly matches the configured `APP_PUBLIC_URL`; forwarded headers are not used for this check. Logout also requires the session-bound HMAC token in `X-CSRF-Token`. All API instances must use the same `IDENTITY_KEY_SECRET` for this check. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour. +Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires exactly one `Origin` header matching `APP_PUBLIC_URL`. Unsafe session operations also require the session-bound HMAC token in `X-CSRF-Token`; all API instances must use the same `IDENTITY_KEY_SECRET`. Origin checks do not trust `Host` or forwarded headers. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour. HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int`; compile the integration suite without starting containers with `make -C backend test-int-compile`. diff --git a/backend/README.md b/backend/README.md index 102fb32..5a9c719 100644 --- a/backend/README.md +++ b/backend/README.md @@ -14,11 +14,11 @@ ## Серверные сессии -Реализованы вход по email и паролю, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current` и `DELETE /api/v1/identity/sessions/current`. Остальные операции, требующие сессию, пока остаются закрытыми. Войти может только пользователь с подтвержденным email. Неизвестный email и неверный пароль возвращают одинаковый `401 invalid_credentials`; для правильного пароля неподтвержденной учетной записи возвращается `403 email_not_verified`. +Реализованы регистрация, подтверждение email, вход, `GET /api/v1/identity/me`, `GET /api/v1/identity/sessions/current` и `DELETE /api/v1/identity/sessions/current`. Session boundary аутентифицирует каждую операцию, для которой OpenAPI требует сессию; principal для handwritten handlers содержит ID и подтвержденный email из PostgreSQL-сессии. Неизвестная, истекшая, отозванная сессия и аккаунт без подтвержденного email получают `401 unauthenticated`. Остальные защищенные бизнес-операции пока отвечают 501 после успешной проверки security и запроса. Неизвестный email и неверный пароль возвращают одинаковый `401 invalid_credentials`; правильный пароль неподтвержденной учетной записи при входе дает `403 email_not_verified`. Сессия хранится в PostgreSQL. Браузер получает cookie `__Host-lincodex_session` с атрибутами `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/` и без `Domain`; в базе хранится только хеш токена. Время бездействия по умолчанию - 24 часа, абсолютный срок - 168 часов. Эти значения задаются через `IDENTITY_SESSION_IDLE_TIMEOUT` и `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; время бездействия не может превышать абсолютный срок. -Вход и выход требуют единственного заголовка `Origin`, в точности совпадающего с настроенным `APP_PUBLIC_URL`; адреса из forwarded-заголовков для этого не используются. Выход дополнительно требует `X-CSRF-Token`, HMAC-токен для текущей сессии. Для него все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверки с неверным Origin или CSRF отвечают `403` и сохраняют действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час. +Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`) требует ровно один заголовок `Origin`, в точности совпадающий с `APP_PUBLIC_URL`. Небезопасные операции сессии также требуют `X-CSRF-Token`, HMAC-токен, связанный с текущей сессией; все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверка Origin не доверяет `Host` или forwarded-заголовкам. Неверный Origin или CSRF отвечает `403` и сохраняет действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час. Проверки HTTP-сценариев с PostgreSQL и Redis входят в `make -C backend test-int`; компиляция integration suite без запуска контейнеров выполняется через `make -C backend test-int-compile`. diff --git a/backend/integration_test/email_verification_test.go b/backend/integration_test/email_verification_test.go index 7c36ecb..e0df035 100644 --- a/backend/integration_test/email_verification_test.go +++ b/backend/integration_test/email_verification_test.go @@ -493,6 +493,9 @@ func (harness *registrationHarness) confirm(t *testing.T, token, password string if err != nil { t.Fatalf("encode confirmation request: %v", err) } + if origin == nil { + return harness.postWithoutDefaultOrigin(t, emailVerificationPath, string(body), headers) + } return harness.post(t, emailVerificationPath, string(body), headers) } diff --git a/backend/integration_test/registration_test.go b/backend/integration_test/registration_test.go index c8d5d85..790587f 100644 --- a/backend/integration_test/registration_test.go +++ b/backend/integration_test/registration_test.go @@ -73,6 +73,7 @@ type registrationHarness struct { clock *testClock logs *syncBuffer identity *postgresadapter.IdentityStore + origin string // registration is the usecase behind the router. registration *identity.Registration // nextKey makes every request carry a new Idempotency-Key. @@ -170,7 +171,9 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm responder := problem.NewResponder(logger) healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler( - registration, v1.WithEmailConfirmation(confirmation, env.Config.AppPublicURL), + registration, + v1.WithEmailConfirmation(confirmation), + v1.WithPublicOrigin(env.Config.AppPublicURL), ))) router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, metrics, logger, nil) if err != nil { @@ -196,6 +199,7 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm } return ®istrationHarness{ start: start, pool: pool, router: router, sender: sender, fixture: fixture, clock: clock, logs: logs, identity: identityStore, + origin: env.Config.AppPublicURL, registration: registration, } } @@ -210,9 +214,20 @@ type registrationResponse struct { } func (harness *registrationHarness) post(t *testing.T, path, body string, headers map[string]string) registrationResponse { + return harness.postWithOriginDefault(t, path, body, headers, true) +} + +func (harness *registrationHarness) postWithoutDefaultOrigin(t *testing.T, path, body string, headers map[string]string) registrationResponse { + return harness.postWithOriginDefault(t, path, body, headers, false) +} + +func (harness *registrationHarness) postWithOriginDefault(t *testing.T, path, body string, headers map[string]string, setDefaultOrigin bool) registrationResponse { t.Helper() request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) request.Header.Set("Content-Type", "application/json") + if setDefaultOrigin { + request.Header.Set("Origin", harness.origin) + } for name, value := range headers { request.Header.Set(name, value) } @@ -678,6 +693,72 @@ func TestRegistrationOverHTTP(t *testing.T) { }) } +func TestPublicIdentityOriginRefusalDoesNotMutateAccountsOrMailState(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 1000) + harness.truncate(ctx, t) + harness.clock.Set(harness.start) + + const verifiedFlowEmail = "origin-check@example.test" + token := harness.registerAndSendVerification(ctx, t, verifiedFlowEmail, "candidate", registrationPassword) + stateCounts := func() map[string]int { + t.Helper() + counts := make(map[string]int) + for _, table := range []string{"users", "consent_records", "email_tokens", "idempotency_records", "outbox_events", "deliveries"} { + counts[table] = harness.count(ctx, t, "SELECT count(*) FROM "+table) + } + return counts + } + assertCountsUnchanged := func(want map[string]int) { + t.Helper() + for table, expected := range want { + if got := harness.count(ctx, t, "SELECT count(*) FROM "+table); got != expected { + t.Errorf("%s count = %d after Origin refusal, want unchanged at %d", table, got, expected) + } + } + } + before := stateCounts() + register := harness.post(t, registrationPath, + registrationBody("rejected@example.test", "candidate", registrationPassword, registrationC1), + map[string]string{"Idempotency-Key": "origin-refused-registration", "Origin": "https://attacker.example"}, + ) + requireProblemStatus(t, register, http.StatusForbidden, "csrf_check_failed") + assertCountsUnchanged(before) + + resend := harness.post(t, resendPath, `{"email":"`+verifiedFlowEmail+`"}`, map[string]string{"Origin": "https://attacker.example"}) + requireProblemStatus(t, resend, http.StatusForbidden, "csrf_check_failed") + assertCountsUnchanged(before) + + confirmation := harness.post(t, emailVerificationPath, + `{"token":"`+token+`","password":"`+registrationPassword+`"}`, + map[string]string{"Origin": "https://attacker.example"}, + ) + requireProblemStatus(t, confirmation, http.StatusForbidden, "csrf_check_failed") + assertCountsUnchanged(before) + + var verifiedAt *time.Time + var registrationVersion int64 + if err := harness.pool.QueryRow(ctx, + `SELECT email_verified_at, registration_version FROM users WHERE email_normalized = $1`, verifiedFlowEmail, + ).Scan(&verifiedAt, ®istrationVersion); err != nil { + t.Fatalf("read account after Origin refusals: %v", err) + } + if verifiedAt != nil || registrationVersion != 1 { + t.Fatalf("account state after refused operations: verified=%v registration version=%d", verifiedAt, registrationVersion) + } + var consumedAt, invalidatedAt *time.Time + if err := harness.pool.QueryRow(ctx, + `SELECT consumed_at, invalidated_at FROM email_tokens WHERE user_id = (SELECT id FROM users WHERE email_normalized = $1)`, verifiedFlowEmail, + ).Scan(&consumedAt, &invalidatedAt); err != nil { + t.Fatalf("read verification token state after Origin refusals: %v", err) + } + if consumedAt != nil || invalidatedAt != nil { + t.Fatalf("verification token changed after Origin refusals: consumed=%v invalidated=%v", consumedAt, invalidatedAt) + } +} + func TestRegistrationClientLimit(t *testing.T) { env := bootstrap(t, postgresService, redisService) ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout) diff --git a/backend/integration_test/session_http_test.go b/backend/integration_test/session_http_test.go index 3eb23a5..258ba81 100644 --- a/backend/integration_test/session_http_test.go +++ b/backend/integration_test/session_http_test.go @@ -86,12 +86,15 @@ func newSessionHTTPHarnessWithSettings( logger := slog.New(slog.NewJSONHandler(logs, nil)) responder := problem.NewResponder(logger) healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) - identityHandler := v1.NewIdentityHandler(nil, v1.WithSessionService(service, env.Config.AppPublicURL)) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithSessionService(service), + v1.WithPublicOrigin(env.Config.AppPublicURL), + ) handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler)) router, err := httpadapter.NewRouter( healthHandler, handler, - v1.NewSessionSecurity(service, env.Config.AppPublicURL), + identityHandler.SessionSecurity(), responder, prometheus.New(), logger, @@ -323,12 +326,55 @@ func TestIdentitySessionsOverHTTP(t *testing.T) { if sessionBody.Account.Email != verifiedEmail || !sessionBody.Account.EmailVerified || sessionBody.CSRFToken != firstBody.CSRFToken { t.Fatalf("current session response = %+v, want the authenticated account and CSRF token", sessionBody) } + var userVersionBefore int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1`, verifiedUser.ID).Scan(&userVersionBefore); err != nil { + t.Fatalf("read current account version before protected reads: %v", err) + } + var outboxBefore, idempotencyBefore int64 + if err := harness.pool.QueryRow(ctx, + `SELECT (SELECT count(*) FROM outbox_events), (SELECT count(*) FROM idempotency_records)`, + ).Scan(&outboxBefore, &idempotencyBefore); err != nil { + t.Fatalf("read business side-effect counts before protected reads: %v", err) + } currentAccount := harness.request(t, http.MethodGet, "/api/v1/identity/me", "", "", firstCookie.Value, "", "192.0.2.7:1234") if currentAccount.Code != http.StatusOK || currentAccount.Header().Get("Cache-Control") != "no-store" || !strings.Contains(currentAccount.Body.String(), verifiedEmail) { t.Fatalf("current account response = %d %s, Cache-Control=%q", currentAccount.Code, currentAccount.Body.String(), currentAccount.Header().Get("Cache-Control")) } - unsupported := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", firstCookie.Value, "", "192.0.2.8:1234") - requireSessionProblem(t, unsupported, http.StatusUnauthorized, "unauthenticated") + var accountBody struct { + ID string `json:"id"` + EmailVerified bool `json:"email_verified"` + } + if err := json.Unmarshal(currentAccount.Body.Bytes(), &accountBody); err != nil { + t.Fatalf("decode current account response: %v", err) + } + if accountBody.ID != verifiedUser.ID.String() || !accountBody.EmailVerified { + t.Fatalf("current account = %+v, want verified account resolved from PostgreSQL session", accountBody) + } + guestProfile := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", "", "", "192.0.2.8:1234") + requireSessionProblem(t, guestProfile, http.StatusUnauthorized, "unauthenticated") + guestWrite := harness.request(t, http.MethodPut, "/api/v1/me/privacy/search-status", `{"expected_version":0,"value":"looking"}`, "", "", "", "192.0.2.9:1234") + requireSessionProblem(t, guestWrite, http.StatusUnauthorized, "unauthenticated") + unsupported := harness.request(t, http.MethodGet, "/api/v1/me/profile", "", "", firstCookie.Value, "", "192.0.2.18:1234") + requireSessionProblem(t, unsupported, http.StatusNotImplemented, "not_implemented") + unsupportedWrite := harness.request( + t, http.MethodPut, "/api/v1/me/privacy/search-status", `{"expected_version":0,"value":"looking"}`, + sessionHTTPTestOrigin, firstCookie.Value, firstBody.CSRFToken, "192.0.2.19:1234", + ) + requireSessionProblem(t, unsupportedWrite, http.StatusNotImplemented, "not_implemented") + var userVersionAfter int64 + if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1`, verifiedUser.ID).Scan(&userVersionAfter); err != nil { + t.Fatalf("read current account version after protected reads: %v", err) + } + var outboxAfter, idempotencyAfter int64 + if err := harness.pool.QueryRow(ctx, + `SELECT (SELECT count(*) FROM outbox_events), (SELECT count(*) FROM idempotency_records)`, + ).Scan(&outboxAfter, &idempotencyAfter); err != nil { + t.Fatalf("read business side-effect counts after protected reads: %v", err) + } + if userVersionAfter != userVersionBefore || outboxAfter != outboxBefore || idempotencyAfter != idempotencyBefore { + t.Fatalf("protected reads changed account or business side effects: user version %d -> %d, outbox %d -> %d, idempotency %d -> %d", + userVersionBefore, userVersionAfter, outboxBefore, outboxAfter, idempotencyBefore, idempotencyAfter) + } wrongPasswordWithSession := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.9:1234") requireSessionProblem(t, wrongPasswordWithSession, http.StatusUnauthorized, "invalid_credentials") diff --git a/backend/internal/adapter/primary/http/identity_confirmation_test.go b/backend/internal/adapter/primary/http/identity_confirmation_test.go index 6981656..8e0e210 100644 --- a/backend/internal/adapter/primary/http/identity_confirmation_test.go +++ b/backend/internal/adapter/primary/http/identity_confirmation_test.go @@ -36,7 +36,10 @@ func newConfirmationRouter(t *testing.T, confirmation v1.EmailConfirmation) http t.Helper() logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - identityHandler := v1.NewIdentityHandler(nil, v1.WithEmailConfirmation(confirmation, "https://app.example")) + identityHandler := v1.NewIdentityHandler(nil, + v1.WithEmailConfirmation(confirmation), + v1.WithPublicOrigin("https://app.example"), + ) handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(identityHandler)) return newTestRouterWithAPI(t, healthHandler, handler, logger) } diff --git a/backend/internal/adapter/primary/http/identity_registration_test.go b/backend/internal/adapter/primary/http/identity_registration_test.go index ba274cd..e1e5a95 100644 --- a/backend/internal/adapter/primary/http/identity_registration_test.go +++ b/backend/internal/adapter/primary/http/identity_registration_test.go @@ -5,6 +5,8 @@ import ( "errors" "log/slog" "net/http" + "net/http/httptest" + "strings" "testing" "time" @@ -22,32 +24,41 @@ type scriptedRegistration struct { err error register identity.RegisterCommand resend identity.ResendCommand + calls int } func (registration *scriptedRegistration) Register(_ context.Context, command identity.RegisterCommand) error { + registration.calls++ registration.register = command return registration.err } func (registration *scriptedRegistration) ResendVerification(_ context.Context, command identity.ResendCommand) error { + registration.calls++ registration.resend = command return registration.err } +const identityTestOrigin = "https://app.example" + func newIdentityRouter(t *testing.T, registration v1.AccountRegistration) http.Handler { t.Helper() logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(v1.NewIdentityHandler(registration))) + identityHandler := v1.NewIdentityHandler(registration, v1.WithPublicOrigin(identityTestOrigin)) + handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(identityHandler)) return newTestRouterWithAPI(t, healthHandler, handler, logger) } func TestRegistrationOperationsMapUsecaseOutcomes(t *testing.T) { registerRequest := identityRequest{ method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent), - headers: map[string]string{"Idempotency-Key": testIdempotencyKey}, + headers: map[string]string{"Idempotency-Key": testIdempotencyKey, "Origin": identityTestOrigin}, + } + resendRequest := identityRequest{ + method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`, + headers: map[string]string{"Origin": identityTestOrigin}, } - resendRequest := identityRequest{method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`} staleConsent := &identity.InvalidFieldError{Pointer: "/consent_c1/text_version", Err: errors.New("stale")} for _, test := range []struct { name string @@ -105,7 +116,7 @@ func TestRegistrationPassesTheRequestToTheUsecase(t *testing.T) { router := newIdentityRouter(t, registration) response := serveIdentityRequest(t, router, identityRequest{ method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent), - headers: map[string]string{"Idempotency-Key": testIdempotencyKey}, + headers: map[string]string{"Idempotency-Key": testIdempotencyKey, "Origin": identityTestOrigin}, }) if response.Code != http.StatusAccepted { t.Fatalf("status = %d: %s", response.Code, response.Body.String()) @@ -118,3 +129,78 @@ func TestRegistrationPassesTheRequestToTheUsecase(t *testing.T) { t.Fatalf("command = %+v, want %+v", registration.register, want) } } + +func TestRegistrationAndResendRejectOriginBeforeUsecase(t *testing.T) { + for _, operation := range []struct { + name string + request identityRequest + }{ + { + name: "register", + request: identityRequest{ + method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent), + headers: map[string]string{"Idempotency-Key": testIdempotencyKey}, + }, + }, + { + name: "resend", + request: identityRequest{method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`}, + }, + } { + for _, originCase := range []struct { + name string + origins []string + headers map[string]string + }{ + {name: "missing"}, + {name: "null origin", origins: []string{"null"}}, + {name: "foreign origin", origins: []string{"https://attacker.example"}}, + {name: "duplicate origin", origins: []string{identityTestOrigin, "https://attacker.example"}}, + {name: "forwarded host only", headers: map[string]string{"X-Forwarded-Host": "app.example"}}, + } { + t.Run(operation.name+"/"+originCase.name, func(t *testing.T) { + registration := &scriptedRegistration{} + request := operation.request + request.headers = cloneHeaders(request.headers) + for name, value := range originCase.headers { + request.headers[name] = value + } + response := serveIdentityRequestWithOrigins(t, newIdentityRouter(t, registration), request, originCase.origins) + requireProblem(t, response, http.StatusForbidden, api.ProblemCodeCsrfCheckFailed) + if registration.calls != 0 { + t.Fatalf("identity usecase calls = %d, want zero before origin check", registration.calls) + } + }) + } + } +} + +func serveIdentityRequestWithOrigins( + t *testing.T, + router http.Handler, + identityRequest identityRequest, + origins []string, +) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(identityRequest.method, identityRequest.path, strings.NewReader(identityRequest.body)) + if identityRequest.body != "" { + request.Header.Set("Content-Type", "application/json") + } + for name, value := range identityRequest.headers { + request.Header.Set(name, value) + } + for _, origin := range origins { + request.Header.Add("Origin", origin) + } + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + return response +} + +func cloneHeaders(headers map[string]string) map[string]string { + cloned := make(map[string]string, len(headers)) + for name, value := range headers { + cloned[name] = value + } + return cloned +} diff --git a/backend/internal/adapter/primary/http/router.go b/backend/internal/adapter/primary/http/router.go index 2b7cff7..400a53c 100644 --- a/backend/internal/adapter/primary/http/router.go +++ b/backend/internal/adapter/primary/http/router.go @@ -61,8 +61,9 @@ func NewRouter( // The client address is resolved once, through the trusted proxies only, // for the per-client rate limits of the handlers. router.Use(httpmiddleware.ClientIP(trustedProxies)) - // Login and logout compare one Origin header value exactly with the - // configured public origin. Session metadata never trusts forwarded headers. + // Unsafe public identity operations and session CSRF checks compare one + // Origin header value exactly with the configured public origin. Session + // metadata never trusts forwarded headers. router.Use(httpmiddleware.SessionRequestMetadata()) router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath)) router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute)) diff --git a/backend/internal/adapter/primary/http/security_contract_test.go b/backend/internal/adapter/primary/http/security_contract_test.go index 624b603..acd16f5 100644 --- a/backend/internal/adapter/primary/http/security_contract_test.go +++ b/backend/internal/adapter/primary/http/security_contract_test.go @@ -18,6 +18,39 @@ const ( sessionCSRFScheme = "sessionCsrf" ) +func TestProtectedContractOperationsRequireSessionCookie(t *testing.T) { + data, err := os.ReadFile(publicContractBundle) + if err != nil { + t.Fatalf("read the public contract bundle: %v", err) + } + spec, err := ogen.Parse(data) + if err != nil { + t.Fatalf("parse the public contract bundle: %v", err) + } + + checked := 0 + for path, item := range spec.Paths { + for method, operation := range contractOperations(item) { + requirements := operation.Security + if requirements == nil { + requirements = spec.Security + } + if len(requirements) == 0 { + continue + } + checked++ + for _, requirement := range requirements { + if _, usesSession := requirement[sessionCookieScheme]; !usesSession { + t.Errorf("%s %s (%s) is protected without %s", method, path, operation.OperationID, sessionCookieScheme) + } + } + } + } + if checked == 0 { + t.Fatal("found no protected operation; the check would pass vacuously") + } +} + // A browser sends the session cookie with every same-site request, so an // unsafe operation that accepts the session must also demand the // session-bound CSRF token. A new operation that forgets sessionCsrf would @@ -78,3 +111,25 @@ func unsafeOperations(item *ogen.PathItem) map[string]*ogen.Operation { } return operations } + +func contractOperations(item *ogen.PathItem) map[string]*ogen.Operation { + operations := map[string]*ogen.Operation{ + http.MethodGet: item.Get, + http.MethodHead: item.Head, + http.MethodPost: item.Post, + http.MethodPut: item.Put, + http.MethodPatch: item.Patch, + http.MethodDelete: item.Delete, + http.MethodOptions: item.Options, + http.MethodTrace: item.Trace, + } + for method, operation := range item.AdditionalOperations { + operations[method] = operation + } + for method, operation := range operations { + if operation == nil { + delete(operations, method) + } + } + return operations +} diff --git a/backend/internal/adapter/primary/http/v1/handler_test.go b/backend/internal/adapter/primary/http/v1/api_test.go similarity index 100% rename from backend/internal/adapter/primary/http/v1/handler_test.go rename to backend/internal/adapter/primary/http/v1/api_test.go diff --git a/backend/internal/adapter/primary/http/v1/auth.go b/backend/internal/adapter/primary/http/v1/auth.go index c0af2b1..85db3b4 100644 --- a/backend/internal/adapter/primary/http/v1/auth.go +++ b/backend/internal/adapter/primary/http/v1/auth.go @@ -5,7 +5,6 @@ import ( "errors" "math" "net/http" - "strings" "time" "lincodex/backend/internal/adapter/primary/http/api" @@ -73,6 +72,9 @@ func (handler *IdentityHandler) RegisterAccount( request *api.RegistrationRequest, params api.RegisterAccountParams, ) (api.RegisterAccountRes, error) { + if !originAllowed(ctx, handler.publicOrigin) { + return (*api.RegisterAccountForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil + } err := handler.registration.Register(ctx, identity.RegisterCommand{ IdempotencyKey: params.IdempotencyKey, Email: string(request.Email), @@ -99,6 +101,9 @@ func (handler *IdentityHandler) ResendEmailVerification( ctx context.Context, request *api.EmailVerificationResendRequest, ) (api.ResendEmailVerificationRes, error) { + if !originAllowed(ctx, handler.publicOrigin) { + return (*api.ResendEmailVerificationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil + } if handler.registration == nil { return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured") } @@ -121,13 +126,12 @@ func (handler *IdentityHandler) ResendEmailVerification( func (handler *IdentityHandler) ConfirmEmail( ctx context.Context, request *api.EmailVerificationRequest, - params api.ConfirmEmailParams, + _ api.ConfirmEmailParams, ) (api.ConfirmEmailRes, error) { if handler.confirmation == nil { return nil, errors.New("IdentityHandler.ConfirmEmail - confirmation is not configured") } - origin, ok := params.Origin.Get() - if !ok || strings.TrimSpace(origin) == "" || origin != handler.confirmationOrigin { + if !originAllowed(ctx, handler.publicOrigin) { return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil } @@ -155,7 +159,7 @@ func (handler *IdentityHandler) ConfirmEmail( } func (handler *IdentityHandler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) { - if !originAllowed(ctx, handler.sessionOrigin) { + if !originAllowed(ctx, handler.publicOrigin) { return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil } result, err := handler.sessions.Login(ctx, identity.LoginCommand{ @@ -254,8 +258,11 @@ func wholeSeconds(wait time.Duration) int32 { } func originAllowed(ctx context.Context, expected string) bool { + if expected == "" { + return false + } origin, ok := httpmiddleware.RequestOrigin(ctx) - return ok && origin == expected + return ok && origin != "" && origin == expected } func unauthenticatedProblemResponse(ctx context.Context) *api.Problem { diff --git a/backend/internal/adapter/primary/http/v1/identity.go b/backend/internal/adapter/primary/http/v1/identity.go index 95f6996..28a42bd 100644 --- a/backend/internal/adapter/primary/http/v1/identity.go +++ b/backend/internal/adapter/primary/http/v1/identity.go @@ -23,11 +23,10 @@ type IdentityHandlerOption func(*IdentityHandler) // IdentityHandler serves authentication and account identity operations. type IdentityHandler struct { - registration AccountRegistration - confirmation EmailConfirmation - confirmationOrigin string - sessions *identity.SessionService - sessionOrigin string + registration AccountRegistration + confirmation EmailConfirmation + sessions *identity.SessionService + publicOrigin string } func NewIdentityHandler(registration AccountRegistration, options ...IdentityHandlerOption) *IdentityHandler { @@ -38,21 +37,26 @@ func NewIdentityHandler(registration AccountRegistration, options ...IdentityHan return handler } -// WithEmailConfirmation serves ConfirmEmail and compares Origin with the -// configured public application origin. The request Host is never trusted. -func WithEmailConfirmation(confirmation EmailConfirmation, publicOrigin string) IdentityHandlerOption { +// WithEmailConfirmation serves ConfirmEmail. The configured public origin is +// supplied once with WithPublicOrigin; the request Host is never trusted. +func WithEmailConfirmation(confirmation EmailConfirmation) IdentityHandlerOption { return func(handler *IdentityHandler) { handler.confirmation = confirmation - handler.confirmationOrigin = publicOrigin } } // WithSessionService serves login, current account, current session, and -// logout against PostgreSQL-backed sessions. Unsafe browser operations compare -// Origin exactly with the configured public origin. -func WithSessionService(sessions *identity.SessionService, publicOrigin string) IdentityHandlerOption { +// logout against PostgreSQL-backed sessions. +func WithSessionService(sessions *identity.SessionService) IdentityHandlerOption { return func(handler *IdentityHandler) { handler.sessions = sessions - handler.sessionOrigin = publicOrigin + } +} + +// WithPublicOrigin configures the exact browser Origin accepted by unsafe +// public identity operations and session CSRF checks. +func WithPublicOrigin(publicOrigin string) IdentityHandlerOption { + return func(handler *IdentityHandler) { + handler.publicOrigin = publicOrigin } } diff --git a/backend/internal/adapter/primary/http/v1/principal.go b/backend/internal/adapter/primary/http/v1/principal.go index b61577d..12d294e 100644 --- a/backend/internal/adapter/primary/http/v1/principal.go +++ b/backend/internal/adapter/primary/http/v1/principal.go @@ -36,18 +36,23 @@ func PrincipalFromContext(ctx context.Context) (Principal, bool) { return Principal{}, false } principal, ok := ctx.Value(principalContextKey{}).(Principal) - return principal, ok && principal.UserID != uuid.Nil + return principal, ok && principal.UserID != uuid.Nil && principal.EmailVerified } -func withAuthenticatedSession(ctx context.Context, session identity.AuthenticatedSession) context.Context { +func withAuthenticatedSession(ctx context.Context, session identity.AuthenticatedSession) (context.Context, bool) { + if ctx == nil || session.User.ID == uuid.Nil || session.SessionID == uuid.Nil || + !session.User.EmailVerified() || session.CSRFToken == "" { + return ctx, false + } principal := Principal{UserID: session.User.ID, EmailVerified: session.User.EmailVerified()} ctx = context.WithValue(ctx, principalContextKey{}, principal) - return context.WithValue(ctx, sessionContextKey{}, authenticatedSession{ + ctx = context.WithValue(ctx, sessionContextKey{}, authenticatedSession{ Principal: principal, User: session.User, SessionID: session.SessionID, CSRFToken: session.CSRFToken, }) + return ctx, true } func sessionFromContext(ctx context.Context) (authenticatedSession, bool) { @@ -55,5 +60,6 @@ func sessionFromContext(ctx context.Context) (authenticatedSession, bool) { return authenticatedSession{}, false } session, ok := ctx.Value(sessionContextKey{}).(authenticatedSession) - return session, ok && session.UserID != uuid.Nil && session.SessionID != uuid.Nil + return session, ok && session.UserID != uuid.Nil && session.SessionID != uuid.Nil && + session.EmailVerified && session.CSRFToken != "" } diff --git a/backend/internal/adapter/primary/http/v1/security.go b/backend/internal/adapter/primary/http/v1/security.go index 61f8a4a..86f791c 100644 --- a/backend/internal/adapter/primary/http/v1/security.go +++ b/backend/internal/adapter/primary/http/v1/security.go @@ -7,21 +7,15 @@ import ( "lincodex/backend/internal/adapter/primary/http/api" ) -// errSessionsNotImplemented rejects every session-protected request until the -// session boundary exists. Its text stays in the server: the generated server -// wraps it in *ogenerrors.SecurityError, which the problem responder answers -// with a fixed 401 unauthenticated problem. +// errSessionsNotImplemented is used by DenyAllSecurity, a test helper. Its text +// stays in the server and maps to a fixed 401 unauthenticated problem. var errSessionsNotImplemented = errors.New("v1.DenyAllSecurity - sessions are not implemented") // DenyAllSecurity implements api.SecurityHandler by rejecting every session -// cookie and CSRF token, so no operation that requires a session is reachable -// before server sessions exist. Operations that declare `security: []` do not -// call it and keep their own behavior, which is 501 not_implemented until -// their business logic exists. -// -// Session authentication will replace it. The generated server (ogen v1.24.0) evaluates the -// schemes of an operation as follows; TestGeneratedServerSecurityOrder pins -// the order and the context propagation: +// cookie and CSRF token. Production bootstrap uses SessionSecurity instead; +// tests use this helper when they need to verify a denied session. The +// generated server evaluates schemes in type-name order. The contract test +// pins the order and context propagation: // // - It evaluates sessionCookie before sessionCsrf, in the order of the // generated type names, and each step receives the context returned by @@ -41,7 +35,7 @@ var errSessionsNotImplemented = errors.New("v1.DenyAllSecurity - sessions are no // ogenerrors.ErrSecurityRequirementIsNotSatisfied}, without a Security // field, to Handler.NewError with the context of the last successful step. // -// The intended mapping on top of that behavior: +// SessionSecurity and Handler.NewError implement this mapping on top of that behavior: // // - HandleSessionCookie returns a context with the principal for a valid // session and ogenerrors.ErrSkipServerSecurity for a missing, unknown, diff --git a/backend/internal/adapter/primary/http/v1/session.go b/backend/internal/adapter/primary/http/v1/session.go index fb5daa2..60319a1 100644 --- a/backend/internal/adapter/primary/http/v1/session.go +++ b/backend/internal/adapter/primary/http/v1/session.go @@ -19,9 +19,8 @@ type SessionAuthenticator interface { Authenticate(ctx context.Context, rawToken string) (identity.AuthenticatedSession, error) } -// SessionSecurity authenticates only the three session operations enabled in -// this implementation. All other protected operations remain unavailable until their -// handlers are implemented. +// SessionSecurity authenticates every operation protected by the public +// contract's session schemes. Business handlers may still be unimplemented. type SessionSecurity struct { authenticator SessionAuthenticator publicOrigin string @@ -37,15 +36,15 @@ func (handler *IdentityHandler) SessionSecurity() *SessionSecurity { if handler == nil || handler.sessions == nil { return NewSessionSecurity(nil, "") } - return NewSessionSecurity(handler.sessions, handler.sessionOrigin) + return NewSessionSecurity(handler.sessions, handler.publicOrigin) } func (security *SessionSecurity) HandleSessionCookie( ctx context.Context, - operation api.OperationName, + _ api.OperationName, cookie api.SessionCookie, ) (context.Context, error) { - if !sessionOperationAllowed(operation) || security == nil || security.authenticator == nil || + if security == nil || security.authenticator == nil || !httpmiddleware.SessionCookieMatches(ctx, cookie.APIKey) { return ctx, ogenerrors.ErrSkipServerSecurity } @@ -56,34 +55,26 @@ func (security *SessionSecurity) HandleSessionCookie( if err != nil { return ctx, fmt.Errorf("SessionSecurity.HandleSessionCookie - authenticate session: %w", err) } - return withAuthenticatedSession(ctx, authenticated), nil + ctx, ok := withAuthenticatedSession(ctx, authenticated) + if !ok { + return ctx, ogenerrors.ErrSkipServerSecurity + } + return ctx, nil } func (security *SessionSecurity) HandleSessionCsrf( ctx context.Context, - operation api.OperationName, + _ api.OperationName, csrf api.SessionCsrf, ) (context.Context, error) { - if operation != api.LogoutOperation { - return ctx, ogenerrors.ErrSkipServerSecurity - } authenticated, ok := sessionFromContext(ctx) if !ok { return ctx, ogenerrors.ErrSkipServerSecurity } origin, hasOrigin := httpmiddleware.RequestOrigin(ctx) - if security == nil || !hasOrigin || origin != security.publicOrigin || authenticated.CSRFToken == "" || + if security == nil || security.publicOrigin == "" || !hasOrigin || origin != security.publicOrigin || !hmac.Equal([]byte(authenticated.CSRFToken), []byte(csrf.APIKey)) { return ctx, errCsrfCheckFailed } return ctx, nil } - -func sessionOperationAllowed(operation api.OperationName) bool { - switch operation { - case api.GetCurrentSessionOperation, api.GetCurrentAccountOperation, api.LogoutOperation: - return true - default: - return false - } -} diff --git a/backend/internal/adapter/primary/http/v1/session_test.go b/backend/internal/adapter/primary/http/v1/session_test.go index 2491252..fa27df0 100644 --- a/backend/internal/adapter/primary/http/v1/session_test.go +++ b/backend/internal/adapter/primary/http/v1/session_test.go @@ -31,7 +31,7 @@ func (authenticator *sessionAuthenticatorStub) Authenticate(_ context.Context, _ return authenticator.result, authenticator.err } -func TestSessionSecurityAddsPrincipalOnlyForTheThreeEnabledOperations(t *testing.T) { +func TestSessionSecurityAddsVerifiedPrincipalForEveryProtectedOperationClass(t *testing.T) { token, err := domain.NewSecretToken() if err != nil { t.Fatal(err) @@ -48,6 +48,8 @@ func TestSessionSecurityAddsPrincipalOnlyForTheThreeEnabledOperations(t *testing for _, operation := range []api.OperationName{ api.GetCurrentAccountOperation, api.GetCurrentSessionOperation, + api.GetMyProfileOperation, + api.CreateOrganizationOperation, api.LogoutOperation, } { ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com") @@ -60,18 +62,12 @@ func TestSessionSecurityAddsPrincipalOnlyForTheThreeEnabledOperations(t *testing t.Fatalf("PrincipalFromContext(%s) = %+v, %v", operation, principal, ok) } } - if authenticator.calls != 3 { - t.Fatalf("authentication calls = %d, want one for each allowed operation", authenticator.calls) - } - - ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com") - _, err = security.HandleSessionCookie(ctx, api.GetMyProfileOperation, api.SessionCookie{APIKey: token.Reveal()}) - if !errors.Is(err, ogenerrors.ErrSkipServerSecurity) || authenticator.calls != 3 { - t.Fatalf("disallowed operation error=%v authentication calls=%d", err, authenticator.calls) + if authenticator.calls != 5 { + t.Fatalf("authentication calls = %d, want one for each protected operation class", authenticator.calls) } } -func TestLogoutRequiresExactOriginAndSessionBoundCSRF(t *testing.T) { +func TestSessionCsrfRequiresExactOriginForAnyContractOperation(t *testing.T) { token, err := domain.NewSecretToken() if err != nil { t.Fatal(err) @@ -97,11 +93,11 @@ func TestLogoutRequiresExactOriginAndSessionBoundCSRF(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { ctx := sessionRequestContext(t, token.Reveal(), test.origin) - ctx, err := security.HandleSessionCookie(ctx, api.LogoutOperation, api.SessionCookie{APIKey: token.Reveal()}) + ctx, err := security.HandleSessionCookie(ctx, api.CreateOrganizationOperation, api.SessionCookie{APIKey: token.Reveal()}) if err != nil { t.Fatalf("HandleSessionCookie() error = %v", err) } - _, err = security.HandleSessionCsrf(ctx, api.LogoutOperation, api.SessionCsrf{APIKey: test.csrf}) + _, err = security.HandleSessionCsrf(ctx, api.CreateOrganizationOperation, api.SessionCsrf{APIKey: test.csrf}) if !errors.Is(err, test.wantErr) { t.Fatalf("HandleSessionCsrf() error = %v, want %v", err, test.wantErr) } @@ -109,6 +105,41 @@ func TestLogoutRequiresExactOriginAndSessionBoundCSRF(t *testing.T) { } } +func TestSessionSecurityRejectsInvalidAuthenticatedSession(t *testing.T) { + token, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + verifiedAt := time.Now() + valid := identity.AuthenticatedSession{ + User: domain.User{ID: uuid.New(), EmailVerifiedAt: &verifiedAt}, + SessionID: uuid.New(), + CSRFToken: "csrf-for-this-session", + } + for _, test := range []struct { + name string + result identity.AuthenticatedSession + }{ + {name: "unverified account", result: identity.AuthenticatedSession{User: domain.User{ID: valid.User.ID}, SessionID: valid.SessionID, CSRFToken: valid.CSRFToken}}, + {name: "missing user ID", result: identity.AuthenticatedSession{User: domain.User{EmailVerifiedAt: &verifiedAt}, SessionID: valid.SessionID, CSRFToken: valid.CSRFToken}}, + {name: "missing session ID", result: identity.AuthenticatedSession{User: valid.User, CSRFToken: valid.CSRFToken}}, + {name: "missing CSRF token", result: identity.AuthenticatedSession{User: valid.User, SessionID: valid.SessionID}}, + } { + t.Run(test.name, func(t *testing.T) { + authenticator := &sessionAuthenticatorStub{result: test.result} + security := NewSessionSecurity(authenticator, "https://app.example.com") + ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com") + authenticated, err := security.HandleSessionCookie(ctx, api.GetMyProfileOperation, api.SessionCookie{APIKey: token.Reveal()}) + if !errors.Is(err, ogenerrors.ErrSkipServerSecurity) { + t.Fatalf("HandleSessionCookie() error = %v, want skipped authentication", err) + } + if _, ok := PrincipalFromContext(authenticated); ok { + t.Fatal("invalid authenticated session installed a principal") + } + }) + } +} + func TestSecurityErrorsMapToUnauthenticatedOrCSRFProblem(t *testing.T) { logger := slog.New(slog.NewTextHandler(&strings.Builder{}, nil)) handler := NewHandler(nil, problem.NewResponder(logger)) diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go index b5a9509..6800cea 100644 --- a/backend/internal/bootstrap/identity.go +++ b/backend/internal/bootstrap/identity.go @@ -133,8 +133,9 @@ func newIdentityHandler( // The HTTP server stops before this cleanup runs, so no request uses the // pool while it closes. return v1.NewIdentityHandler(registration, - v1.WithEmailConfirmation(confirmation, settings.AppPublicURL), - v1.WithSessionService(sessions, settings.AppPublicURL), + v1.WithEmailConfirmation(confirmation), + v1.WithSessionService(sessions), + v1.WithPublicOrigin(settings.AppPublicURL), ), pool.Close, nil } diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 2426c13..18ae04c 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -540,7 +540,7 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate. Outside the implemented identity and consent flows, domain types and usecases for other product workflows are not implemented. SMTP and FSP adapters, and product worker jobs, remain planned. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature. -This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for a limited set of session operations, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. +This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, confirmation, and login, PostgreSQL sessions and a security boundary for every operation protected by the API contract, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration, confirmation, and login, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Profiles, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists. `backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/`: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`. @@ -691,7 +691,7 @@ Implemented and tested: registration and login use the hasher created from confi ### Server-side sessions -Login, reading the current session, and logout are implemented in the backend. Login requires the sole `Origin` value to exactly match `APP_PUBLIC_URL`; logout checks the same Origin and a session-bound `X-CSRF-Token`. Origin is checked at the HTTP boundary and does not trust `Host` or arbitrary forwarded headers. The CSRF value is a domain-separated HMAC-SHA-256 derived from the session token, bound to that token, and compared in constant time. `GetCurrentSession` returns it again after a page reload. GET `/api/v1/identity/sessions/current` returns the current session and account, GET `/api/v1/identity/me` returns the current account, and DELETE `/api/v1/identity/sessions/current` revokes the session. These are the only OpenAPI operations currently allowed through the session security boundary; all other protected operations remain denied even with a valid cookie. +Login, current-session and current-account reads, and logout are implemented in the backend. Every contract-protected operation passes through the session boundary, which resolves a verified principal from an active PostgreSQL session; other protected business handlers currently answer 501 after security and request validation. Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires the sole `Origin` value to exactly match `APP_PUBLIC_URL`. Protected unsafe operations also require the session-bound `X-CSRF-Token`. Origin is checked at the HTTP boundary and does not trust `Host` or forwarded headers. The CSRF value is a domain-separated HMAC-SHA-256 derived from the session token, bound to that token, and compared in constant time. `GetCurrentSession` returns it again after a page reload. GET `/api/v1/identity/sessions/current` returns the current session and account, GET `/api/v1/identity/me` returns the current account, and DELETE `/api/v1/identity/sessions/current` revokes the session. Guests and unverified sessions answer 401; a valid session with missing or wrong Origin or CSRF on a protected unsafe operation answers 403 `csrf_check_failed`. The cookie is named `__Host-lincodex_session` and has `Path=/`, `Secure`, `HttpOnly`, and `SameSite=Strict`, with no `Domain`; `Expires` and `Max-Age` point to the absolute session expiry. PostgreSQL stores only the SHA-256 hash of the random cookie token, never its value; IP addresses and user agents are not stored. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` and accepts `1m` to `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` and accepts `1m` to `365d`. The idle timeout cannot exceed the absolute lifetime; invalid values stop startup. Active requests extend the idle deadline, not the absolute deadline. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index d967b37..dc43fc8 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -249,7 +249,7 @@ Release compatibility: `ConfirmEmail` requires both `token` and the password sel | `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt | | `EMAIL_QUOTA_DAILY` | `100` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC day through the configured provider account: an integer from 1 to 1000000000. Empty counts as unset. No value turns the quota off. | | `EMAIL_QUOTA_MONTHLY` | `3000` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC calendar month: an integer from 1 to 1000000000, not below `EMAIL_QUOTA_DAILY`. Empty counts as unset. | -| `APP_PUBLIC_URL` | none, required | Public origin for mail links and the Origin of confirmation requests: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. | +| `APP_PUBLIC_URL` | none, required | Public origin for mail links and exact Origin checks on unsafe public identity and protected operations: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. | | `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. | | `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. | | `SMTP_PORT` | empty | Required for `smtp`. Integer from 1 to 65535. | @@ -378,9 +378,9 @@ All names and addresses come from `deploy/edge/edge.env` (copy `deploy/edge/edge ### One origin and the Secure cookie -The browser sees only `https://`. The SPA and `/api` come from the same origin: the edge forwards every path unchanged, and the frontend container serves the SPA with its `try_files ... /index.html` fallback, so a deep link such as `/some/deep/link` returns the SPA, and proxies `/api/` to Go. The backend issues the `__Host-lincodex_session` cookie with `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict`, and no `Domain`; `Expires` and `Max-Age` match the absolute session expiry. The edge keeps `Host` as the public name and sets `X-Forwarded-Proto: https`; the frontend container's Nginx keeps that value for the backend (`$forwarded_proto` in `deploy/nginx/conf.d/app.conf`) and otherwise reports its own scheme. `APP_PUBLIC_URL` in the app host `.env` must be `https://`. Login and logout require the sole `Origin` value to exactly match `APP_PUBLIC_URL`; the backend does not derive the allowed origin from `Host` or trust forwarded headers for this check. +The browser sees only `https://`. The SPA and `/api` come from the same origin: the edge forwards every path unchanged, and the frontend container serves the SPA with its `try_files ... /index.html` fallback, so a deep link such as `/some/deep/link` returns the SPA, and proxies `/api/` to Go. The backend issues the `__Host-lincodex_session` cookie with `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict`, and no `Domain`; `Expires` and `Max-Age` match the absolute session expiry. The edge keeps `Host` as the public name and sets `X-Forwarded-Proto: https`; the frontend container's Nginx keeps that value for the backend (`$forwarded_proto` in `deploy/nginx/conf.d/app.conf`) and otherwise reports its own scheme. `APP_PUBLIC_URL` in the app host `.env` must be `https://`. Unsafe public identity operations and protected unsafe operations require the sole `Origin` value to exactly match `APP_PUBLIC_URL`; protected unsafe operations also require a CSRF token bound to the session cookie. The backend does not derive the allowed origin from `Host` or trust forwarded headers for this check. -Registration, verification resend, email confirmation, login, current-session reading, and logout are available through the backend API. Frontend registration and confirmation screens remain placeholders, and the backend does not read `X-Forwarded-Proto` for the Origin check. The browser login path through the edge has not been verified end to end. +Registration, verification resend, email confirmation, login, current-session reading, and logout are available through the backend API. Protected contract operations authenticate a verified account session; operations without business handlers still return 501 after the security boundary passes. Frontend registration and confirmation screens remain placeholders, and the backend does not read `X-Forwarded-Proto` for the Origin check. The browser login path through the edge has not been verified end to end. ### Request handling at the edge diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index fa6e3dc..a0df5ad 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -540,7 +540,7 @@ backend/ За пределами реализованных потоков identity и согласий доменные типы и usecase других продуктовых сценариев пока не реализованы. Адаптеры SMTP и FSP, а также продуктовые задания worker остаются планом. `main.go` запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация. -Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и проверку ограниченного набора операций сессии, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. +Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки, подтверждения и входа identity, PostgreSQL сессии и security boundary для всех операций, защищенных API-контрактом, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации, подтверждении и входе, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Профили, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей. `backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; `ServiceMailer` создает письма подтверждения при регистрации и повторной отправке. Письма сброса пароля относятся к будущему потоку сброса. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`. @@ -762,7 +762,7 @@ contact_grant относится к паре кандидат-компания ### Серверные сессии -Вход, чтение текущей сессии и выход реализованы на backend. Login требует единственный `Origin`, точно равный `APP_PUBLIC_URL`; logout проверяет тот же Origin и session-bound `X-CSRF-Token`. Проверка Origin выполняется на HTTP boundary и не доверяет `Host` или произвольным forwarded headers. Токен CSRF выводится через domain-separated HMAC-SHA-256 с ключом из `IDENTITY_KEY_SECRET`, связан с конкретным session token и сравнивается за постоянное время. `GetCurrentSession` возвращает CSRF-токен снова после перезагрузки страницы. GET `/api/v1/identity/sessions/current` возвращает сессию с аккаунтом, GET `/api/v1/identity/me` - текущий аккаунт, DELETE `/api/v1/identity/sessions/current` отзывает сессию. Это единственные OpenAPI operations, которым текущая HTTP security boundary разрешает session principal; остальные защищенные operations остаются закрытыми даже при валидной cookie. +Вход, чтение текущей сессии и аккаунта, выход реализованы на backend. Каждая защищенная контрактом операция проходит session boundary, которая создает verified principal из действующей PostgreSQL-сессии; для остальных защищенных business handlers пока возвращается 501 после security и проверки запроса. Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`) требует единственный `Origin`, точно равный `APP_PUBLIC_URL`. Защищенные небезопасные операции также требуют session-bound `X-CSRF-Token`. Проверка Origin выполняется на HTTP boundary и не доверяет `Host` или forwarded headers. Токен CSRF выводится через domain-separated HMAC-SHA-256 с ключом из `IDENTITY_KEY_SECRET`, связан с конкретным session token и сравнивается за постоянное время. `GetCurrentSession` возвращает CSRF-токен снова после перезагрузки страницы. GET `/api/v1/identity/sessions/current` возвращает сессию с аккаунтом, GET `/api/v1/identity/me` - текущий аккаунт, DELETE `/api/v1/identity/sessions/current` отзывает сессию. Гость и неподтвержденная сессия получают 401; при валидной сессии неверный или отсутствующий Origin либо CSRF на защищенной небезопасной операции отвечает 403 `csrf_check_failed`. Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict`, без `Domain`; `Expires` и `Max-Age` указывают на абсолютное завершение сессии. В PostgreSQL сохраняется только SHA-256 хеш случайного cookie token, а не его значение; IP и user agent не сохраняются. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h`, принимает от `1m` до `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h`, принимает от `1m` до `365d`. Таймаут простоя не может превышать абсолютный срок; неверные значения останавливают запуск. Активный запрос продлевает срок простоя, но не абсолютный срок. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 76b3d59..adea3ba 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -251,7 +251,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL | `EMAIL_TIMEOUT` | `10s` | Go duration от `1s` до `1m`; ограничивает одну попытку транспорта | | `EMAIL_QUOTA_DAILY` | `100` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за UTC-сутки через настроенный аккаунт провайдера: целое от 1 до 1000000000. Пустое значение считается незаданным. Значения, которое отключает квоту, нет. | | `EMAIL_QUOTA_MONTHLY` | `3000` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за календарный месяц UTC: целое от 1 до 1000000000, не меньше `EMAIL_QUOTA_DAILY`. Пустое значение считается незаданным. | -| `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах и Origin запроса подтверждения: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. | +| `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах и точной проверки Origin у небезопасных публичных identity-операций и защищенных операций: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. | | `RESEND_API_KEY` | пусто | Читается только для `resend` и там обязательна. Печатные ASCII символы без пробелов. Префикс `re_` из примеров Resend не проверяется. | | `SMTP_HOST` | пусто | Читается только для `smtp` и там обязательна. Имя хоста или IP адрес без порта. | | `SMTP_PORT` | пусто | Обязательна для `smtp`. Целое число от 1 до 65535. | @@ -380,9 +380,9 @@ Edge-хост общий с другими сервисами. Здесь все ### Один origin и Secure cookie -Браузер видит только `https://`. SPA и `/api` приходят с одного origin: edge пересылает каждый путь без изменений, а frontend контейнер отдает SPA с запасным вариантом `try_files ... /index.html`, поэтому глубокая ссылка вроде `/some/deep/link` возвращает SPA, и проксирует `/api/` в Go. Backend выдает cookie `__Host-lincodex_session` с `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict` и без `Domain`; `Expires` и `Max-Age` равны абсолютному сроку сессии. Edge сохраняет `Host` как публичное имя и ставит `X-Forwarded-Proto: https`; Nginx frontend контейнера сохраняет это значение для backend (`$forwarded_proto` в `deploy/nginx/conf.d/app.conf`), а иначе сообщает собственную схему. `APP_PUBLIC_URL` в `.env` app-хоста должен быть `https://`. Вход и выход требуют единственный `Origin`, точно равный `APP_PUBLIC_URL`; backend не выводит разрешенный origin из `Host` и не доверяет forwarded headers для этой проверки. +Браузер видит только `https://`. SPA и `/api` приходят с одного origin: edge пересылает каждый путь без изменений, а frontend контейнер отдает SPA с запасным вариантом `try_files ... /index.html`, поэтому глубокая ссылка вроде `/some/deep/link` возвращает SPA, и проксирует `/api/` в Go. Backend выдает cookie `__Host-lincodex_session` с `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict` и без `Domain`; `Expires` и `Max-Age` равны абсолютному сроку сессии. Edge сохраняет `Host` как публичное имя и ставит `X-Forwarded-Proto: https`; Nginx frontend контейнера сохраняет это значение для backend (`$forwarded_proto` в `deploy/nginx/conf.d/app.conf`), а иначе сообщает собственную схему. `APP_PUBLIC_URL` в `.env` app-хоста должен быть `https://`. Небезопасные публичные identity-операции и защищенные небезопасные операции требуют единственный `Origin`, точно равный `APP_PUBLIC_URL`; защищенные небезопасные операции также требуют CSRF-токен, связанный с cookie сессии. Backend не выводит разрешенный origin из `Host` и не доверяет forwarded headers для этой проверки. -Регистрация, повторная отправка подтверждения, подтверждение email, вход, чтение текущей сессии и выход доступны через backend API. Экраны регистрации и подтверждения во frontend остаются заглушками, а backend не читает `X-Forwarded-Proto` для проверки origin. Браузерный путь входа через edge не проверен end to end. +Регистрация, повторная отправка подтверждения, подтверждение email, вход, чтение текущей сессии и выход доступны через backend API. Защищенные операции API требуют сессию подтвержденного аккаунта; операции без бизнес-обработчика после успешной проверки границы безопасности возвращают 501. Экраны регистрации и подтверждения во frontend остаются заглушками, а backend не читает `X-Forwarded-Proto` для проверки origin. Браузерный путь входа через edge не проверен end to end. ### Обработка запросов на edge