feat(identity): enforce shared session and browser request security

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 11:33:40 +03:00
1 parent 7df521bd89
commit 86f562f5b6
23 files changed
+430 -121

No files matched your search

+2 -2
View File
@@ -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.
+3 -3
View File
@@ -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://<EDGE_DOMAIN>`. 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://<EDGE_DOMAIN>`. 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://<EDGE_DOMAIN>`. 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://<EDGE_DOMAIN>`. 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
+2 -2
View File
@@ -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`. Таймаут простоя не может превышать абсолютный срок; неверные значения останавливают запуск. Активный запрос продлевает срок простоя, но не абсолютный срок.
+3 -3
View File
@@ -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://<EDGE_DOMAIN>`. 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://<EDGE_DOMAIN>`. Вход и выход требуют единственный `Origin`, точно равный `APP_PUBLIC_URL`; backend не выводит разрешенный origin из `Host` и не доверяет forwarded headers для этой проверки.
Браузер видит только `https://<EDGE_DOMAIN>`. 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://<EDGE_DOMAIN>`. Небезопасные публичные 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