From 4ee53d9a74876594e7560a170e030f44e83ad7f3 Mon Sep 17 00:00:00 2001 From: TakuyaYagam1 Date: Wed, 7 Oct 2026 11:03:46 +0300 Subject: [PATCH] feat(identity): add server sessions and audited mail recovery --- .env.example | 15 +- api/README.en.md | 20 +- api/README.md | 20 +- backend/Makefile | 8 + backend/README.en.md | 12 +- backend/README.md | 12 +- backend/cmd/mail-retry/main.go | 27 + backend/config/config.go | 15 +- backend/config/identity.go | 83 ++- backend/config/identity_test.go | 68 ++- .../migrations/00017_retry_unknown_mail.sql | 115 ++++ backend/db/queries/delivery.sql | 220 +++++++- .../mail_retry_migration_test.go | 72 +++ backend/integration_test/mail_sender_test.go | 399 +++++++++++++- .../registration_consent_migration_test.go | 57 +- backend/integration_test/session_http_test.go | 495 ++++++++++++++++++ .../adapter/primary/cli/mailretry/command.go | 196 +++++++ .../primary/cli/mailretry/command_test.go | 142 +++++ .../primary/http/middleware/session.go | 81 +++ .../primary/http/middleware/session_test.go | 96 ++++ .../internal/adapter/primary/http/router.go | 29 +- .../internal/adapter/primary/http/v1/api.go | 65 +++ .../internal/adapter/primary/http/v1/auth.go | 292 +++++++++++ .../adapter/primary/http/v1/handler.go | 98 ---- .../adapter/primary/http/v1/healthz.go | 4 + .../adapter/primary/http/v1/identity.go | 144 +---- .../adapter/primary/http/v1/principal.go | 59 +++ .../adapter/primary/http/v1/session.go | 89 ++++ .../adapter/primary/http/v1/session_test.go | 200 +++++++ .../internal/adapter/primary/http/v1/user.go | 37 ++ .../mail/resend/resendfixture/fixture.go | 116 +++- .../adapter/secondary/postgres/delivery.go | 141 ++++- .../adapter/secondary/postgres/identity.go | 8 +- .../secondary/postgres/sqlc/delivery.sql.go | 398 ++++++++++++-- .../adapter/secondary/postgres/sqlc/models.go | 21 + .../secondary/postgres/sqlc/querier.go | 41 +- backend/internal/bootstrap/identity.go | 48 +- backend/internal/bootstrap/wire.go | 8 +- backend/internal/bootstrap/wire_gen.go | 8 +- backend/internal/domain/delivery.go | 41 ++ backend/internal/domain/delivery_test.go | 43 ++ backend/internal/domain/mail_retry.go | 18 + backend/internal/port/outbound/delivery.go | 66 ++- .../internal/usecase/identity/credentials.go | 19 + .../usecase/identity/credentials_test.go | 17 +- backend/internal/usecase/identity/errors.go | 12 + backend/internal/usecase/identity/keyring.go | 28 + backend/internal/usecase/identity/session.go | 326 ++++++++++++ .../internal/usecase/identity/session_test.go | 445 ++++++++++++++++ .../notification/delivery_retry_operator.go | 130 +++++ .../delivery_retry_operator_test.go | 218 ++++++++ .../usecase/notification/service_sender.go | 198 ++++++- .../notification/service_sender_test.go | 225 +++++++- deploy/docker/docker-compose.yml | 5 +- docs/en/ARCHITECTURE.md | 68 +-- docs/en/DEPLOY.md | 22 +- docs/ru/ARCHITECTURE.md | 64 ++- docs/ru/DEPLOY.md | 22 +- 58 files changed, 5359 insertions(+), 567 deletions(-) create mode 100644 backend/cmd/mail-retry/main.go create mode 100644 backend/db/migrations/00017_retry_unknown_mail.sql create mode 100644 backend/integration_test/mail_retry_migration_test.go create mode 100644 backend/integration_test/session_http_test.go create mode 100644 backend/internal/adapter/primary/cli/mailretry/command.go create mode 100644 backend/internal/adapter/primary/cli/mailretry/command_test.go create mode 100644 backend/internal/adapter/primary/http/middleware/session.go create mode 100644 backend/internal/adapter/primary/http/middleware/session_test.go create mode 100644 backend/internal/adapter/primary/http/v1/api.go create mode 100644 backend/internal/adapter/primary/http/v1/auth.go delete mode 100644 backend/internal/adapter/primary/http/v1/handler.go create mode 100644 backend/internal/adapter/primary/http/v1/principal.go create mode 100644 backend/internal/adapter/primary/http/v1/session.go create mode 100644 backend/internal/adapter/primary/http/v1/session_test.go create mode 100644 backend/internal/adapter/primary/http/v1/user.go create mode 100644 backend/internal/domain/mail_retry.go create mode 100644 backend/internal/usecase/identity/session.go create mode 100644 backend/internal/usecase/identity/session_test.go create mode 100644 backend/internal/usecase/notification/delivery_retry_operator.go create mode 100644 backend/internal/usecase/notification/delivery_retry_operator_test.go diff --git a/.env.example b/.env.example index 2ff7f1b..31a8c9a 100644 --- a/.env.example +++ b/.env.example @@ -71,7 +71,8 @@ PASSWORD_HASH_CONCURRENCY=1 APP_SUBNET=172.29.79.0/24 APP_FRONTEND_IP=172.29.79.10 # Registration and email confirmation. IDENTITY_KEY_SECRET is required. It -# keys idempotency records and rate-limit counters across restarts and instances. +# keys idempotency records, rate-limit counters, and session CSRF tokens across +# restarts and instances. # Use at least 32 bytes. There is no usable example value: leave it empty here # and generate one for every deployment (Compose refuses an empty value): # openssl rand -base64 48 @@ -83,9 +84,17 @@ VERIFICATION_MAIL_MIN_INTERVAL=1m VERIFICATION_MAIL_DAILY_LIMIT=5 # Confirmation attempts are limited to 5 per token per hour by the service. # This token limit is fixed; it has no environment setting. -# IDENTITY_CLIENT_HOURLY_LIMIT applies to registration, resends, and -# confirmations per resolved client address per hour, when available. +# IDENTITY_CLIENT_HOURLY_LIMIT applies to registration, confirmation, resends, +# and login per resolved client address per hour, when available. IDENTITY_CLIENT_HOURLY_LIMIT=30 +# Login attempts are limited by the resolved client address and normalized +# email address. The email limit applies whether or not the account exists. +IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT=10 +# Sessions expire after this much inactivity or at the absolute lifetime, +# whichever comes first. Idle must not exceed absolute; idle is capped at 30d +# and absolute at 365d. +IDENTITY_SESSION_IDLE_TIMEOUT=24h +IDENTITY_SESSION_ABSOLUTE_LIFETIME=168h # Reverse proxies the backend trusts to report the client address in # X-Forwarded-For. Leave it unset: the default is the frontend container's diff --git a/api/README.en.md b/api/README.en.md index 9ea93f9..086335f 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`, and `ConfirmEmail` are implemented. Login still answers 501 `not_implemented`, and `v1.DenyAllSecurity` rejects every request to a protected operation with 401 `unauthenticated`. Frontend registration and confirmation screens remain placeholders, and login is not implemented. +The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. Session security allows only the last three protected operations; other operations that require a session remain closed with 401 `unauthenticated`. Frontend registration and confirmation screens remain placeholders. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -119,15 +119,15 @@ Every operation also declares the `default` problem response. Registration and verification: -- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login is not implemented yet, so its contract behavior of answering 401 `invalid_credentials` for both an unknown email and a wrong password is not available. +- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login answers the same 401 `invalid_credentials` for an unknown email, a wrong password, or an invalid stored hash; unknown emails and invalid hashes also receive extra Argon2id work. A correct password for an unverified account answers 403 `email_not_verified` and creates no session. - Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists. -- Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie. Login is not implemented. The planned login rule is that an unverified account cannot sign in. -- Implementation of registration and resend. Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). Limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). `ConfirmEmail` also limits each token to 5 attempts per hour and uses the same client limit. A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, and the limiter keys. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend). +- Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie; sign-in is a separate endpoint and requires a verified account. +- Implementation of registration, resend, and login. A verified address changes nothing and receives no message during registration (the "you already have an account" notice is not implemented). Mail limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours. `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour, range 1 to 10000) limits registration, confirmation, resend, and login per resolved client address. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour, range 1 to 10000) limits login by normalized email whether or not an account exists. `ConfirmEmail` also limits each token to 5 attempts per hour and uses the client limit. A refused request answers 429 `rate_limited` with `Retry-After`. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, the limiter keys, and session CSRF. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend). - Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions). - Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check. - `ConfirmEmail` takes both `token` and the `password` selected for that registration; clients that sent only a token must be updated. The password follows `LoginPassword`: NFKC normalization and 1 to 128 code points; the registration blocklist is not applied again. `Origin` must match `APP_PUBLIC_URL`; a missing Origin, the literal value null, or a foreign Origin answers 403 `csrf_check_failed`. Confirmation attempts are limited to 5 per token per hour and also use the shared `IDENTITY_CLIENT_HOURLY_LIMIT`; a refused attempt answers 429 `rate_limited` with `Retry-After`. - The verification link is `/verify-email#token=`. The frontend confirmation screen is still a placeholder. A client page must remove the fragment with `history.replaceState`, wait for an explicit user action, and post both token and registration password; a link scanner that only opens the page does not consume the token. -- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error, and can offer sign-in after login is implemented. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token. +- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error; after confirmation the user can sign in separately. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token. Consent C1 and the account: @@ -138,17 +138,17 @@ Consent C1 and the account: Sessions and CSRF: -- Planned session behavior: the `sessionCookie` scheme uses `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain; the server will keep sessions in PostgreSQL and identify the caller from the session. Once login is implemented, only a verified account will receive a session, and login will revoke the session from the request and issue a new identifier and CSRF token. Logout will revoke the session server-side. Policy timeouts are 24 hours idle and 7 days absolute; activity extends only the idle deadline. Configuration does not override these values. -- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the session-bound token from `Session.csrf_token`. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`. -- Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`). +- Implemented session operations: Login issues a `__Host-lincodex_session` cookie with `Path=/; Secure; HttpOnly; SameSite=Strict`, no Domain, and Expires/Max-Age at the absolute session deadline. PostgreSQL stores only the SHA-256 hash of the cookie token; the current-session GET returns the account and CSRF token after a reload. Successful login transactionally revokes an active session from the request and creates a new one; only a verified account can sign in. Logout revokes the session and clears the cookie; an expired or revoked cookie is also cleared on 401. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` (range `1m` to `30d`) and `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` (range `1m` to `365d`); idle cannot exceed absolute, and invalid values stop startup. Requests extend only the idle deadline. +- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the current session's token from `Session.csrf_token`. The backend derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, compares it in constant time, and does not store it in the database. All instances must share one `IDENTITY_KEY_SECRET` (at least 32 bytes), stable across restarts; changing it invalidates old CSRF values but does not revoke PostgreSQL sessions. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`. +- The contract requires the exact configured public Origin on every unsafe request, including public operations. The backend currently checks the sole `Origin` header against `APP_PUBLIC_URL` for `ConfirmEmail`, `Login`, and `Logout`; `Logout` also requires CSRF. `RegisterAccount` and `ResendEmailVerification` do not currently check Origin, although the contract requires it. The backend does not derive Origin from `Host` or trust forwarded headers for this check. Public identity operations are rate-limited (429 with `Retry-After`). - Responses with a session or account carry `Cache-Control: no-store`. - The root `security` requires `sessionCookie`, so an operation that does not declare `security: []` is protected by default. -How the generated server (ogen v1.24.0) evaluates the schemes, and the mapping planned for session authentication, are documented on `v1.DenyAllSecurity` and pinned by `TestGeneratedServerSecurityOrder`: +How the generated server (ogen v1.24.0) evaluates the schemes, and how `v1.SessionSecurity` applies the current session boundary, are pinned by `TestGeneratedServerSecurityOrder`: - It calls `HandleSessionCookie` before `HandleSessionCsrf` and passes the context returned by a successful call on. An absent value (no cookie, empty `X-CSRF-Token`) does not call the handler, and a handler that returns `ogenerrors.ErrSkipServerSecurity` counts as unsatisfied; both continue with the next scheme, so `HandleSessionCsrf` also runs without a cookie, with the original context. - Any other handler error stops evaluation and reaches `NewError` as a `SecurityError` whose `Security` is `SessionCookie` or `SessionCsrf`. An unsatisfied requirement reaches `NewError` as a `SecurityError` with `ErrSecurityRequirementIsNotSatisfied` and no `Security` field. -- Planned mapping: `HandleSessionCookie` skips a missing or invalid session; `HandleSessionCsrf` skips when the context has no principal (401) and returns a typed error for a wrong token. `NewError` maps a `SessionCsrf` error and an unsatisfied requirement with a principal in the context to 403 `csrf_check_failed`, and every other security failure to 401 `unauthenticated`. A 401 from `Logout` also clears the cookie. +- Implemented mapping: `HandleSessionCookie` authenticates only `GetCurrentSession`, `GetCurrentAccount`, and `Logout`; missing, unknown, expired, or revoked sessions leave the requirement unsatisfied. `HandleSessionCsrf` checks Origin and the token only for `Logout`; without a principal the result is 401, while a wrong Origin or CSRF token with a valid principal is 403 `csrf_check_failed`. Other protected operations fail the allowlist and remain 401 `unauthenticated`. A 401 from `Logout` also clears the cookie. ### Catalog and questionnaire diff --git a/api/README.md b/api/README.md index 4cac0ba..489178c 100644 --- a/api/README.md +++ b/api/README.md @@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Identity: сессии, cookie и CSRF -Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification` и `ConfirmEmail` реализованы. Вход еще отвечает 501 `not_implemented`, а `v1.DenyAllSecurity` отклоняет все запросы к защищенным операциям с 401 `unauthenticated`. Экраны регистрации и подтверждения во frontend остаются заглушками, вход еще не реализован. +Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session security разрешает только последние три защищенные операции; остальные операции, требующие сессию, остаются закрытыми с 401 `unauthenticated`. Экраны регистрации и подтверждения во frontend остаются заглушками. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -119,15 +119,15 @@ ML-сервис отвечает на ошибки той же схемой `Pro Регистрация и подтверждение: -- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email. Вход пока не реализован: его предусмотренный контрактом ответ 401 `invalid_credentials` для неизвестного email и неверного пароля пока не доступен. +- Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email. Вход отвечает одинаковым 401 `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша; для неизвестного email и некорректного хеша выполняется дополнительная работа Argon2id. Верный пароль неподтвержденной учетной записи дает 403 `email_not_verified` и не создает сессию. - До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта. -- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля, сценарий и первый шаг онбординга) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует прежние токены. `ConfirmEmail` требует пароль этой регистрации и проверяет его по отложенному хешу именно нажатого токена. В одной транзакции сервер проверяет текущую версию регистрации и связанную с ней запись C1, погашает токен, отмечает email подтвержденным, применяет отложенные данные токена к аккаунту, очищает поля `pending_*` и записывает ровно одно событие `identity.email_verified`. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный или устаревший токен, неверный пароль и отсутствие отложенных данных дают 400 `verification_token_invalid`; истекший токен дает 400 `verification_token_expired`. Так владелец адреса, перешедший по чужой ссылке, не принимает пароль, выбранный другим регистрантом, и наоборот. Подтверждение не создает сессию или cookie. Вход еще не реализован. Планируемое правило для входа: неподтвержденный аккаунт нельзя будет использовать для входа. -- Реализация регистрации и повторной отправки. Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). `ConfirmEmail` дополнительно ограничивает каждый токен до 5 попыток в час и использует тот же лимит клиента. Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка). +- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля, сценарий и первый шаг онбординга) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует прежние токены. `ConfirmEmail` требует пароль этой регистрации и проверяет его по отложенному хешу именно нажатого токена. В одной транзакции сервер проверяет текущую версию регистрации и связанную с ней запись C1, погашает токен, отмечает email подтвержденным, применяет отложенные данные токена к аккаунту, очищает поля `pending_*` и записывает ровно одно событие `identity.email_verified`. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный или устаревший токен, неверный пароль и отсутствие отложенных данных дают 400 `verification_token_invalid`; истекший токен дает 400 `verification_token_expired`. Так владелец адреса, перешедший по чужой ссылке, не принимает пароль, выбранный другим регистрантом, и наоборот. Подтверждение не создает сессию или cookie; вход доступен отдельно и принимает только пароль подтвержденной учетной записи. +- Реализация регистрации, повторной отправки и входа. Подтвержденный адрес при регистрации: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на почту (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа. `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час, диапазон 1..10000) ограничивает регистрацию, подтверждение, повторную отправку и вход по адресу клиента, если он разрешен доверенной цепочкой. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (по умолчанию 10 в час, диапазон 1..10000) ограничивает вход по нормализованному email независимо от наличия аккаунта. `ConfirmEmail` дополнительно ограничивает каждый токен до 5 попыток в час и использует лимит клиента. Отклоненный запрос дает 429 `rate_limited` с `Retry-After`. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток, лимиты и session CSRF. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `idempotency_in_progress` не возникает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка). - Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии с отложенными данными этой регистрации, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики). - Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля. - Запрос `ConfirmEmail` принимает и `token`, и выбранный при этой регистрации `password`; прежние клиенты, отправлявшие только токен, нужно обновить. Пароль обрабатывается по правилам `LoginPassword`: NFKC-нормализация и от 1 до 128 кодовых точек; blocklist регистрации повторно не применяется. `Origin` должен совпадать с `APP_PUBLIC_URL`; отсутствующий Origin, значение null или посторонний Origin дают 403 `csrf_check_failed`. Endpoint ограничивает попытки подтверждения одним токеном до 5 в час и применяет общий лимит клиента `IDENTITY_CLIENT_HOURLY_LIMIT`; отказ по лимиту дает 429 `rate_limited` с `Retry-After`. - Ссылка подтверждения имеет вид `/verify-email#token=`. Экран подтверждения во frontend пока остается заглушкой. Клиентская страница должна удалить фрагмент через `history.replaceState`, запросить явное действие пользователя и отправить токен вместе с паролем регистрации; сканер ссылок, который только открывает страницу, не расходует токен. -- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку и вход, когда вход будет реализован. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос. +- Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку; после подтверждения пользователь может отдельно войти. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос. Согласие C1 и аккаунт: @@ -138,17 +138,17 @@ ML-сервис отвечает на ошибки той же схемой `Pro Сессии и CSRF: -- Планируемое поведение сессий: cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict` и без Domain; сервер хранит сессии в PostgreSQL и берет вызывающего только из сессии. Когда вход будет реализован, сессию сможет получить только подтвержденный аккаунт, а вход будет отзывать сессию из запроса и выдавать новый идентификатор и CSRF-токен. Выход будет отзывать сессию на сервере. Тайм-ауты по продуктовой политике: 24 часа простоя и 7 дней абсолютного срока; активность продлевает только срок простоя. Эти значения не настраиваются через конфигурацию. -- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с привязанным к сессии токеном из `Session.csrf_token`. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`. -- Любой небезопасный запрос, включая публичные, должен нести `Origin` из настроенного allowlist, иначе 403 `csrf_check_failed` (запланировано; см. [руководство по разработке](../docs/ru/DEVELOPMENT.md#сессии-на-локальном-http)). Публичные операции identity ограничены по частоте (429 с `Retry-After`). +- Реализованные операции сессии: Login выдает cookie `__Host-lincodex_session` с `Path=/; Secure; HttpOnly; SameSite=Strict`, без Domain, и с Expires/Max-Age до абсолютного срока. PostgreSQL хранит только SHA-256 хеш cookie token; GET текущей сессии возвращает аккаунт и CSRF-токен после перезагрузки. Успешный вход отзывает действующую сессию из запроса и создает новую транзакционно; войти может только подтвержденный аккаунт. Logout отзывает сессию и очищает cookie; устаревшая или отозванная cookie также очищается с ответом 401. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h` (от `1m` до `30d`), а `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h` (от `1m` до `365d`); idle timeout не может превышать absolute lifetime, некорректные значения останавливают запуск. Запросы продлевают только idle deadline. +- Схема `sessionCsrf` - заголовок `X-CSRF-Token` с токеном для текущей сессии из `Session.csrf_token`. Backend выводит его через domain-separated HMAC-SHA-256 из cookie token и `IDENTITY_KEY_SECRET`, сравнивает за постоянное время и не хранит в БД. Все экземпляры должны использовать один `IDENTITY_KEY_SECRET` (не менее 32 байт), одинаковый между перезапусками; смена ключа делает прежние CSRF-токены недействительными, но не отзывает сессии PostgreSQL. Любая небезопасная операция, требующая `sessionCookie`, обязана требовать и `sessionCsrf`; это проверяет `TestUnsafeSessionOperationsRequireCSRFToken` в backend по bundle. Клиент хранит токен только в памяти и восстанавливает его через `GetCurrentSession` после перезагрузки страницы или после 403 `csrf_check_failed`. +- Контракт требует точный Origin с настроенным публичным origin для любого небезопасного запроса, включая публичные; backend сейчас проверяет единственный заголовок `Origin` на точное совпадение с `APP_PUBLIC_URL` в `ConfirmEmail`, `Login` и `Logout`. Logout дополнительно требует CSRF токен. `RegisterAccount` и `ResendEmailVerification` пока не проверяют Origin, хотя контракт этого требует. Backend не выводит origin из `Host` и не доверяет forwarded headers для этой проверки. Публичные операции identity ограничены по частоте (429 с `Retry-After`). - Ответы с сессией или аккаунтом несут `Cache-Control: no-store`. - Корневой `security` требует `sessionCookie`, поэтому операция без явного `security: []` защищена по умолчанию. -Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и какое отображение запланировано для аутентификации сессий, описано в `v1.DenyAllSecurity` и закреплено тестом `TestGeneratedServerSecurityOrder`: +Как сгенерированный сервер (ogen v1.24.0) проверяет схемы и как `v1.SessionSecurity` применяет текущую session boundary, закреплено тестом `TestGeneratedServerSecurityOrder`: - Он вызывает `HandleSessionCookie` раньше `HandleSessionCsrf` и передает дальше контекст, возвращенный успешным вызовом. Отсутствующее значение (нет cookie, пустой `X-CSRF-Token`) не вызывает обработчик, а обработчик, вернувший `ogenerrors.ErrSkipServerSecurity`, считается невыполненным; в обоих случаях проверка продолжается со следующей схемы, поэтому `HandleSessionCsrf` вызывается и без cookie, с исходным контекстом. - Любая другая ошибка обработчика останавливает проверку и попадает в `NewError` как `SecurityError` с `Security`, равным `SessionCookie` или `SessionCsrf`. Невыполненное требование попадает в `NewError` как `SecurityError` с `ErrSecurityRequirementIsNotSatisfied` и без поля `Security`. -- Запланированное отображение: `HandleSessionCookie` пропускает отсутствующую или недействительную сессию; `HandleSessionCsrf` пропускает проверку, если в контексте нет principal (401), и возвращает типизированную ошибку при неверном токене. `NewError` отображает ошибку `SessionCsrf` и невыполненное требование с principal в контексте в 403 `csrf_check_failed`, а любой другой сбой защиты - в 401 `unauthenticated`. 401 от `Logout` также удаляет cookie. +- Реализованное отображение: `HandleSessionCookie` аутентифицирует только `GetCurrentSession`, `GetCurrentAccount` и `Logout`; для отсутствующей, неизвестной, истекшей или отозванной сессии проверка не выполнена. `HandleSessionCsrf` проверяет Origin и токен только для `Logout`; без principal отказ остается 401, неверный Origin или CSRF с действующим principal дает 403 `csrf_check_failed`. Другие protected operations не проходят allowlist и остаются 401 `unauthenticated`. 401 от `Logout` также очищает cookie. ### Каталог и анкета diff --git a/backend/Makefile b/backend/Makefile index 9dd3e81..384f4a6 100644 --- a/backend/Makefile +++ b/backend/Makefile @@ -33,6 +33,14 @@ migrate-up: ## Apply pending embedded migrations to the database in DATABASE_URL migrate-down-one: ## Roll back the latest applied migration in the database in DATABASE_URL $(GO) run ./cmd/migrate down-one +.PHONY: mail-retry mail-retry-build +mail-retry: ## Inspect or authorize an audited unknown mail retry (set ARGS) + $(GO) run ./cmd/mail-retry $(ARGS) + +mail-retry-build: ## Build the local mail retry operator command + @mkdir -p bin + $(GO) build -buildvcs=false -trimpath -o bin/mail-retry ./cmd/mail-retry + .PHONY: deps install install-tools deps: ## Download pinned Go module dependencies $(GO) mod download diff --git a/backend/README.en.md b/backend/README.en.md index 2a1a87d..99dc906 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -2,7 +2,7 @@ [Русский](README.md) | English -The main service uses Go, chi, and Clean Architecture. It currently provides health checks and PostgreSQL, Redis, and SeaweedFS adapters; hiring workflows are still to be implemented. +The main service uses Go, chi, and Clean Architecture. It currently provides health checks, registration and email verification, server-side sessions, and PostgreSQL, Redis, and SeaweedFS adapters; hiring workflows are still to be implemented. - `cmd/app/` is the entry point; `internal/bootstrap/` wires dependencies and manages startup. - `internal/` contains domain types, use cases, ports, and primary/secondary adapters. @@ -12,4 +12,14 @@ The main service uses Go, chi, and Clean Architecture. It currently provides hea From the repository root, `make -C backend check` runs the main checks and `make -C backend test-int` runs integration tests with Docker. Use `make -C backend help` for all commands. +## 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`. + +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. + +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`. + See [architecture](../docs/en/ARCHITECTURE.md) and [development](../docs/en/DEVELOPMENT.md). diff --git a/backend/README.md b/backend/README.md index 96a0592..102fb32 100644 --- a/backend/README.md +++ b/backend/README.md @@ -2,7 +2,7 @@ Русский | [English](README.en.md) -Основной сервис на Go и chi с Clean Architecture. Сейчас реализованы проверки состояния, адаптеры PostgreSQL, Redis и SeaweedFS; продуктовые сценарии найма еще предстоит добавить. +Основной сервис на Go и chi с Clean Architecture. Сейчас реализованы проверки состояния, регистрация и подтверждение email, серверные сессии, а также адаптеры PostgreSQL, Redis и SeaweedFS; продуктовые сценарии найма еще предстоит добавить. - `cmd/app/` - точка входа; `internal/bootstrap/` собирает зависимости и управляет запуском. - `internal/` - доменные типы, use case, порты и primary/secondary адаптеры. @@ -12,4 +12,14 @@ Из корня: `make -C backend check` запускает основные проверки, `make -C backend test-int` - интеграционные тесты с Docker. Все команды доступны через `make -C backend help`. +## Серверные сессии + +Реализованы вход по 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`. + +Сессия хранится в 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 попыток в час. + +Проверки HTTP-сценариев с PostgreSQL и Redis входят в `make -C backend test-int`; компиляция integration suite без запуска контейнеров выполняется через `make -C backend test-int-compile`. + Подробнее: [архитектура](../docs/ru/ARCHITECTURE.md) и [разработка](../docs/ru/DEVELOPMENT.md). diff --git a/backend/cmd/mail-retry/main.go b/backend/cmd/mail-retry/main.go new file mode 100644 index 0000000..2ce44e6 --- /dev/null +++ b/backend/cmd/mail-retry/main.go @@ -0,0 +1,27 @@ +// Command mail-retry inspects and schedules an audited retry of an unknown +// mail delivery. It never sends mail itself. +package main + +import ( + "context" + "fmt" + "os" + "os/signal" + "syscall" + + "lincodex/backend/internal/adapter/primary/cli/mailretry" +) + +func main() { + os.Exit(run()) +} + +func run() int { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + if err := mailretry.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "mail-retry: %v\n", err) + return 2 + } + return 0 +} diff --git a/backend/config/config.go b/backend/config/config.go index 69d3e79..a3a50d3 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -120,10 +120,9 @@ type Config struct { // that may run at once; further logins and registrations wait. PasswordHashConcurrency int - // IdentityKeySecret keys the HMACs that scope idempotency records and - // rate limit counters by email address, so neither holds a plain hash of - // an address or a password. Empty means a random secret for the life of - // the process. + // IdentityKeySecret seeds domain-separated HMAC keys for idempotency + // scopes, rate limit buckets, and session CSRF tokens. Empty means a random + // secret for the life of the process. IdentityKeySecret string // IdentityAllowEphemeralKey lets a development stand run without // IDENTITY_KEY_SECRET, with a random secret per process. @@ -136,6 +135,14 @@ type Config struct { // IdentityClientHourlyLimit bounds the registrations and resends of one // client network address per hour. IdentityClientHourlyLimit int + // IdentityLoginEmailHourlyLimit bounds login attempts for one normalized + // email address per hour. + IdentityLoginEmailHourlyLimit int + // IdentitySessionIdleTimeout ends a session after this much inactivity. + IdentitySessionIdleTimeout time.Duration + // IdentitySessionAbsoluteLifetime is the maximum lifetime of a session, + // even when it remains active. + IdentitySessionAbsoluteLifetime time.Duration // TrustedProxyCIDRs are the reverse proxies in front of the API. The // client address is taken from X-Forwarded-For only through them (see diff --git a/backend/config/identity.go b/backend/config/identity.go index 7f20d64..8672956 100644 --- a/backend/config/identity.go +++ b/backend/config/identity.go @@ -21,12 +21,21 @@ const ( // messages to one address per 24 hours. defaultVerificationMailDailyLimit = 5 maxVerificationMailDailyLimit = 50 - // defaultIdentityClientHourlyLimit is the number of registrations and - // resends per client network address per hour. It is a brake on one - // source reaching many addresses; the per-address limits above protect - // one address from many sources. + // defaultIdentityClientHourlyLimit is the number of registration, + // confirmation, resend, and login attempts per client network address per + // hour. It is a brake on one source reaching many addresses; the per-address + // limits above protect one address from many sources. defaultIdentityClientHourlyLimit = 30 maxIdentityClientHourlyLimit = 10000 + // Login limits count attempts against both the client and normalized + // address buckets, regardless of whether the address has an account. + defaultIdentityLoginEmailHourlyLimit = 10 + maxIdentityLoginEmailHourlyLimit = 10000 + defaultIdentitySessionIdleTimeout = 24 * time.Hour + defaultIdentitySessionAbsoluteLifetime = 7 * 24 * time.Hour + minIdentitySessionTimeout = time.Minute + maxIdentitySessionIdleTimeout = 30 * 24 * time.Hour + maxIdentitySessionAbsoluteLifetime = 365 * 24 * time.Hour // MinIdentityKeySecretBytes is the shortest accepted IDENTITY_KEY_SECRET. MinIdentityKeySecretBytes = 32 // examplePlaceholderPrefix starts the placeholder values of the example @@ -34,14 +43,14 @@ const ( examplePlaceholderPrefix = "replace-this" ) -// loadIdentity reads the registration settings. IDENTITY_KEY_SECRET is +// loadIdentity reads the identity settings. IDENTITY_KEY_SECRET is // required: without it ValidateIdentity refuses the configuration, unless // IDENTITY_ALLOW_EPHEMERAL_KEY is true, which lets a development stand draw a -// random secret for the life of the process and so forget idempotency records -// and rate limit counters on every restart. +// random secret for the life of the process, so idempotency records and rate +// limit buckets change and session CSRF tokens differ after a restart. // -// The three limits treat an empty value as unset, as the mail quota does: -// Compose passes an unset variable as an empty string. +// Limit and timeout settings treat an empty value as unset, as the mail quota +// does: Compose passes an unset variable as an empty string. func (config *Config) loadIdentity(lookup LookupEnv) error { config.IdentityKeySecret = strings.TrimSpace(valueOrDefault(lookup, "IDENTITY_KEY_SECRET", "")) var err error @@ -64,13 +73,35 @@ func (config *Config) loadIdentity(lookup LookupEnv) error { if err != nil { return err } - config.IdentityClientHourlyLimit, err = intOrDefault(setOnly, "IDENTITY_CLIENT_HOURLY_LIMIT", defaultIdentityClientHourlyLimit) + if config.IdentityClientHourlyLimit, err = intOrDefault(setOnly, "IDENTITY_CLIENT_HOURLY_LIMIT", defaultIdentityClientHourlyLimit); err != nil { + return err + } + if config.IdentityLoginEmailHourlyLimit, err = intOrDefault(setOnly, "IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT", defaultIdentityLoginEmailHourlyLimit); err != nil { + return err + } + if config.IdentitySessionIdleTimeout, err = durationOrDefault(setOnly, "IDENTITY_SESSION_IDLE_TIMEOUT", defaultIdentitySessionIdleTimeout); err != nil { + return err + } + config.IdentitySessionAbsoluteLifetime, err = durationOrDefault(setOnly, "IDENTITY_SESSION_ABSOLUTE_LIFETIME", defaultIdentitySessionAbsoluteLifetime) return err } // ValidateIdentity checks the registration settings. Errors never include // the secret. func (config Config) ValidateIdentity() error { + if err := config.validateIdentitySecret(); err != nil { + return err + } + if err := config.validateVerificationMailSettings(); err != nil { + return err + } + if err := config.validateIdentityLimits(); err != nil { + return err + } + return config.validateSessionTimeouts() +} + +func (config Config) validateIdentitySecret() error { if config.IdentityKeySecret == "" && !config.IdentityAllowEphemeralKey { return errors.New("Config.ValidateIdentity - IDENTITY_KEY_SECRET is required (generate one with: openssl rand -base64 48); " + "set IDENTITY_ALLOW_EPHEMERAL_KEY=true only on a development stand") @@ -81,6 +112,10 @@ func (config Config) ValidateIdentity() error { if config.IdentityKeySecret != "" && len(config.IdentityKeySecret) < MinIdentityKeySecretBytes { return fmt.Errorf("Config.ValidateIdentity - IDENTITY_KEY_SECRET must have at least %d bytes", MinIdentityKeySecretBytes) } + return nil +} + +func (config Config) validateVerificationMailSettings() error { if config.VerificationMailMinInterval < minVerificationMailMinInterval || config.VerificationMailMinInterval > maxVerificationMailMinInterval { return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be between %s and %s", minVerificationMailMinInterval, maxVerificationMailMinInterval) @@ -88,11 +123,33 @@ func (config Config) ValidateIdentity() error { if config.VerificationMailDailyLimit < 1 || config.VerificationMailDailyLimit > maxVerificationMailDailyLimit { return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT must be between 1 and %d", maxVerificationMailDailyLimit) } - if config.IdentityClientHourlyLimit < 1 || config.IdentityClientHourlyLimit > maxIdentityClientHourlyLimit { - return fmt.Errorf("Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT must be between 1 and %d", maxIdentityClientHourlyLimit) - } if config.VerificationMailMinInterval >= 24*time.Hour { return errors.New("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be shorter than the daily window") } return nil } + +func (config Config) validateIdentityLimits() error { + if config.IdentityClientHourlyLimit < 1 || config.IdentityClientHourlyLimit > maxIdentityClientHourlyLimit { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT must be between 1 and %d", maxIdentityClientHourlyLimit) + } + if config.IdentityLoginEmailHourlyLimit < 1 || config.IdentityLoginEmailHourlyLimit > maxIdentityLoginEmailHourlyLimit { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT must be between 1 and %d", maxIdentityLoginEmailHourlyLimit) + } + return nil +} + +func (config Config) validateSessionTimeouts() error { + if config.IdentitySessionIdleTimeout < minIdentitySessionTimeout || config.IdentitySessionIdleTimeout > maxIdentitySessionIdleTimeout { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_SESSION_IDLE_TIMEOUT must be between %s and %s", + minIdentitySessionTimeout, maxIdentitySessionIdleTimeout) + } + if config.IdentitySessionAbsoluteLifetime < minIdentitySessionTimeout || config.IdentitySessionAbsoluteLifetime > maxIdentitySessionAbsoluteLifetime { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_SESSION_ABSOLUTE_LIFETIME must be between %s and %s", + minIdentitySessionTimeout, maxIdentitySessionAbsoluteLifetime) + } + if config.IdentitySessionIdleTimeout > config.IdentitySessionAbsoluteLifetime { + return errors.New("Config.ValidateIdentity - IDENTITY_SESSION_IDLE_TIMEOUT must not exceed IDENTITY_SESSION_ABSOLUTE_LIFETIME") + } + return nil +} diff --git a/backend/config/identity_test.go b/backend/config/identity_test.go index ff3267f..0a44713 100644 --- a/backend/config/identity_test.go +++ b/backend/config/identity_test.go @@ -14,25 +14,30 @@ func TestLoadFromEnvIdentityDefaults(t *testing.T) { if settings.IdentityKeySecret != "" || settings.VerificationMailMinInterval != time.Minute || settings.VerificationMailDailyLimit != 5 || - settings.IdentityClientHourlyLimit != 30 { - t.Fatalf("identity defaults = %q, %s, %d, %d", settings.IdentityKeySecret, - settings.VerificationMailMinInterval, settings.VerificationMailDailyLimit, settings.IdentityClientHourlyLimit) + settings.IdentityClientHourlyLimit != 30 || settings.IdentityLoginEmailHourlyLimit != 10 || + settings.IdentitySessionIdleTimeout != 24*time.Hour || settings.IdentitySessionAbsoluteLifetime != 7*24*time.Hour { + t.Fatalf("identity defaults = %+v", settings) } } func TestLoadFromEnvIdentityExplicit(t *testing.T) { secret := strings.Repeat("k", MinIdentityKeySecretBytes) settings, err := LoadFromEnv(testEnvironment(map[string]string{ - "IDENTITY_KEY_SECRET": " " + secret + " ", - "VERIFICATION_MAIL_MIN_INTERVAL": "90s", - "VERIFICATION_MAIL_DAILY_LIMIT": "3", - "IDENTITY_CLIENT_HOURLY_LIMIT": "100", + "IDENTITY_KEY_SECRET": " " + secret + " ", + "VERIFICATION_MAIL_MIN_INTERVAL": "90s", + "VERIFICATION_MAIL_DAILY_LIMIT": "3", + "IDENTITY_CLIENT_HOURLY_LIMIT": "100", + "IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT": "12", + "IDENTITY_SESSION_IDLE_TIMEOUT": "12h", + "IDENTITY_SESSION_ABSOLUTE_LIFETIME": "72h", })) if err != nil { t.Fatalf("LoadFromEnv() error = %v", err) } if settings.IdentityKeySecret != secret || settings.VerificationMailMinInterval != 90*time.Second || - settings.VerificationMailDailyLimit != 3 || settings.IdentityClientHourlyLimit != 100 { + settings.VerificationMailDailyLimit != 3 || settings.IdentityClientHourlyLimit != 100 || + settings.IdentityLoginEmailHourlyLimit != 12 || settings.IdentitySessionIdleTimeout != 12*time.Hour || + settings.IdentitySessionAbsoluteLifetime != 72*time.Hour { t.Fatalf("identity settings were not read: %+v", settings) } } @@ -41,14 +46,19 @@ func TestLoadFromEnvRejectsIdentitySettings(t *testing.T) { tests := map[string]struct { key, value, want string }{ - "short secret": {"IDENTITY_KEY_SECRET", "too-short", "Config.ValidateIdentity - IDENTITY_KEY_SECRET"}, - "interval below": {"VERIFICATION_MAIL_MIN_INTERVAL", "500ms", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"}, - "interval above": {"VERIFICATION_MAIL_MIN_INTERVAL", "2h", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"}, - "interval malformed": {"VERIFICATION_MAIL_MIN_INTERVAL", "soon", "config.durationOrDefault - parse VERIFICATION_MAIL_MIN_INTERVAL"}, - "daily zero": {"VERIFICATION_MAIL_DAILY_LIMIT", "0", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"}, - "daily too high": {"VERIFICATION_MAIL_DAILY_LIMIT", "51", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"}, - "daily malformed": {"VERIFICATION_MAIL_DAILY_LIMIT", "five", "config.intOrDefault - VERIFICATION_MAIL_DAILY_LIMIT"}, - "client zero": {"IDENTITY_CLIENT_HOURLY_LIMIT", "0", "Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT"}, + "short secret": {"IDENTITY_KEY_SECRET", "too-short", "Config.ValidateIdentity - IDENTITY_KEY_SECRET"}, + "interval below": {"VERIFICATION_MAIL_MIN_INTERVAL", "500ms", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"}, + "interval above": {"VERIFICATION_MAIL_MIN_INTERVAL", "2h", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"}, + "interval malformed": {"VERIFICATION_MAIL_MIN_INTERVAL", "soon", "config.durationOrDefault - parse VERIFICATION_MAIL_MIN_INTERVAL"}, + "daily zero": {"VERIFICATION_MAIL_DAILY_LIMIT", "0", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"}, + "daily too high": {"VERIFICATION_MAIL_DAILY_LIMIT", "51", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"}, + "daily malformed": {"VERIFICATION_MAIL_DAILY_LIMIT", "five", "config.intOrDefault - VERIFICATION_MAIL_DAILY_LIMIT"}, + "client zero": {"IDENTITY_CLIENT_HOURLY_LIMIT", "0", "Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT"}, + "login email zero": {"IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT", "0", "Config.ValidateIdentity - IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT"}, + "login email malformed": {"IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT", "ten", "config.intOrDefault - IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT"}, + "session idle too short": {"IDENTITY_SESSION_IDLE_TIMEOUT", "30s", "Config.ValidateIdentity - IDENTITY_SESSION_IDLE_TIMEOUT"}, + "session idle too long": {"IDENTITY_SESSION_IDLE_TIMEOUT", "744h", "Config.ValidateIdentity - IDENTITY_SESSION_IDLE_TIMEOUT"}, + "session absolute too long": {"IDENTITY_SESSION_ABSOLUTE_LIFETIME", "8784h", "Config.ValidateIdentity - IDENTITY_SESSION_ABSOLUTE_LIFETIME"}, } for name, test := range tests { _, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value})) @@ -58,6 +68,16 @@ func TestLoadFromEnvRejectsIdentitySettings(t *testing.T) { } } +func TestIdentitySessionIdleTimeoutDoesNotExceedAbsoluteLifetime(t *testing.T) { + _, err := LoadFromEnv(testEnvironment(map[string]string{ + "IDENTITY_SESSION_IDLE_TIMEOUT": "25h", + "IDENTITY_SESSION_ABSOLUTE_LIFETIME": "24h", + })) + if err == nil || !strings.Contains(err.Error(), "IDENTITY_SESSION_IDLE_TIMEOUT must not exceed IDENTITY_SESSION_ABSOLUTE_LIFETIME") { + t.Fatalf("LoadFromEnv() error = %v, want idle timeout bounded by absolute lifetime", err) + } +} + func TestIdentityErrorsDoNotQuoteTheSecret(t *testing.T) { _, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_KEY_SECRET": "short-secret-value"})) if err == nil || strings.Contains(err.Error(), "short-secret-value") { @@ -67,16 +87,20 @@ func TestIdentityErrorsDoNotQuoteTheSecret(t *testing.T) { func TestLoadFromEnvIdentityEmptyLimitsMeanUnset(t *testing.T) { settings, err := LoadFromEnv(testEnvironment(map[string]string{ - "VERIFICATION_MAIL_MIN_INTERVAL": "", - "VERIFICATION_MAIL_DAILY_LIMIT": " ", - "IDENTITY_CLIENT_HOURLY_LIMIT": "", + "VERIFICATION_MAIL_MIN_INTERVAL": "", + "VERIFICATION_MAIL_DAILY_LIMIT": " ", + "IDENTITY_CLIENT_HOURLY_LIMIT": "", + "IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT": "", + "IDENTITY_SESSION_IDLE_TIMEOUT": "", + "IDENTITY_SESSION_ABSOLUTE_LIFETIME": "", })) if err != nil { t.Fatalf("LoadFromEnv() error = %v", err) } - if settings.VerificationMailMinInterval != time.Minute || settings.VerificationMailDailyLimit != 5 || settings.IdentityClientHourlyLimit != 30 { - t.Fatalf("empty limits = %s, %d, %d, want the defaults", settings.VerificationMailMinInterval, - settings.VerificationMailDailyLimit, settings.IdentityClientHourlyLimit) + if settings.VerificationMailMinInterval != time.Minute || settings.VerificationMailDailyLimit != 5 || + settings.IdentityClientHourlyLimit != 30 || settings.IdentityLoginEmailHourlyLimit != 10 || + settings.IdentitySessionIdleTimeout != 24*time.Hour || settings.IdentitySessionAbsoluteLifetime != 7*24*time.Hour { + t.Fatalf("empty identity limits = %+v, want the defaults", settings) } } diff --git a/backend/db/migrations/00017_retry_unknown_mail.sql b/backend/db/migrations/00017_retry_unknown_mail.sql new file mode 100644 index 0000000..3a583e2 --- /dev/null +++ b/backend/db/migrations/00017_retry_unknown_mail.sql @@ -0,0 +1,115 @@ +-- +goose Up +-- Resend may accept a request even when the caller loses the response. Keep +-- that delivery unknown, but schedule bounded retries while its provider key +-- is still inside the deduplication window. An operator decision after the +-- automatic cutoff is append-only and single-use; manual send markers never +-- reset the provider's idempotency window. + +ALTER TABLE deliveries +ADD COLUMN manual_retry_authorized_at timestamptz, +ADD COLUMN manual_retry_started_at timestamptz, +ADD COLUMN send_started_attempt_count integer; + +COMMENT ON COLUMN deliveries.manual_retry_authorized_at IS +'Database time of the latest audited operator authorization to retry a terminal unknown delivery; it does not replace the original send history.'; +COMMENT ON COLUMN deliveries.manual_retry_started_at IS +'Database time when the first provider call of the latest manual authorization started; this is a single-use/recovery marker and never resets the provider deduplication window.'; +COMMENT ON COLUMN deliveries.send_started_attempt_count IS +'Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start.'; + +ALTER TABLE deliveries ADD CONSTRAINT deliveries_manual_retry_cycle_complete CHECK ( + manual_retry_started_at IS NULL OR manual_retry_authorized_at IS NOT NULL +); +ALTER TABLE deliveries ADD CONSTRAINT deliveries_send_started_attempt_count_valid CHECK ( + send_started_attempt_count IS NULL + OR (send_started_attempt_count >= 0 AND send_started_attempt_count <= attempt_count) +); + +-- Keep the decision after a delivery or account is deleted. This table holds +-- only an opaque delivery ID, attempt number, operator handle, acknowledgement +-- and decision time; it never stores recipient data or message content. +CREATE TABLE delivery_retry_decisions ( + decision_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + delivery_id uuid NOT NULL, + attempt_count integer NOT NULL CHECK (attempt_count > 0), + actor text NOT NULL CHECK ( + length(actor) <= 128 + AND actor ~ '^operator:[a-z0-9][a-z0-9._-]*$' + ), + duplicate_risk_acknowledged boolean NOT NULL CHECK (duplicate_risk_acknowledged), + previous_lease_expired boolean NOT NULL, + decided_at timestamptz NOT NULL DEFAULT clock_timestamp() +); + +CREATE INDEX delivery_retry_decisions_delivery_idx +ON delivery_retry_decisions (delivery_id, decision_id); + +COMMENT ON TABLE delivery_retry_decisions IS +'Append-only record of an operator decision to retry a terminal unknown mail delivery after its provider deduplication window. No foreign key so history survives account deletion.'; +COMMENT ON COLUMN delivery_retry_decisions.delivery_id IS +'Opaque ID of the delivery whose current unknown attempt was authorized for another send cycle.'; +COMMENT ON COLUMN delivery_retry_decisions.actor IS +'Operator handle in the form operator:; never an email address or credential.'; +COMMENT ON COLUMN delivery_retry_decisions.duplicate_risk_acknowledged IS +'Must be true: after the provider key expires, reusing it does not guarantee deduplication.'; +COMMENT ON COLUMN delivery_retry_decisions.previous_lease_expired IS +'True when this decision also cleared an expired worker lease after a manual send began but its result was not recorded.'; + +-- +goose StatementBegin +CREATE FUNCTION delivery_retry_decisions_refuse_change() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'TRUNCATE' THEN + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'delivery_retry_decisions_immutable', + TABLE = 'delivery_retry_decisions', + MESSAGE = 'mail retry decisions are append-only'; + END IF; + RAISE EXCEPTION USING + ERRCODE = 'integrity_constraint_violation', + CONSTRAINT = 'delivery_retry_decisions_immutable', + TABLE = 'delivery_retry_decisions', + MESSAGE = 'mail retry decisions are append-only'; +END; +$$; +-- +goose StatementEnd + +CREATE TRIGGER delivery_retry_decisions_refuse_update_delete +BEFORE UPDATE OR DELETE ON delivery_retry_decisions +FOR EACH ROW EXECUTE FUNCTION delivery_retry_decisions_refuse_change(); + +CREATE TRIGGER delivery_retry_decisions_refuse_truncate +BEFORE TRUNCATE ON delivery_retry_decisions +FOR EACH STATEMENT EXECUTE FUNCTION delivery_retry_decisions_refuse_change(); + +-- A due unknown row is claimable only when the retry policy gave it a due +-- time. Keep the worker's single indexed queue broad enough for all due +-- service-mail statuses. +DROP INDEX deliveries_due_idx; +CREATE INDEX deliveries_due_idx +ON deliveries (next_attempt_at, id) +WHERE + status IN ('pending', 'waiting_quota', 'unknown') + AND next_attempt_at IS NOT NULL + AND kind IN ('verification', 'password_reset'); + +-- +goose Down +-- Rolling back this migration removes its append-only operator decision +-- history. Export or preserve that audit data before an intentional rollback. +DROP INDEX deliveries_due_idx; +CREATE INDEX deliveries_due_idx +ON deliveries (next_attempt_at, id) +WHERE + status IN ('pending', 'waiting_quota') + AND next_attempt_at IS NOT NULL + AND kind IN ('verification', 'password_reset'); + +DROP TRIGGER delivery_retry_decisions_refuse_update_delete ON delivery_retry_decisions; +DROP TRIGGER delivery_retry_decisions_refuse_truncate ON delivery_retry_decisions; +DROP FUNCTION delivery_retry_decisions_refuse_change(); +DROP INDEX delivery_retry_decisions_delivery_idx; +DROP TABLE delivery_retry_decisions; +ALTER TABLE deliveries DROP CONSTRAINT deliveries_manual_retry_cycle_complete; +ALTER TABLE deliveries DROP CONSTRAINT deliveries_send_started_attempt_count_valid; +ALTER TABLE deliveries DROP COLUMN send_started_attempt_count, DROP COLUMN manual_retry_started_at, DROP COLUMN manual_retry_authorized_at; diff --git a/backend/db/queries/delivery.sql b/backend/db/queries/delivery.sql index febe45a..2196b4f 100644 --- a/backend/db/queries/delivery.sql +++ b/backend/db/queries/delivery.sql @@ -86,6 +86,21 @@ SELECT FROM deliveries WHERE id = sqlc.arg(id); +-- Reads only the metadata needed by the local operator retry interface. It +-- intentionally does not select the address, token, subject, or message body. +-- name: GetDeliveryRetrySnapshot :one +SELECT + id, + provider, + provider_account, + status, + attempt_count, + next_attempt_at, + first_send_started_at, + manual_retry_started_at +FROM deliveries +WHERE id = sqlc.arg(id); + -- Advances a delivery past one attempt and appends the attempt in one -- statement, so both happen or neither does, inside or outside a -- transaction. The update applies only while the stored version still @@ -219,7 +234,7 @@ WHERE AND deliveries.version = sqlc.arg(expected_version); -- Claims the most overdue delivery that the sending worker may send, in one --- statement: a pending or waiting_quota delivery of the service mail kinds +-- statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds -- (the literals match the predicate of deliveries_due_idx, so an idle poll -- reads only that small index) whose next_attempt_at has passed, pinned to the -- configured provider account (or to rebind_provider before its first @@ -233,10 +248,15 @@ WHERE -- stay on the application clock that wrote them. Neither the version nor -- updated_at changes: a claim is not a change of the delivery. -- previous_claimed_until is the deadline of an abandoned lease, NULL for a --- delivery nobody held; since_first_send_seconds is how long ago, by the --- database clock, its first request started, -1 when none did. now is the --- application clock. Deliveries that are unknown or wait for an unknown quota --- reset have no due time here and wait for an operator. +-- delivery nobody held; since_first_send_seconds always measures from the +-- original first request by the database clock, and is -1 when none started. +-- manual_retry_pending is true until the first provider call of the latest +-- manual authorization starts. send_start_unsettled means a provider call +-- started at the current attempt_count but no result was recorded afterward. +-- has_uncertain_attempt keeps an earlier unknown result visible even if a +-- later confirmed refusal moved the current delivery back to pending. +-- now is the application clock. Unknown deliveries without a scheduled retry +-- and quota waits with an unknown reset wait for an operator. -- name: ClaimDueDelivery :one WITH candidate AS ( SELECT @@ -245,12 +265,25 @@ WITH candidate AS ( coalesce( extract(EPOCH FROM clock_timestamp() - due.first_send_started_at), -1 - )::float8 AS since_first_send_seconds + )::float8 AS since_first_send_seconds, + (due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL) + AS manual_retry_pending, + (due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started, + ( + due.send_started_attempt_count IS NOT NULL + AND due.send_started_attempt_count = due.attempt_count + )::boolean AS send_start_unsettled, + EXISTS ( + SELECT 1 + FROM delivery_attempts AS prior_attempt + WHERE prior_attempt.delivery_id = due.id + AND prior_attempt.outcome = 'unknown' + )::boolean AS has_uncertain_attempt FROM deliveries AS due WHERE due.kind IN ('verification', 'password_reset') AND due.kind = any(sqlc.arg(kinds)::text []) - AND due.status IN ('pending', 'waiting_quota') + AND due.status IN ('pending', 'waiting_quota', 'unknown') AND due.next_attempt_at IS NOT NULL AND due.next_attempt_at <= sqlc.arg(now)::timestamptz AND ( @@ -306,7 +339,144 @@ RETURNING claimed.created_at, claimed.updated_at, candidate.previous_claimed_until, - candidate.since_first_send_seconds; + candidate.since_first_send_seconds, + candidate.manual_retry_pending, + candidate.manual_retry_cycle_started, + candidate.send_start_unsettled, + candidate.has_uncertain_attempt; + +-- Authorizes one retry of a terminal unknown delivery. The update and append- +-- only decision share one statement and lock the current row, so a second or +-- concurrent operator decision cannot schedule another send for the same +-- unknown attempt. The provider account must still match the delivery's pin. +-- name: AuthorizeUnknownDeliveryRetry :execrows +WITH eligible AS MATERIALIZED ( + SELECT + due.id, + (due.claim_owner IS NOT NULL) AS previous_lease_expired, + ( + due.manual_retry_started_at IS NOT NULL + AND due.send_started_attempt_count = due.attempt_count + ) AS unsettled_manual_send, + greatest( + clock_timestamp(), + due.updated_at, + coalesce(due.last_attempt_at, due.updated_at) + ) AS lost_attempt_at + FROM deliveries AS due + WHERE + due.id = sqlc.arg(delivery_id) + AND due.status = 'unknown' + AND due.next_attempt_at IS NULL + AND ( + due.claim_owner IS NULL + OR due.claimed_until <= clock_timestamp() + ) + AND due.attempt_count > 0 + AND due.provider = sqlc.arg(provider) + AND due.provider_account = sqlc.arg(provider_account) + AND due.first_send_started_at IS NOT NULL + AND clock_timestamp() - due.first_send_started_at + >= make_interval(secs => sqlc.arg(minimum_age_seconds)::float8) + AND sqlc.arg(duplicate_risk_acknowledged)::boolean + AND sqlc.arg(actor)::text ~ '^operator:[a-z0-9][a-z0-9._-]*$' + FOR UPDATE +), authorized AS ( + UPDATE deliveries AS due + SET + attempt_count = due.attempt_count + CASE WHEN eligible.unsettled_manual_send THEN 1 ELSE 0 END, + last_attempt_at = CASE + WHEN eligible.unsettled_manual_send THEN eligible.lost_attempt_at + ELSE due.last_attempt_at + END, + next_attempt_at = greatest( + sqlc.arg(now)::timestamptz, + due.updated_at, + coalesce(eligible.lost_attempt_at, due.updated_at) + ), + manual_retry_authorized_at = clock_timestamp(), + manual_retry_started_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + version = due.version + 1, + updated_at = greatest( + due.updated_at, + sqlc.arg(now)::timestamptz, + coalesce(eligible.lost_attempt_at, due.updated_at) + ) + FROM eligible + WHERE due.id = eligible.id + RETURNING + due.id, + due.attempt_count, + eligible.previous_lease_expired, + eligible.unsettled_manual_send, + eligible.lost_attempt_at +), recorded_lost_attempt AS ( + -- A manual send whose lease expired after Mark but before settlement has + -- no provider answer. Preserve it as an unknown attempt before this new + -- explicit decision schedules another possible send. + INSERT INTO delivery_attempts ( + delivery_id, + attempt_number, + attempted_at, + outcome, + rejection, + provider_code, + provider_message_id, + retry_after_ns, + status_after, + next_attempt_at + ) + SELECT + authorized.id, + authorized.attempt_count, + authorized.lost_attempt_at, + 'unknown', + NULL, + NULL, + NULL, + 0, + 'unknown', + NULL + FROM authorized + WHERE authorized.unsettled_manual_send + RETURNING delivery_id +) +INSERT INTO delivery_retry_decisions ( + delivery_id, + attempt_count, + actor, + duplicate_risk_acknowledged, + previous_lease_expired, + decided_at +) +SELECT + authorized.id, + authorized.attempt_count, + sqlc.arg(actor), + sqlc.arg(duplicate_risk_acknowledged), + authorized.previous_lease_expired, + clock_timestamp() +FROM authorized; + +-- Stops a due automatic retry of an unknown delivery without recording a +-- fictitious provider attempt, for example when the 23-hour safety cutoff is +-- reached after the claim but before the provider call. +-- name: StopUnknownDeliveryRetry :execrows +UPDATE deliveries +SET + status = 'unknown', + next_attempt_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, sqlc.arg(now)::timestamptz) +WHERE + id = sqlc.arg(id) + AND status IN ('pending', 'waiting_quota', 'unknown') + AND next_attempt_at IS NOT NULL + AND claim_owner = sqlc.arg(lease_owner)::uuid; -- Ends a claimed delivery whose stored content no longer matches its hash, so -- one broken row never blocks the delivery queue. It matches only a delivery @@ -428,19 +598,41 @@ WHERE AND claim_owner = sqlc.arg(lease_owner) FOR UPDATE; --- Notes that the first request of a claimed delivery is about to start, by the --- database clock, and clears the count of worker failures: the claim and the --- preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted --- from this moment, so a later claim can tell whether repeating the request is --- still safe. It never moves. +-- Notes that a request is about to start, by the database clock, and clears +-- the count of worker failures. For an operator-authorized send, this sets +-- its single-use marker without overwriting the original first-send time. The +-- marker captures the current attempt_count so a lost result can be recovered +-- as unknown instead of silently retried. When require_dedup_window is true, +-- the age check is repeated here after quota work and the row lock, immediately +-- before the network call; manual starts never reset that original window. -- name: MarkDeliverySendStarted :execrows UPDATE deliveries SET first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()), + send_started_attempt_count = deliveries.attempt_count, + next_attempt_at = CASE + WHEN deliveries.manual_retry_authorized_at IS NOT NULL + AND deliveries.manual_retry_started_at IS NULL + THEN NULL + ELSE deliveries.next_attempt_at + END, + manual_retry_started_at = CASE + WHEN deliveries.manual_retry_authorized_at IS NOT NULL + AND deliveries.manual_retry_started_at IS NULL + THEN clock_timestamp() + ELSE deliveries.manual_retry_started_at + END, failure_count = 0 WHERE id = sqlc.arg(id) - AND claim_owner = sqlc.arg(lease_owner); + AND claim_owner = sqlc.arg(lease_owner) + AND ( + NOT sqlc.arg(require_dedup_window)::boolean + OR (deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL) + OR coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) IS NULL + OR clock_timestamp() - coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) + < make_interval(secs => sqlc.arg(retry_window_seconds)::float8) + ); -- Gives a claimed delivery back without changing it, so the next pass may -- claim it. It matches only the lease of lease_owner: a delivery that another diff --git a/backend/integration_test/mail_retry_migration_test.go b/backend/integration_test/mail_retry_migration_test.go new file mode 100644 index 0000000..25db9b3 --- /dev/null +++ b/backend/integration_test/mail_retry_migration_test.go @@ -0,0 +1,72 @@ +//go:build integration + +package integration_test + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +const mailRetryMigrationVersion = 17 + +func TestMailRetryMigrationKeepsAnAppendOnlyAudit(t *testing.T) { + env := bootstrap(t, postgresService) + ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout) + defer cancel() + databaseURL := env.createIsolatedDatabase(ctx, t) + migrator := newMigrator(t, databaseURL) + pool := newPoolFor(ctx, t, databaseURL) + if _, err := migrator.Up(ctx); err != nil { + t.Fatalf("Up() error = %v", err) + } + + deliveryID := uuid.New() + decidedAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) + if _, err := pool.Exec(ctx, `INSERT INTO delivery_retry_decisions ( + delivery_id, attempt_count, actor, duplicate_risk_acknowledged, previous_lease_expired, decided_at + ) VALUES ($1, 2, 'operator:mail-ops', true, false, $2)`, deliveryID, decidedAt); err != nil { + t.Fatalf("insert retry decision: %v", err) + } + + for _, statement := range []string{ + "UPDATE delivery_retry_decisions SET actor = 'operator:other' WHERE delivery_id = '" + deliveryID.String() + "'", + "DELETE FROM delivery_retry_decisions WHERE delivery_id = '" + deliveryID.String() + "'", + "TRUNCATE delivery_retry_decisions", + } { + _, err := pool.Exec(ctx, statement) + assertSQLRefusal(t, err, "delivery_retry_decisions_immutable") + } + var decisions int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 { + t.Fatalf("audit decisions = %d, %v; want one retained record", decisions, err) + } + var predicate string + if err := pool.QueryRow(ctx, `SELECT pg_get_expr(indpred, indrelid) FROM pg_index WHERE indexrelid = 'deliveries_due_idx'::regclass`).Scan(&predicate); err != nil { + t.Fatalf("read deliveries_due_idx predicate: %v", err) + } + if predicate == "" || !containsAll(predicate, "unknown", "next_attempt_at") { + t.Fatalf("deliveries_due_idx predicate = %q; want scheduled unknown rows", predicate) + } + + result, err := migrator.DownOne(ctx) + if err != nil || result.Version != mailRetryMigrationVersion { + t.Fatalf("DownOne() = %+v, %v; want rollback of migration %d", result, err, mailRetryMigrationVersion) + } + var auditTable bool + if err := pool.QueryRow(ctx, "SELECT to_regclass('public.delivery_retry_decisions') IS NOT NULL").Scan(&auditTable); err != nil || auditTable { + t.Fatalf("audit table after rollback = %t, %v; want removed", auditTable, err) + } +} + +func containsAll(value string, fragments ...string) bool { + for _, fragment := range fragments { + if !strings.Contains(value, fragment) { + return false + } + } + return true +} diff --git a/backend/integration_test/mail_sender_test.go b/backend/integration_test/mail_sender_test.go index 4b412f3..15b2e71 100644 --- a/backend/integration_test/mail_sender_test.go +++ b/backend/integration_test/mail_sender_test.go @@ -3,6 +3,7 @@ package integration_test import ( + "bytes" "context" "errors" "fmt" @@ -20,6 +21,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" + "lincodex/backend/internal/adapter/primary/cli/mailretry" "lincodex/backend/internal/adapter/secondary/mail/disabled" "lincodex/backend/internal/adapter/secondary/mail/resend" "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" @@ -145,6 +147,7 @@ func TestServiceMailSending(t *testing.T) { fixture := resendfixture.New() t.Cleanup(fixture.Close) clock := &testClock{now: mailSenderStart} + fixture.SetClock(clock.Now) transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, fixture.URL(), clock.Now) if err != nil { t.Fatalf("NewLoopbackSender() error = %v", err) @@ -173,6 +176,7 @@ func TestServiceMailSending(t *testing.T) { // their start instead. truncateTables(ctx, t, pool, slices.Concat(mailSenderTables, usersDependentTables)...) clock.Set(mailSenderStart) + fixture.SetClock(clock.Now) fixture.SetDelay(0) } @@ -246,6 +250,45 @@ func TestServiceMailSending(t *testing.T) { harness.assertLogsHoldNoSecrets(t, user.Email.Address(), raw.Reveal(), "verify-email") }) + t.Run("an accepted request with a lost response retries under the same key within 24 hours", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + fixture.Script(resendfixture.Reply{DropAfterAccept: true}) + + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass after the fixture accepted and dropped the response = %+v, want unknown", result) + } + uncertain := harness.delivery(ctx, t, deliveryID) + if uncertain.Status() != domain.DeliveryStatusUnknown || !uncertain.NextAttemptAt().Equal(mailSenderStart.Add(time.Minute)) { + t.Fatalf("delivery is %s due %s, want unknown with a bounded retry", uncertain.Status(), uncertain.NextAttemptAt()) + } + if fixture.Messages()-messages != 1 { + t.Fatalf("fixture accepted %d messages, want exactly one before the retry", fixture.Messages()-messages) + } + + harness.clock.Advance(time.Minute) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass within the provider window = %+v, want the original acceptance", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || + requests[0].IdempotencyKey != "delivery/"+deliveryID.String() || !requests[1].Replayed || + !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || + requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { + t.Fatalf("provider calls = %+v, want the same pinned key and stored body, replayed once", requests) + } + stored := harness.delivery(ctx, t, deliveryID) + if stored.ProviderAccount() != harness.account || stored.Status() != domain.DeliveryStatusAccepted || + stored.AttemptCount() != 2 || fixture.Messages()-messages != 1 { + t.Fatalf("delivery is %s on %s after %d attempts, fixture has %d new message(s); want pinned account, accepted, two calls, one message", + stored.Status(), stored.ProviderAccount().Account(), stored.AttemptCount(), fixture.Messages()-messages) + } + }) + t.Run("a worker that holds a delivery keeps every other worker off it", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) @@ -917,21 +960,27 @@ func TestServiceMailSending(t *testing.T) { t.Fatalf("attempts = %+v, want a temporary refusal and then acceptance", attempts) } - // An uncertain answer is never retried by the worker and never read - // as not sent. + // An uncertain answer remains unknown, but gets a bounded retry while + // the provider still holds the idempotency key. other := harness.createUser(ctx, t, false) _, _, uncertainID := harness.enqueueVerification(ctx, t, other, mailSenderTokenLifetime) fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { t.Fatalf("pass after a 500 = %+v, want unknown", result) } - if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() { - t.Fatalf("delivery is %s with next attempt %s, want unknown without one", got.Status(), got.NextAttemptAt()) + if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().Equal(harness.clock.Now().Add(time.Minute)) { + t.Fatalf("delivery is %s with next attempt %s, want unknown with bounded retry", got.Status(), got.NextAttemptAt()) } harness.clock.Advance(24 * time.Hour) + // PostgreSQL owns the cutoff clock; move its start time to exercise + // the same DB-clock age calculation without sleeping for a day. + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '24 hours' WHERE id = $1", uncertainID) callsBefore := len(fixture.Requests()) - if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()) != callsBefore { - t.Fatalf("pass after an unknown outcome = %+v, want idle without a call", result) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown || len(fixture.Requests()) != callsBefore { + t.Fatalf("pass after the deduplication cutoff = %+v, want unknown without a call", result) + } + if got := harness.delivery(ctx, t, uncertainID); got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() { + t.Fatalf("delivery after cutoff is %s due %s, want terminal unknown without automatic retry", got.Status(), got.NextAttemptAt()) } // A permanent refusal ends the delivery. @@ -947,6 +996,344 @@ func TestServiceMailSending(t *testing.T) { } }) + t.Run("an earlier unknown answer remains uncertain after a confirmed 429", func(t *testing.T) { + for _, test := range []struct { + name string + age time.Duration + wantOutcome inbound.MailPassOutcome + wantStatus domain.DeliveryStatus + wantCalls int + }{ + {name: "retry remains allowed before cutoff", age: 22 * time.Hour, wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantCalls: 3}, + {name: "cutoff stops without a phantom attempt", age: 24 * time.Hour, wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantCalls: 2}, + } { + t.Run(test.name, func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + + fixture.Script(resendfixture.Reply{DropAfterAccept: true}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("accepted request with dropped response = %+v, want unknown", result) + } + harness.clock.Advance(time.Minute) + fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "60"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { + t.Fatalf("confirmed 429 = %+v, want retry", result) + } + pending := harness.delivery(ctx, t, deliveryID) + if pending.Status() != domain.DeliveryStatusPending || pending.AttemptCount() != 2 { + t.Fatalf("delivery after 429 is %s after %d attempts, want pending after two", pending.Status(), pending.AttemptCount()) + } + attempts := harness.attempts(ctx, t, deliveryID) + if len(attempts) != 2 || attempts[0].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].Rejection != domain.DeliveryRejectionRateLimited { + t.Fatalf("attempts = %+v, want unknown then confirmed rate limit", attempts) + } + + harness.clock.Set(mailSenderStart.Add(test.age)) + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - make_interval(secs => $2::float8) WHERE id = $1", deliveryID, test.age.Seconds()) + result := harness.pass(ctx, t, sender) + stored := harness.delivery(ctx, t, deliveryID) + if result.Outcome != test.wantOutcome || stored.Status() != test.wantStatus || len(fixture.Requests())-calls != test.wantCalls { + t.Fatalf("pass = %+v, delivery %s, provider requests %d; want %s and %d calls", result, stored.Status(), len(fixture.Requests())-calls, test.wantOutcome, test.wantCalls) + } + requests := fixture.Requests()[calls:] + if requests[0].IdempotencyKey != requests[1].IdempotencyKey || + !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || + requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { + t.Fatal("unknown and confirmed-refusal requests did not keep the same pinned key and body") + } + if test.wantStatus == domain.DeliveryStatusUnknown && + (stored.AttemptCount() != 2 || !stored.NextAttemptAt().IsZero() || len(attempts) != 2 || fixture.Messages()-messages != 1) { + t.Fatalf("cutoff state = %s due %s after %d attempts, fixture accepted %d messages; want no new call or attempt", stored.Status(), stored.NextAttemptAt(), stored.AttemptCount(), fixture.Messages()-messages) + } + }) + } + }) + + t.Run("manual retry audits the decision, honors 429 Retry-After, and stops after another unknown", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + messages := fixture.Messages() + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial 500 pass = %+v, want unknown", result) + } + + operator, err := notification.NewDeliveryRetryOperator( + harness.transactor, harness.deliveries, harness.account, resend.IdempotencyWindow, harness.clock.Now, + ) + if err != nil { + t.Fatalf("NewDeliveryRetryOperator() error = %v", err) + } + if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) { + t.Fatalf("RetryUnknown() before cutoff error = %v, want not allowed", err) + } + if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", false); !errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired) { + t.Fatalf("RetryUnknown() without acknowledgement error = %v, want acknowledgement required", err) + } + + // Claim while the original result is still inside the safe window, + // then age the DB-clock timestamp before MarkSendStarted. The last + // storage check must refuse the call even though the claim succeeded. + harness.clock.Advance(time.Minute) + owner := uuid.New() + var claimed outbound.ClaimedDelivery + if err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + claimed, err = unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: time.Minute, + }) + return err + }); err != nil || claimed.Delivery.ID() != deliveryID { + t.Fatalf("claim for the cutoff check = %s, %v; want the uncertain delivery", claimed.Delivery.ID(), err) + } + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '24 hours' WHERE id = $1", deliveryID) + started, err := harness.deliveries.MarkSendStarted(ctx, deliveryID, owner, true, 23*time.Hour) + if err != nil || started { + t.Fatalf("MarkSendStarted() at the DB-clock cutoff = %t, %v; want no send", started, err) + } + if released, err := harness.deliveries.ReleaseClaim(ctx, deliveryID, owner); err != nil || !released { + t.Fatalf("ReleaseClaim() after cutoff refusal = %t, %v; want released", released, err) + } + + harness.clock.Set(mailSenderStart.Add(23 * time.Hour)) + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '23 hours' WHERE id = $1", deliveryID) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass at the automatic cutoff = %+v, want automatic retry stopped", result) + } + stopped := harness.delivery(ctx, t, deliveryID) + if stopped.Status() != domain.DeliveryStatusUnknown || !stopped.NextAttemptAt().IsZero() { + t.Fatalf("delivery after automatic cutoff is %s due %s, want unknown without automatic retry", stopped.Status(), stopped.NextAttemptAt()) + } + lookup := func(key string) (string, bool) { + switch key { + case "DATABASE_URL": + return env.Config.DatabaseURL, true + case "EMAIL_PROVIDER": + return "resend", true + case "EMAIL_ACCOUNT": + return mailSenderAccount, true + default: + return "", false + } + } + var cliOutput bytes.Buffer + if err := mailretry.Run(ctx, []string{"inspect", "--delivery", deliveryID.String()}, lookup, &cliOutput); err != nil { + t.Fatalf("mail-retry inspect error = %v", err) + } + if !strings.Contains(cliOutput.String(), notification.DuplicateRiskWarning) || + strings.Contains(cliOutput.String(), user.Email.Address()) { + t.Fatalf("mail-retry inspect output = %q; want duplicate warning without recipient data", cliOutput.String()) + } + cliOutput.Reset() + if err := mailretry.Run(ctx, []string{ + "retry", "--delivery", deliveryID.String(), "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk", + }, lookup, &cliOutput); err != nil { + t.Fatalf("mail-retry retry error = %v", err) + } + if !strings.Contains(cliOutput.String(), notification.DuplicateRiskWarning) || + !strings.Contains(cliOutput.String(), "retry scheduled; audit decision recorded") { + t.Fatalf("mail-retry retry output = %q; want warning and audited scheduling", cliOutput.String()) + } + if _, err := operator.RetryUnknown(ctx, deliveryID, "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) { + t.Fatalf("duplicate RetryUnknown() error = %v, want not allowed", err) + } + var decisions int + if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 { + t.Fatalf("audited decisions = %d, %v; want exactly one", decisions, err) + } + + fixture.Script(resendfixture.Reply{Status: http.StatusTooManyRequests, Name: "rate_limit_exceeded", RetryAfter: "300"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassRetry { + t.Fatalf("manual 429 pass = %+v, want scheduled retry", result) + } + rateLimited := harness.delivery(ctx, t, deliveryID) + wantRetryAt := harness.clock.Now().Add(5 * time.Minute) + if rateLimited.Status() != domain.DeliveryStatusPending || !rateLimited.NextAttemptAt().Equal(wantRetryAt) { + t.Fatalf("429 state is %s due %s, want pending due at Retry-After %s", rateLimited.Status(), rateLimited.NextAttemptAt(), wantRetryAt) + } + + harness.clock.Set(wantRetryAt) + fixture.Script(resendfixture.Reply{DropAfterAccept: true}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("manual send with accepted connection drop = %+v, want unknown", result) + } + unknown := harness.delivery(ctx, t, deliveryID) + if unknown.Status() != domain.DeliveryStatusUnknown || !unknown.NextAttemptAt().IsZero() || unknown.AttemptCount() != 3 { + t.Fatalf("manual drop state is %s due %s after %d attempts, want terminal unknown after 3", unknown.Status(), unknown.NextAttemptAt(), unknown.AttemptCount()) + } + callsAfterUnknown := len(fixture.Requests()) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle || len(fixture.Requests()) != callsAfterUnknown { + t.Fatalf("pass after manual unknown = %+v with %d requests, want idle", result, len(fixture.Requests())-calls) + } + if err := pool.QueryRow(ctx, "SELECT count(*) FROM delivery_retry_decisions WHERE delivery_id = $1", deliveryID).Scan(&decisions); err != nil || decisions != 1 { + t.Fatalf("audited decisions without another operator command = %d, %v; want still one", decisions, err) + } + requests := fixture.Requests()[calls:] + if len(requests) != 3 || fixture.Messages()-messages != 1 { + t.Fatalf("provider saw %d requests and accepted %d messages; want 3 requests and one accepted message", len(requests), fixture.Messages()-messages) + } + for _, request := range requests[1:] { + if request.IdempotencyKey != requests[0].IdempotencyKey || !slices.Equal(request.To, requests[0].To) || + request.Subject != requests[0].Subject || request.Text != requests[0].Text || request.HTML != requests[0].HTML { + t.Fatal("the manual retries changed the pinned key or stored body") + } + } + if requests[2].Replayed { + t.Fatal("the final request was unexpectedly replayed before the fixture accepted its first manual request") + } + }) + + t.Run("an expired manual send-start is recorded before another authorized send", func(t *testing.T) { + reset(t) + calls := len(fixture.Requests()) + user := harness.createUser(ctx, t, false) + _, _, deliveryID := harness.enqueueVerification(ctx, t, user, mailSenderTokenLifetime) + sender := harness.newSender(t, harness.transactor, 100, 3000) + fixture.Script(resendfixture.Reply{Status: http.StatusInternalServerError, Name: "application_error"}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial 500 pass = %+v, want unknown", result) + } + harness.clock.Set(mailSenderStart.Add(23 * time.Hour)) + harness.exec(ctx, t, "UPDATE deliveries SET first_send_started_at = clock_timestamp() - interval '23 hours' WHERE id = $1", deliveryID) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass at automatic cutoff = %+v, want terminal unknown", result) + } + + lookup := func(key string) (string, bool) { + switch key { + case "DATABASE_URL": + return env.Config.DatabaseURL, true + case "EMAIL_PROVIDER": + return "resend", true + case "EMAIL_ACCOUNT": + return mailSenderAccount, true + default: + return "", false + } + } + retryCommand := func() { + t.Helper() + var output bytes.Buffer + if err := mailretry.Run(ctx, []string{ + "retry", "--delivery", deliveryID.String(), "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk", + }, lookup, &output); err != nil { + t.Fatalf("mail-retry command error = %v", err) + } + if !strings.Contains(output.String(), notification.DuplicateRiskWarning) || + !strings.Contains(output.String(), "retry scheduled; audit decision recorded") || + strings.Contains(output.String(), user.Email.Address()) { + t.Fatalf("mail-retry output = %q; want warning and safe scheduling result", output.String()) + } + } + dbClock := func() time.Time { + t.Helper() + var now time.Time + if err := pool.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil { + t.Fatalf("read database clock: %v", err) + } + return now + } + retryCommand() + authorized := harness.delivery(ctx, t, deliveryID) + if authorized.Status() != domain.DeliveryStatusUnknown || authorized.NextAttemptAt().IsZero() { + t.Fatalf("authorized delivery state = %s due %s; want scheduled unknown work", authorized.Status(), authorized.NextAttemptAt()) + } + // Authorization keeps the later of the app and database timestamps. + // The cutoff pass above uses the fake app clock, so advancing only to + // database-now can still leave the delivery not due yet. + dueAfterAuthorization := authorized.NextAttemptAt().Add(time.Second) + if databaseNow := dbClock().Add(time.Second); databaseNow.After(dueAfterAuthorization) { + dueAfterAuthorization = databaseNow + } + harness.clock.Set(dueAfterAuthorization) + owner := uuid.New() + var claimed outbound.ClaimedDelivery + if err := harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + var err error + claimed, err = unit.Deliveries().ClaimDue(ctx, outbound.DeliveryClaim{ + Owner: owner, Account: harness.account, Kinds: domain.ServiceMailKinds(), Now: harness.clock.Now(), Lease: mailSenderLease, + }) + return err + }); err != nil || claimed.Delivery.ID() != deliveryID || !claimed.ManualRetryPending { + t.Fatalf("manual send claim = %s, pending %t, error %v; want the authorized delivery", claimed.Delivery.ID(), claimed.ManualRetryPending, err) + } + started, err := harness.deliveries.MarkSendStarted(ctx, deliveryID, owner, true, 23*time.Hour) + if err != nil || !started { + t.Fatalf("MarkSendStarted() for operator decision = %t, %v; want started", started, err) + } + harness.exec(ctx, t, "UPDATE deliveries SET claimed_until = clock_timestamp() - interval '1 second' WHERE id = $1", deliveryID) + + callsBeforeRecovery := len(fixture.Requests()) + retryCommand() + if len(fixture.Requests()) != callsBeforeRecovery { + t.Fatal("operator recovery called the provider instead of only recording the lost result and scheduling work") + } + recovered := harness.delivery(ctx, t, deliveryID) + attempts := harness.attempts(ctx, t, deliveryID) + if recovered.AttemptCount() != 2 || recovered.Status() != domain.DeliveryStatusUnknown || recovered.NextAttemptAt().IsZero() || len(attempts) != 2 || + attempts[0].Outcome != domain.DeliveryOutcomeUnknown || attempts[1].Outcome != domain.DeliveryOutcomeUnknown || + attempts[1].At.Before(attempts[0].At) { + t.Fatalf("recovered delivery = %s due %s after %d attempts, attempts %+v; want the lost manual call appended as unknown and another decision scheduled", recovered.Status(), recovered.NextAttemptAt(), recovered.AttemptCount(), attempts) + } + rows, err := pool.Query(ctx, ` + SELECT attempt_count, duplicate_risk_acknowledged, previous_lease_expired + FROM delivery_retry_decisions + WHERE delivery_id = $1 + ORDER BY decision_id`, deliveryID) + if err != nil { + t.Fatalf("read retry decisions: %v", err) + } + defer rows.Close() + var decisions []struct { + attemptCount int32 + duplicateRiskAcknowledged bool + previousLeaseExpired bool + } + for rows.Next() { + var decision struct { + attemptCount int32 + duplicateRiskAcknowledged bool + previousLeaseExpired bool + } + if err := rows.Scan(&decision.attemptCount, &decision.duplicateRiskAcknowledged, &decision.previousLeaseExpired); err != nil { + t.Fatalf("scan retry decision: %v", err) + } + decisions = append(decisions, decision) + } + if err := rows.Err(); err != nil { + t.Fatalf("read retry decisions: %v", err) + } + if len(decisions) != 2 || decisions[0].attemptCount != 1 || decisions[1].attemptCount != 2 || + !decisions[0].duplicateRiskAcknowledged || !decisions[1].duplicateRiskAcknowledged || + decisions[0].previousLeaseExpired || !decisions[1].previousLeaseExpired { + t.Fatalf("retry decisions = %+v; want each decision tied to its unknown attempt and second decision marked as lease recovery", decisions) + } + + dueAfterRecovery := recovered.NextAttemptAt().Add(time.Second) + if databaseNow := dbClock().Add(time.Second); databaseNow.After(dueAfterRecovery) { + dueAfterRecovery = databaseNow + } + harness.clock.Set(dueAfterRecovery) + fixture.Script(resendfixture.Reply{}) + if result := harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass after recovered operator decision = %+v, want accepted", result) + } + requests := fixture.Requests()[calls:] + if len(requests) != 2 || requests[0].IdempotencyKey != requests[1].IdempotencyKey || + !slices.Equal(requests[0].To, requests[1].To) || requests[0].Subject != requests[1].Subject || + requests[0].Text != requests[1].Text || requests[0].HTML != requests[1].HTML { + t.Fatalf("provider requests after recovery = %+v; want initial and manually authorized request with the pinned key and body", requests) + } + }) + t.Run("a used-up quota parks the delivery in a user-visible waiting status", func(t *testing.T) { reset(t) calls := len(fixture.Requests()) diff --git a/backend/integration_test/registration_consent_migration_test.go b/backend/integration_test/registration_consent_migration_test.go index a63cc6e..7c30dcd 100644 --- a/backend/integration_test/registration_consent_migration_test.go +++ b/backend/integration_test/registration_consent_migration_test.go @@ -8,9 +8,15 @@ import ( "time" "github.com/jackc/pgx/v5/pgxpool" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" ) -const registrationConsentMigrationName = "00016_bind_registration_consent.sql" +const ( + registrationConsentMigrationVersion = 16 + registrationConsentMigrationName = "00016_bind_registration_consent.sql" + mailRetryMigrationName = "00017_retry_unknown_mail.sql" +) func TestRegistrationConsentMigration(t *testing.T) { env := bootstrap(t, postgresService) @@ -24,10 +30,7 @@ func TestRegistrationConsentMigration(t *testing.T) { if _, err := migrator.Up(ctx); err != nil { t.Fatalf("apply migrations before preparing legacy data: %v", err) } - rolledBack, err := migrator.DownOne(ctx) - if err != nil || rolledBack.Name != registrationConsentMigrationName { - t.Fatalf("roll back the registration-consent migration = %+v, %v", rolledBack, err) - } + rollbackThroughRegistrationConsent(ctx, t, migrator) assertRegistrationConsentColumn(ctx, t, pool, false) const userID = "018f0000-0000-7000-8000-000000000001" @@ -41,8 +44,8 @@ func TestRegistrationConsentMigration(t *testing.T) { seedRegistrationConsentFixture(ctx, t, pool, userID, createdAt, registrationAt, registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion, settingsAt) applied, err := migrator.Up(ctx) - if err != nil || len(applied) != 1 || applied[0].Name != registrationConsentMigrationName { - t.Fatalf("apply registration-consent migration = %+v, %v", applied, err) + if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName { + t.Fatalf("apply registration-consent and later migrations = %+v, %v", applied, err) } assertConsentRegistrationVersion(ctx, t, pool, registrationConsentID, 2) assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID) @@ -89,17 +92,14 @@ func TestRegistrationConsentMigration(t *testing.T) { t.Fatal("a refused registration C1 version change altered its version or revocation state") } - rolledBack, err = migrator.DownOne(ctx) - if err != nil || rolledBack.Name != registrationConsentMigrationName { - t.Fatalf("roll back registration-consent migration = %+v, %v", rolledBack, err) - } + rollbackThroughRegistrationConsent(ctx, t, migrator) assertRegistrationConsentColumn(ctx, t, pool, false) if countConsentRecords(ctx, t, pool) != beforeMismatch { t.Fatal("rolling back the registration-consent migration changed the consent ledger") } applied, err = migrator.Up(ctx) - if err != nil || len(applied) != 1 || applied[0].Name != registrationConsentMigrationName { - t.Fatalf("reapply registration-consent migration = %+v, %v", applied, err) + if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName { + t.Fatalf("reapply registration-consent and later migrations = %+v, %v", applied, err) } assertRegistrationConsentColumn(ctx, t, pool, true) assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3) @@ -113,10 +113,7 @@ func TestRegistrationConsentMigration(t *testing.T) { if _, err := migrator.Up(ctx); err != nil { t.Fatalf("apply migrations before preparing stale legacy data: %v", err) } - rolledBack, err := migrator.DownOne(ctx) - if err != nil || rolledBack.Name != registrationConsentMigrationName { - t.Fatalf("roll back the registration-consent migration = %+v, %v", rolledBack, err) - } + rollbackThroughRegistrationConsent(ctx, t, migrator) assertRegistrationConsentColumn(ctx, t, pool, false) const userID = "018f0000-0000-7000-8000-000000000101" @@ -147,14 +144,36 @@ func TestRegistrationConsentMigration(t *testing.T) { if _, err := pool.Exec(ctx, `UPDATE users SET last_registered_at = $2, updated_at = $2 WHERE id = $1::uuid`, userID, grantAt); err != nil { t.Fatalf("correct the synthetic legacy registration timestamp: %v", err) } - if _, err := migrator.Up(ctx); err != nil { - t.Fatalf("migration did not succeed after the legacy data was corrected: %v", err) + applied, err := migrator.Up(ctx) + if err != nil || len(applied) < 2 || applied[0].Name != registrationConsentMigrationName || applied[1].Name != mailRetryMigrationName { + t.Fatalf("migrations did not succeed after the legacy data was corrected: %+v, %v", applied, err) } assertRegistrationConsentColumn(ctx, t, pool, true) assertConsentRegistrationVersion(ctx, t, pool, consentID, 1) }) } +// rollbackThroughRegistrationConsent removes later migrations as well, so +// each fixture is truly at the schema immediately before migration 00016. +func rollbackThroughRegistrationConsent(ctx context.Context, t *testing.T, migrator *postgresadapter.Migrator) { + t.Helper() + for { + rolledBack, err := migrator.DownOne(ctx) + if err != nil { + t.Fatalf("roll back through registration-consent migration: %v", err) + } + if rolledBack.Version < registrationConsentMigrationVersion { + t.Fatalf("rolled back migration %d before reaching migration %d", rolledBack.Version, registrationConsentMigrationVersion) + } + if rolledBack.Version == registrationConsentMigrationVersion { + if rolledBack.Name != registrationConsentMigrationName { + t.Fatalf("rolled back migration %d named %q, want %q", rolledBack.Version, rolledBack.Name, registrationConsentMigrationName) + } + return + } + } +} + func seedRegistrationConsentFixture( ctx context.Context, t *testing.T, diff --git a/backend/integration_test/session_http_test.go b/backend/integration_test/session_http_test.go new file mode 100644 index 0000000..3eb23a5 --- /dev/null +++ b/backend/integration_test/session_http_test.go @@ -0,0 +1,495 @@ +//go:build integration + +package integration_test + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgxpool" + + httpadapter "lincodex/backend/internal/adapter/primary/http" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" +) + +const ( + sessionHTTPTestTimeout = 5 * time.Minute + sessionHTTPTestOrigin = "http://localhost:8080" + sessionHTTPTestPass = "correct horse battery staple" +) + +type sessionHTTPHarness struct { + pool *pgxpool.Pool + store *postgresadapter.IdentityStore + router http.Handler + credentials *identity.Credentials + clock *testClock + logs *strings.Builder +} + +func newSessionHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *sessionHTTPHarness { + t.Helper() + return newSessionHTTPHarnessWithSettings(ctx, t, env, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: env.Config.IdentitySessionIdleTimeout, + AbsoluteLifetime: env.Config.IdentitySessionAbsoluteLifetime, + }) +} + +func newSessionHTTPHarnessWithSettings( + ctx context.Context, + t *testing.T, + env *testEnvironment, + settings identity.SessionSettings, +) *sessionHTTPHarness { + t.Helper() + pool := env.newPool(ctx, t) + store := postgresadapter.NewIdentityStore(pool) + hasher, err := argon2id.NewHasher(1) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + credentials := identity.NewCredentials(hasher) + keyring, err := identity.NewKeyring([]byte(env.Config.IdentityKeySecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + clock := &testClock{now: time.Now().UTC().Truncate(time.Microsecond)} + service, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: postgresadapter.NewTransactor(pool), + Users: store.Users(), + Sessions: store.Sessions(), + Credentials: credentials, + Limiter: env.Redis, + Keyring: keyring, + Clock: clock.Now, + }, settings) + if err != nil { + t.Fatalf("NewSessionService() error = %v", err) + } + logs := &strings.Builder{} + 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)) + handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(identityHandler)) + router, err := httpadapter.NewRouter( + healthHandler, + handler, + v1.NewSessionSecurity(service, env.Config.AppPublicURL), + responder, + prometheus.New(), + logger, + nil, + ) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + return &sessionHTTPHarness{pool: pool, store: store, router: router, credentials: credentials, clock: clock, logs: logs} +} + +func createSessionHTTPUser( + ctx context.Context, + t *testing.T, + harness *sessionHTTPHarness, + email string, + passwordHash domain.PasswordHash, + verified bool, +) domain.User { + t.Helper() + address, err := domain.NewEmailAddress(email) + if err != nil { + t.Fatalf("NewEmailAddress() error = %v", err) + } + now := harness.clock.Now().Truncate(time.Microsecond) + user, err := domain.NewUser(domain.Registration{ + Email: address, + PasswordHash: passwordHash, + Scenario: domain.ScenarioCandidate, + RegisteredAt: now, + }) + if err != nil { + t.Fatalf("NewUser() error = %v", err) + } + if err := harness.store.Users().Create(ctx, user); err != nil { + t.Fatalf("Create(%s) error = %v", email, err) + } + if !verified { + return user + } + user, err = harness.store.Users().MarkEmailVerified(ctx, user.ID, user.RegistrationVersion, now.Add(time.Microsecond)) + if err != nil { + t.Fatalf("MarkEmailVerified() error = %v", err) + } + return user +} + +func (harness *sessionHTTPHarness) request( + t *testing.T, + method string, + path string, + body string, + origin string, + cookie string, + csrf string, + remoteAddr string, +) *httptest.ResponseRecorder { + t.Helper() + request := httptest.NewRequest(method, path, strings.NewReader(body)) + if body != "" { + request.Header.Set("Content-Type", "application/json") + } + if origin != "" { + request.Header.Set("Origin", origin) + } + if cookie != "" { + request.Header.Set("Cookie", "__Host-lincodex_session="+cookie) + } + if csrf != "" { + request.Header.Set("X-CSRF-Token", csrf) + } + request.RemoteAddr = remoteAddr + recorder := httptest.NewRecorder() + harness.router.ServeHTTP(recorder, request) + return recorder +} + +func loginSessionHTTP(t *testing.T, harness *sessionHTTPHarness, email, password string, origin, cookie, remoteAddr string) *httptest.ResponseRecorder { + t.Helper() + body, err := json.Marshal(struct { + Email string `json:"email"` + Password string `json:"password"` + }{Email: email, Password: password}) + if err != nil { + t.Fatalf("marshal login request: %v", err) + } + return harness.request(t, http.MethodPost, "/api/v1/identity/sessions", string(body), origin, cookie, "", remoteAddr) +} + +func requireSessionProblem(t *testing.T, response *httptest.ResponseRecorder, status int, code string) { + t.Helper() + var body struct { + Code string `json:"code"` + } + if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil { + t.Fatalf("decode problem response %d %s: %v", response.Code, response.Body.String(), err) + } + if response.Code != status || body.Code != code { + t.Fatalf("response = %d code=%q body=%s, want %d code=%q", response.Code, body.Code, response.Body.String(), status, code) + } +} + +func requireSessionCookie(t *testing.T, response *httptest.ResponseRecorder) *http.Cookie { + t.Helper() + cookies := response.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("Set-Cookie values = %v, want exactly one session cookie", response.Header().Values("Set-Cookie")) + } + cookie := cookies[0] + if cookie.Name != "__Host-lincodex_session" || cookie.Value == "" || cookie.Path != "/" || cookie.Domain != "" || + !cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge <= 0 || cookie.Expires.IsZero() { + t.Fatalf("session cookie attributes = %+v", cookie) + } + return cookie +} + +func requireExpiredSessionCookie(t *testing.T, response *httptest.ResponseRecorder) { + t.Helper() + cookies := response.Result().Cookies() + if len(cookies) != 1 { + t.Fatalf("Set-Cookie values = %v, want one cleared session cookie", response.Header().Values("Set-Cookie")) + } + cookie := cookies[0] + if cookie.Name != "__Host-lincodex_session" || cookie.Value != "" || cookie.Path != "/" || cookie.Domain != "" || + !cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || cookie.MaxAge >= 0 { + t.Fatalf("cleared session cookie attributes = %+v", cookie) + } +} + +func TestIdentitySessionsOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout) + defer cancel() + harness := newSessionHTTPHarness(ctx, t, env) + + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + verifiedEmail := "verified@example.test" + unverifiedEmail := "unverified@example.test" + verifiedUser := createSessionHTTPUser(ctx, t, harness, verifiedEmail, passwordHash, true) + createSessionHTTPUser(ctx, t, harness, unverifiedEmail, passwordHash, false) + + unknown := loginSessionHTTP(t, harness, "unknown@example.test", sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.1:1234") + wrongPassword := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, "", "192.0.2.2:1234") + requireSessionProblem(t, unknown, http.StatusUnauthorized, "invalid_credentials") + requireSessionProblem(t, wrongPassword, http.StatusUnauthorized, "invalid_credentials") + if unknown.Header().Get("Content-Type") != wrongPassword.Header().Get("Content-Type") || + !strings.Contains(unknown.Header().Get("Content-Type"), "application/problem+json") { + t.Fatalf("unknown and wrong-password response media types differ: %q and %q", unknown.Header().Get("Content-Type"), wrongPassword.Header().Get("Content-Type")) + } + if len(unknown.Header().Values("Set-Cookie")) != 0 || len(wrongPassword.Header().Values("Set-Cookie")) != 0 { + t.Fatal("a rejected login set a session cookie") + } + unverified := loginSessionHTTP(t, harness, unverifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.3:1234") + requireSessionProblem(t, unverified, http.StatusForbidden, "email_not_verified") + if len(unverified.Header().Values("Set-Cookie")) != 0 { + t.Fatal("unverified login set a session cookie") + } + + badOriginBody, err := json.Marshal(struct { + Email string `json:"email"` + Password string `json:"password"` + }{Email: verifiedEmail, Password: sessionHTTPTestPass}) + if err != nil { + t.Fatalf("marshal bad-origin login request: %v", err) + } + badOriginRequest := httptest.NewRequest(http.MethodPost, "/api/v1/identity/sessions", strings.NewReader(string(badOriginBody))) + badOriginRequest.Header.Set("Content-Type", "application/json") + badOriginRequest.Header.Set("Origin", "http://attacker.example") + badOriginRequest.Header.Set("X-Forwarded-Host", "localhost:8080") + badOriginRequest.RemoteAddr = "192.0.2.4:1234" + badOrigin := httptest.NewRecorder() + harness.router.ServeHTTP(badOrigin, badOriginRequest) + requireSessionProblem(t, badOrigin, http.StatusForbidden, "csrf_check_failed") + if len(badOrigin.Header().Values("Set-Cookie")) != 0 { + t.Fatal("a login with a disallowed Origin set a session cookie") + } + + limitedEmail := "limit@example.test" + for attempt := 1; attempt <= 10; attempt++ { + response := loginSessionHTTP(t, harness, limitedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", fmt.Sprintf("198.51.100.%d:1234", attempt)) + requireSessionProblem(t, response, http.StatusUnauthorized, "invalid_credentials") + } + limited := loginSessionHTTP(t, harness, limitedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "198.51.100.11:1234") + requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.Header().Get("Retry-After") == "" { + t.Fatal("email login limit response has no Retry-After") + } + + malformedCookieLogin := loginSessionHTTP(t, harness, verifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "not-a-session-token", "192.0.2.5:1234") + if malformedCookieLogin.Code != http.StatusCreated { + t.Fatalf("login with a malformed incoming cookie status = %d, body=%s", malformedCookieLogin.Code, malformedCookieLogin.Body.String()) + } + firstCookie := requireSessionCookie(t, malformedCookieLogin) + if malformedCookieLogin.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("login Cache-Control = %q, want no-store", malformedCookieLogin.Header().Get("Cache-Control")) + } + var firstBody struct { + Account struct { + ID string `json:"id"` + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + } `json:"account"` + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(malformedCookieLogin.Body.Bytes(), &firstBody); err != nil { + t.Fatalf("decode login response: %v", err) + } + if firstBody.Account.ID != verifiedUser.ID.String() || firstBody.Account.Email != verifiedEmail || !firstBody.Account.EmailVerified || firstBody.CSRFToken == "" { + t.Fatalf("login account or CSRF token = %+v", firstBody) + } + + currentSession := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.6:1234") + if currentSession.Code != http.StatusOK || currentSession.Header().Get("Cache-Control") != "no-store" { + t.Fatalf("current session response = %d %s, Cache-Control=%q", currentSession.Code, currentSession.Body.String(), currentSession.Header().Get("Cache-Control")) + } + var sessionBody struct { + Account struct { + Email string `json:"email"` + EmailVerified bool `json:"email_verified"` + } `json:"account"` + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(currentSession.Body.Bytes(), &sessionBody); err != nil { + t.Fatalf("decode current session response: %v", err) + } + 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) + } + 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") + + wrongPasswordWithSession := loginSessionHTTP(t, harness, verifiedEmail, "incorrect horse battery staple", sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.9:1234") + requireSessionProblem(t, wrongPasswordWithSession, http.StatusUnauthorized, "invalid_credentials") + stillActive := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.10:1234") + if stillActive.Code != http.StatusOK { + t.Fatalf("failed login revoked its incoming session: status=%d body=%s", stillActive.Code, stillActive.Body.String()) + } + + rotated := loginSessionHTTP(t, harness, verifiedEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, firstCookie.Value, "192.0.2.11:1234") + if rotated.Code != http.StatusCreated { + t.Fatalf("rotating login status = %d, body=%s", rotated.Code, rotated.Body.String()) + } + secondCookie := requireSessionCookie(t, rotated) + if secondCookie.Value == firstCookie.Value { + t.Fatal("rotating login reused the session token") + } + var secondBody struct { + CSRFToken string `json:"csrf_token"` + } + if err := json.Unmarshal(rotated.Body.Bytes(), &secondBody); err != nil { + t.Fatalf("decode rotated login response: %v", err) + } + if secondBody.CSRFToken == "" || secondBody.CSRFToken == firstBody.CSRFToken { + t.Fatal("rotated login did not issue a new session-bound CSRF token") + } + replayed := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", firstCookie.Value, "", "192.0.2.12:1234") + requireSessionProblem(t, replayed, http.StatusUnauthorized, "unauthenticated") + + for _, test := range []struct { + name string + origin string + csrf string + }{ + {name: "wrong origin", origin: "http://attacker.example", csrf: secondBody.CSRFToken}, + {name: "wrong CSRF token", origin: sessionHTTPTestOrigin, csrf: firstBody.CSRFToken}, + {name: "missing CSRF token", origin: sessionHTTPTestOrigin}, + } { + t.Run(test.name, func(t *testing.T) { + response := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", test.origin, secondCookie.Value, test.csrf, "192.0.2.13:1234") + requireSessionProblem(t, response, http.StatusForbidden, "csrf_check_failed") + if len(response.Header().Values("Set-Cookie")) != 0 { + t.Fatalf("rejected logout cleared the session cookie: %v", response.Header().Values("Set-Cookie")) + } + active := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", secondCookie.Value, "", "192.0.2.14:1234") + if active.Code != http.StatusOK { + t.Fatalf("rejected logout revoked the session: %d %s", active.Code, active.Body.String()) + } + }) + } + + logout := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", sessionHTTPTestOrigin, secondCookie.Value, secondBody.CSRFToken, "192.0.2.15:1234") + if logout.Code != http.StatusNoContent || logout.Body.Len() != 0 { + t.Fatalf("logout response = %d %q, want 204 with no body", logout.Code, logout.Body.String()) + } + requireExpiredSessionCookie(t, logout) + replayAfterLogout := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", secondCookie.Value, "", "192.0.2.16:1234") + requireSessionProblem(t, replayAfterLogout, http.StatusUnauthorized, "unauthenticated") + staleLogout := harness.request(t, http.MethodDelete, "/api/v1/identity/sessions/current", "", sessionHTTPTestOrigin, secondCookie.Value, secondBody.CSRFToken, "192.0.2.17:1234") + requireSessionProblem(t, staleLogout, http.StatusUnauthorized, "unauthenticated") + requireExpiredSessionCookie(t, staleLogout) + + for _, secret := range []string{firstCookie.Value, secondCookie.Value, sessionHTTPTestPass, "incorrect horse battery staple"} { + if secret != "" && strings.Contains(harness.logs.String(), secret) { + t.Fatalf("a session token or password reached request logs") + } + } +} + +func TestSessionExpiryAcrossAPIRestart(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout) + defer cancel() + first := newSessionHTTPHarness(ctx, t, env) + + passwordHash, err := first.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + absoluteEmail := "absolute@example.test" + idleEmail := "idle@example.test" + createSessionHTTPUser(ctx, t, first, absoluteEmail, passwordHash, true) + createSessionHTTPUser(ctx, t, first, idleEmail, passwordHash, true) + + absoluteLogin := loginSessionHTTP(t, first, absoluteEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.20:1234") + if absoluteLogin.Code != http.StatusCreated { + t.Fatalf("absolute-expiry login status = %d, body=%s", absoluteLogin.Code, absoluteLogin.Body.String()) + } + absoluteCookie := requireSessionCookie(t, absoluteLogin) + idleLogin := loginSessionHTTP(t, first, idleEmail, sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.21:1234") + if idleLogin.Code != http.StatusCreated { + t.Fatalf("idle-expiry login status = %d, body=%s", idleLogin.Code, idleLogin.Body.String()) + } + idleCookie := requireSessionCookie(t, idleLogin) + + second := newSessionHTTPHarness(ctx, t, env) + for _, cookie := range []*http.Cookie{absoluteCookie, idleCookie} { + response := second.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.22:1234") + if response.Code != http.StatusOK { + t.Fatalf("session did not survive an API handler restart: %d %s", response.Code, response.Body.String()) + } + } + + absoluteToken, err := domain.ParseSecretToken(absoluteCookie.Value) + if err != nil { + t.Fatalf("ParseSecretToken(absolute cookie) error = %v", err) + } + idleToken, err := domain.ParseSecretToken(idleCookie.Value) + if err != nil { + t.Fatalf("ParseSecretToken(idle cookie) error = %v", err) + } + now := second.clock.Now() + absoluteHash := absoluteToken.Hash() + idleHash := idleToken.Hash() + if _, err := second.pool.Exec(ctx, + `UPDATE sessions SET created_at = $1, last_seen_at = $1, expires_at = $2 WHERE token_hash = $3`, + now.Add(-2*time.Second), now.Add(-time.Second), absoluteHash[:], + ); err != nil { + t.Fatalf("expire absolute session: %v", err) + } + idleCreatedAt := now.Add(-env.Config.IdentitySessionIdleTimeout - 2*time.Second) + if _, err := second.pool.Exec(ctx, + `UPDATE sessions SET created_at = $1, last_seen_at = $2 WHERE token_hash = $3`, + idleCreatedAt, now.Add(-env.Config.IdentitySessionIdleTimeout-time.Second), idleHash[:], + ); err != nil { + t.Fatalf("age idle session: %v", err) + } + for _, cookie := range []*http.Cookie{absoluteCookie, idleCookie} { + response := second.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.23:1234") + requireSessionProblem(t, response, http.StatusUnauthorized, "unauthenticated") + } +} + +func TestShortIdleSessionRefreshesWhileActive(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), sessionHTTPTestTimeout) + defer cancel() + harness := newSessionHTTPHarnessWithSettings(ctx, t, env, identity.SessionSettings{ + ClientHourlyLimit: int64(env.Config.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(env.Config.IdentityLoginEmailHourlyLimit), + IdleTimeout: time.Minute, + AbsoluteLifetime: 2 * time.Minute, + }) + passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass) + if err != nil { + t.Fatalf("HashNewPassword() error = %v", err) + } + user := createSessionHTTPUser(ctx, t, harness, "short-idle@example.test", passwordHash, true) + login := loginSessionHTTP(t, harness, user.Email.Address(), sessionHTTPTestPass, sessionHTTPTestOrigin, "", "192.0.2.30:1234") + if login.Code != http.StatusCreated { + t.Fatalf("login status = %d, body=%s", login.Code, login.Body.String()) + } + cookie := requireSessionCookie(t, login) + + harness.clock.Advance(40 * time.Second) + firstActivity := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.31:1234") + if firstActivity.Code != http.StatusOK { + t.Fatalf("session expired before first activity: %d %s", firstActivity.Code, firstActivity.Body.String()) + } + harness.clock.Advance(40 * time.Second) + secondActivity := harness.request(t, http.MethodGet, "/api/v1/identity/sessions/current", "", "", cookie.Value, "", "192.0.2.32:1234") + if secondActivity.Code != http.StatusOK { + t.Fatalf("session was not refreshed by activity: %d %s", secondActivity.Code, secondActivity.Body.String()) + } +} diff --git a/backend/internal/adapter/primary/cli/mailretry/command.go b/backend/internal/adapter/primary/cli/mailretry/command.go new file mode 100644 index 0000000..9834756 --- /dev/null +++ b/backend/internal/adapter/primary/cli/mailretry/command.go @@ -0,0 +1,196 @@ +// Package mailretry implements the local operator command for inspecting and +// authorizing a retry of an unknown mail delivery. +package mailretry + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "strings" + "time" + + "github.com/google/uuid" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" +) + +const usage = "usage: mail-retry inspect --delivery | mail-retry retry --delivery --actor operator: --acknowledge-duplicate-risk" + +type action uint8 + +const ( + inspectAction action = iota + 1 + retryAction +) + +// Command is a parsed, validated local mail retry command. +type Command struct { + Action action + DeliveryID uuid.UUID + Actor string + AcknowledgeDuplicateRisk bool +} + +// Operator is the metadata-only and audit-backed retry usecase. +type Operator interface { + Inspect(ctx context.Context, deliveryID uuid.UUID) (notification.DeliveryRetryInspection, error) + RetryUnknown(ctx context.Context, deliveryID uuid.UUID, actor string, acknowledgeDuplicateRisk bool) (string, error) +} + +// Parse validates every argument before Run reads configuration or connects +// to PostgreSQL. +func Parse(args []string) (Command, error) { + if len(args) == 0 { + return Command{}, errors.New(usage) + } + + var command Command + var actor *string + var acknowledge *bool + switch args[0] { + case "inspect": + command.Action = inspectAction + case "retry": + command.Action = retryAction + default: + return Command{}, errors.New(usage) + } + + flags := flag.NewFlagSet("mail-retry "+args[0], flag.ContinueOnError) + flags.SetOutput(io.Discard) + deliveryID := flags.String("delivery", "", "delivery UUID") + if command.Action == retryAction { + actor = flags.String("actor", "", "operator handle") + acknowledge = flags.Bool("acknowledge-duplicate-risk", false, "acknowledge that a duplicate may be sent") + } + if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 { + return Command{}, errors.New(usage) + } + parsedID, err := uuid.Parse(strings.TrimSpace(*deliveryID)) + if err != nil || parsedID == uuid.Nil { + return Command{}, errors.New("delivery must be a non-zero UUID") + } + command.DeliveryID = parsedID + if command.Action == retryAction { + if _, err := domain.ParseMailRetryActor(strings.TrimSpace(*actor)); err != nil { + return Command{}, errors.New("actor must be operator:") + } + if !*acknowledge { + return Command{}, errors.New("--acknowledge-duplicate-risk is required") + } + command.Actor = strings.TrimSpace(*actor) + command.AcknowledgeDuplicateRisk = true + } + return command, nil +} + +// Run parses the command, loads only its database and mail-account settings +// from the supplied environment, then executes the operator usecase. It does +// not load dotenv files or read transport credentials. +func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error { + command, err := Parse(args) + if err != nil { + return err + } + if lookup == nil || output == nil { + return errors.New("mail retry command dependencies are required") + } + databaseURL := config.DatabaseURLFromEnv(lookup) + if databaseURL == "" { + return errors.New("DATABASE_URL is not set") + } + provider := strings.ToLower(strings.TrimSpace(envValue(lookup, "EMAIL_PROVIDER", ""))) + if provider != string(config.EmailProviderResend) { + return errors.New("mail retry is available only with EMAIL_PROVIDER=resend in this build") + } + accountLabel := strings.TrimSpace(envValue(lookup, "EMAIL_ACCOUNT", "default")) + account, err := domain.NewMailProviderAccount(provider, accountLabel) + if err != nil { + return errors.New("mail provider account configuration is invalid") + } + + pool, err := postgres.NewPool(ctx, databaseURL) + if err != nil { + return errors.New("database configuration is invalid") + } + defer pool.Close() + if err := pool.Ping(ctx); err != nil { + return errors.New("database is unavailable") + } + deliveries := postgres.NewDeliveryStore(pool).Deliveries() + operator, err := notification.NewDeliveryRetryOperator( + postgres.NewTransactor(pool), + deliveries, + account, + resend.IdempotencyWindow, + time.Now, + ) + if err != nil { + return errors.New("mail retry is unavailable") + } + return Execute(ctx, command, operator, output) +} + +// Execute prints the duplicate-risk warning before retry authorization can +// mutate the delivery or append an audit decision. +func Execute(ctx context.Context, command Command, operator Operator, output io.Writer) error { + if operator == nil || output == nil { + return errors.New("mail retry command dependencies are required") + } + snapshot, err := operator.Inspect(ctx, command.DeliveryID) + if err != nil { + return safeOperationError(err) + } + if command.Action == inspectAction { + if _, err := fmt.Fprintf(output, + "delivery: %s\nprovider: %s\nstatus: %s\nattempts: %d\n%s\n", + snapshot.DeliveryID, snapshot.Provider, snapshot.Status, snapshot.AttemptCount, notification.DuplicateRiskWarning, + ); err != nil { + return errors.New("could not write mail retry inspection") + } + return nil + } + if command.Action != retryAction || !command.AcknowledgeDuplicateRisk { + return errors.New(usage) + } + if _, err := fmt.Fprintln(output, notification.DuplicateRiskWarning); err != nil { + return errors.New("could not write duplicate-risk warning") + } + if _, err := operator.RetryUnknown(ctx, command.DeliveryID, command.Actor, command.AcknowledgeDuplicateRisk); err != nil { + return safeOperationError(err) + } + if _, err := fmt.Fprintln(output, "retry scheduled; audit decision recorded"); err != nil { + return errors.New("retry was scheduled, but the result could not be written") + } + return nil +} + +func envValue(lookup config.LookupEnv, name, fallback string) string { + value, ok := lookup(name) + if !ok || strings.TrimSpace(value) == "" { + return fallback + } + return value +} + +func safeOperationError(err error) error { + switch { + case errors.Is(err, outbound.ErrDeliveryNotFound): + return errors.New("delivery not found") + case errors.Is(err, outbound.ErrDeliveryRetryNotAllowed): + return errors.New("delivery is not eligible for manual retry") + case errors.Is(err, notification.ErrDuplicateRiskAcknowledgementRequired): + return errors.New("duplicate-risk acknowledgement is required") + case errors.Is(err, domain.ErrInvalidDelivery): + return errors.New("delivery or actor is invalid") + default: + return errors.New("mail retry operation failed") + } +} diff --git a/backend/internal/adapter/primary/cli/mailretry/command_test.go b/backend/internal/adapter/primary/cli/mailretry/command_test.go new file mode 100644 index 0000000..17116bd --- /dev/null +++ b/backend/internal/adapter/primary/cli/mailretry/command_test.go @@ -0,0 +1,142 @@ +package mailretry + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/notification" +) + +const testDeliveryID = "2e203b62-3fb5-4ef7-b118-360bbff7f2aa" + +func TestParseRequiresExplicitCommandFields(t *testing.T) { + tests := []struct { + name string + args []string + want string + }{ + {name: "command", args: nil, want: "usage:"}, + {name: "unknown command", args: []string{"send"}, want: "usage:"}, + {name: "inspect delivery", args: []string{"inspect"}, want: "non-zero UUID"}, + {name: "invalid delivery", args: []string{"inspect", "--delivery", "not-a-uuid"}, want: "non-zero UUID"}, + {name: "retry delivery", args: []string{"retry", "--actor", "operator:mail-ops", "--acknowledge-duplicate-risk"}, want: "non-zero UUID"}, + {name: "retry actor", args: []string{"retry", "--delivery", testDeliveryID, "--acknowledge-duplicate-risk"}, want: "actor must be"}, + {name: "retry acknowledgement", args: []string{"retry", "--delivery", testDeliveryID, "--actor", "operator:mail-ops"}, want: "--acknowledge-duplicate-risk is required"}, + {name: "invalid actor", args: []string{"retry", "--delivery", testDeliveryID, "--actor", "mail-ops", "--acknowledge-duplicate-risk"}, want: "actor must be"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + _, err := Parse(test.args) + if err == nil || !strings.Contains(err.Error(), test.want) { + t.Fatalf("Parse(%q) error = %v, want text %q", test.args, err, test.want) + } + }) + } +} + +func TestRunValidatesArgumentsBeforeReadingEnvironment(t *testing.T) { + var reads int + err := Run(context.Background(), []string{"retry", "--delivery", testDeliveryID, "--actor", "operator:mail-ops"}, func(string) (string, bool) { + reads++ + return "", false + }, &bytes.Buffer{}) + if err == nil || reads != 0 { + t.Fatalf("Run() error = %v, environment reads = %d; want argument error before config access", err, reads) + } +} + +func TestRunDoesNotPrintDatabaseURL(t *testing.T) { + const secretURL = "postgres://operator:secret-password@127.0.0.1:1/mail" + lookup := func(key string) (string, bool) { + switch key { + case "DATABASE_URL": + return secretURL, true + case "EMAIL_PROVIDER": + return "resend", true + default: + return "", false + } + } + var output bytes.Buffer + err := Run(context.Background(), []string{"inspect", "--delivery", testDeliveryID}, lookup, &output) + if err == nil || strings.Contains(err.Error(), "secret-password") || strings.Contains(output.String(), "secret-password") { + t.Fatalf("Run() error/output leaked connection details: error %v, output %q", err, output.String()) + } +} + +func TestExecuteWarnsBeforeSchedulingAndRedactsMetadata(t *testing.T) { + deliveryID := uuid.MustParse(testDeliveryID) + var output bytes.Buffer + operator := &testOperator{ + inspection: notification.DeliveryRetryInspection{ + DeliveryID: deliveryID, + Provider: "resend", + ProviderAccount: "sensitive-account-label", + Status: domain.DeliveryStatusUnknown, + AttemptCount: 2, + }, + output: &output, + } + command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true} + if err := Execute(context.Background(), command, operator, &output); err != nil { + t.Fatalf("Execute() error = %v", err) + } + if !operator.retryCalled || !strings.Contains(output.String(), notification.DuplicateRiskWarning) || + strings.Contains(output.String(), "sensitive-account-label") { + t.Fatalf("Execute() output/calls = %q, %t; want warning before retry and redacted account", output.String(), operator.retryCalled) + } +} + +func TestExecuteDoesNotScheduleWhenWarningCannotBeWritten(t *testing.T) { + deliveryID := uuid.MustParse(testDeliveryID) + operator := &testOperator{inspection: notification.DeliveryRetryInspection{DeliveryID: deliveryID, Status: domain.DeliveryStatusUnknown}} + command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true} + if err := Execute(context.Background(), command, operator, errorWriter{}); err == nil || operator.retryCalled { + t.Fatalf("Execute() error = %v, retry called = %t; want output error before mutation", err, operator.retryCalled) + } +} + +func TestExecuteReturnsSafeStateError(t *testing.T) { + deliveryID := uuid.MustParse(testDeliveryID) + operator := &testOperator{ + inspection: notification.DeliveryRetryInspection{DeliveryID: deliveryID, Status: domain.DeliveryStatusUnknown}, + retryErr: errors.Join(outbound.ErrDeliveryRetryNotAllowed, errors.New("recipient private@example.invalid")), + } + var output bytes.Buffer + command := Command{Action: retryAction, DeliveryID: deliveryID, Actor: "operator:mail-ops", AcknowledgeDuplicateRisk: true} + err := Execute(context.Background(), command, operator, &output) + if err == nil || err.Error() != "delivery is not eligible for manual retry" || strings.Contains(err.Error(), "private@example.invalid") { + t.Fatalf("Execute() error = %v; want a safe state error", err) + } +} + +type testOperator struct { + inspection notification.DeliveryRetryInspection + inspectErr error + retryErr error + output *bytes.Buffer + retryCalled bool +} + +func (operator *testOperator) Inspect(context.Context, uuid.UUID) (notification.DeliveryRetryInspection, error) { + return operator.inspection, operator.inspectErr +} + +func (operator *testOperator) RetryUnknown(context.Context, uuid.UUID, string, bool) (string, error) { + operator.retryCalled = true + if operator.output != nil && !strings.Contains(operator.output.String(), notification.DuplicateRiskWarning) { + return "", errors.New("retry called before warning") + } + return "", operator.retryErr +} + +type errorWriter struct{} + +func (errorWriter) Write([]byte) (int, error) { return 0, errors.New("output unavailable") } diff --git a/backend/internal/adapter/primary/http/middleware/session.go b/backend/internal/adapter/primary/http/middleware/session.go new file mode 100644 index 0000000..a32394d --- /dev/null +++ b/backend/internal/adapter/primary/http/middleware/session.go @@ -0,0 +1,81 @@ +package middleware + +import ( + "context" + "crypto/subtle" + "net/http" + + "lincodex/backend/internal/domain" +) + +const SessionCookieName = "__Host-lincodex_session" + +type sessionRequestMetadataKey struct{} + +type sessionRequestMetadata struct { + origin string + originValid bool + incomingToken domain.SecretToken +} + +// SessionRequestMetadata records the browser Origin and an optional incoming +// session token for the handwritten identity operations. It never trusts +// forwarded headers and rejects duplicate or malformed cookie values. +func SessionRequestMetadata() func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + metadata := sessionRequestMetadata{} + origins := r.Header.Values("Origin") + if len(origins) == 1 { + metadata.origin = origins[0] + metadata.originValid = true + } + cookieCount := 0 + for _, cookie := range r.Cookies() { + if cookie.Name != SessionCookieName { + continue + } + cookieCount++ + if token, err := domain.ParseSecretToken(cookie.Value); err == nil { + metadata.incomingToken = token + } + } + if cookieCount != 1 { + metadata.incomingToken = domain.SecretToken{} + } + ctx := context.WithValue(r.Context(), sessionRequestMetadataKey{}, metadata) + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +} + +// RequestOrigin returns the sole Origin header value when one was provided. +func RequestOrigin(ctx context.Context) (string, bool) { + metadata, ok := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata) + return metadata.origin, ok && metadata.originValid +} + +// IncomingSessionToken returns a parsed token from exactly one session cookie. +// The zero value means missing, malformed, or duplicated input. +func IncomingSessionToken(ctx context.Context) domain.SecretToken { + metadata, ok := ctx.Value(sessionRequestMetadataKey{}).(sessionRequestMetadata) + if !ok { + return domain.SecretToken{} + } + return metadata.incomingToken +} + +// SessionCookieMatches reports whether the generated API parser's value is +// the sole valid session cookie recorded at the HTTP boundary. +func SessionCookieMatches(ctx context.Context, rawToken string) bool { + stored := IncomingSessionToken(ctx) + if stored.IsZero() { + return false + } + provided, err := domain.ParseSecretToken(rawToken) + if err != nil { + return false + } + storedHash, providedHash := stored.Hash(), provided.Hash() + return subtle.ConstantTimeCompare(storedHash[:], providedHash[:]) == 1 +} diff --git a/backend/internal/adapter/primary/http/middleware/session_test.go b/backend/internal/adapter/primary/http/middleware/session_test.go new file mode 100644 index 0000000..37c90c0 --- /dev/null +++ b/backend/internal/adapter/primary/http/middleware/session_test.go @@ -0,0 +1,96 @@ +package middleware + +import ( + "net/http" + "net/http/httptest" + "testing" + + "lincodex/backend/internal/domain" +) + +func TestSessionRequestMetadataAcceptsOneOriginAndSessionCookie(t *testing.T) { + token, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + var origin string + var originOK, cookieMatches bool + var incoming domain.SecretToken + handler := SessionRequestMetadata()(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { + origin, originOK = RequestOrigin(request.Context()) + incoming = IncomingSessionToken(request.Context()) + cookieMatches = SessionCookieMatches(request.Context(), token.Reveal()) + })) + request := httptest.NewRequest(http.MethodPost, "/api/v1/identity/sessions", nil) + request.Header.Set("Origin", "https://app.example.com") + request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: token.Reveal()}) + handler.ServeHTTP(httptest.NewRecorder(), request) + if !originOK || origin != "https://app.example.com" || incoming.Hash() != token.Hash() || !cookieMatches { + t.Fatal("metadata did not preserve the sole Origin and parsed session cookie") + } +} + +func TestSessionRequestMetadataRejectsAmbiguousOrMalformedBrowserHeaders(t *testing.T) { + token, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + tests := map[string]func(*http.Request){ + "duplicate cookie": func(request *http.Request) { + request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: token.Reveal()}) + request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: token.Reveal()}) + }, + "malformed cookie": func(request *http.Request) { + request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: "short"}) + }, + "duplicate origin": func(request *http.Request) { + request.Header.Add("Origin", "https://app.example.com") + request.Header.Add("Origin", "https://attacker.example") + }, + "forwarded origin only": func(request *http.Request) { + request.Header.Set("X-Forwarded-Host", "app.example.com") + }, + } + for name, prepare := range tests { + t.Run(name, func(t *testing.T) { + var origin string + var originOK bool + var incoming domain.SecretToken + handler := SessionRequestMetadata()(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { + origin, originOK = RequestOrigin(request.Context()) + incoming = IncomingSessionToken(request.Context()) + })) + request := httptest.NewRequest(http.MethodPost, "/api/v1/identity/sessions", nil) + prepare(request) + handler.ServeHTTP(httptest.NewRecorder(), request) + if originOK || origin != "" || !incoming.IsZero() { + t.Fatalf("ambiguous input was accepted: origin present=%v token present=%v", originOK, !incoming.IsZero()) + } + }) + } +} + +func TestSessionCookieMatchesOnlyTheBoundaryToken(t *testing.T) { + first, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + second, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + request := httptest.NewRequest(http.MethodGet, "/api/v1/identity/me", nil) + request.AddCookie(&http.Cookie{Name: SessionCookieName, Value: first.Reveal()}) + var matches []bool + handler := SessionRequestMetadata()(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) { + matches = []bool{ + SessionCookieMatches(request.Context(), first.Reveal()), + SessionCookieMatches(request.Context(), second.Reveal()), + SessionCookieMatches(request.Context(), "short"), + } + })) + handler.ServeHTTP(httptest.NewRecorder(), request) + if len(matches) != 3 || !matches[0] || matches[1] || matches[2] { + t.Fatalf("SessionCookieMatches() = %v", matches) + } +} diff --git a/backend/internal/adapter/primary/http/router.go b/backend/internal/adapter/primary/http/router.go index 88ce0a9..2b7cff7 100644 --- a/backend/internal/adapter/primary/http/router.go +++ b/backend/internal/adapter/primary/http/router.go @@ -61,6 +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. + router.Use(httpmiddleware.SessionRequestMetadata()) router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath)) router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute)) router.Group(func(operational chi.Router) { @@ -73,7 +76,7 @@ func NewRouter( // server aborts the response; the kit Recoverer would swallow that panic. router.Group(func(public chi.Router) { public.Use(problems.Recover) - public.Handle(apiWildcard, apiServer) + public.Handle(apiWildcard, clearUnauthorizedLogoutCookie(apiServer)) // Unknown /api paths outside the versioned prefix are also problems, // so every error under /api has the contract's format. public.Handle(apiRoot, http.HandlerFunc(problems.NotFound)) @@ -82,6 +85,30 @@ func NewRouter( return router, nil } +func clearUnauthorizedLogoutCookie(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCookie := r.Method == http.MethodDelete && r.URL.Path == publicPrefix+"/identity/sessions/current" + next.ServeHTTP(&logoutCookieWriter{ResponseWriter: w, clearCookie: clearCookie}, r) + }) +} + +type logoutCookieWriter struct { + http.ResponseWriter + + clearCookie bool +} + +func (writer *logoutCookieWriter) WriteHeader(status int) { + if writer.clearCookie && status == http.StatusUnauthorized { + writer.Header().Add("Set-Cookie", v1.ExpiredSessionCookie()) + } + writer.ResponseWriter.WriteHeader(status) +} + +func (writer *logoutCookieWriter) Unwrap() http.ResponseWriter { + return writer.ResponseWriter +} + // apiWildcard is the chi pattern that mounts the generated server. const apiWildcard = publicPrefix + "/*" diff --git a/backend/internal/adapter/primary/http/v1/api.go b/backend/internal/adapter/primary/http/v1/api.go new file mode 100644 index 0000000..d75b6a1 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/api.go @@ -0,0 +1,65 @@ +package v1 + +import ( + "context" + "errors" + + "github.com/ogen-go/ogen/ogenerrors" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/usecase/identity" +) + +// Handler is the composite implementation of the generated api.Handler. +// Unimplemented operations stay on ogen's embedded fallback until a business +// handler is added for them. +type Handler struct { + api.UnimplementedHandler + + health *HealthHandler + identity *IdentityHandler + problems *problem.Responder +} + +var _ api.Handler = (*Handler)(nil) + +// HandlerOption adds a business-area handler to Handler. +type HandlerOption func(*Handler) + +// WithIdentity serves the configured identity operations. +func WithIdentity(identity *IdentityHandler) HandlerOption { + return func(handler *Handler) { handler.identity = identity } +} + +func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler { + handler := &Handler{health: health, problems: problems} + for _, option := range options { + option(handler) + } + return handler +} + +// NewError maps security failures to fixed public problems. Other errors are +// passed to the responder, which logs them and does not expose their text. +func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode { + var securityError *ogenerrors.SecurityError + if errors.As(err, &securityError) { + switch { + case errors.Is(securityError.Err, errCsrfCheckFailed): + return problem.New(ctx, api.ProblemCodeCsrfCheckFailed) + case errors.Is(securityError.Err, ogenerrors.ErrSecurityRequirementIsNotSatisfied): + if _, ok := PrincipalFromContext(ctx); ok { + return problem.New(ctx, api.ProblemCodeCsrfCheckFailed) + } + return problem.New(ctx, api.ProblemCodeUnauthenticated) + case errors.Is(securityError.Err, ogenerrors.ErrSkipServerSecurity), + errors.Is(securityError.Err, identity.ErrUnauthenticated), + errors.Is(securityError.Err, errSessionsNotImplemented): + return problem.New(ctx, api.ProblemCodeUnauthenticated) + default: + return handler.problems.HandlerError(ctx, securityError.Err) + } + } + return handler.problems.HandlerError(ctx, err) +} diff --git a/backend/internal/adapter/primary/http/v1/auth.go b/backend/internal/adapter/primary/http/v1/auth.go new file mode 100644 index 0000000..c0af2b1 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/auth.go @@ -0,0 +1,292 @@ +package v1 + +import ( + "context" + "errors" + "math" + "net/http" + "strings" + "time" + + "lincodex/backend/internal/adapter/primary/http/api" + httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/identity" +) + +func (handler *Handler) RegisterAccount( + ctx context.Context, + request *api.RegistrationRequest, + params api.RegisterAccountParams, +) (api.RegisterAccountRes, error) { + if handler.identity == nil { + return handler.UnimplementedHandler.RegisterAccount(ctx, request, params) + } + return handler.identity.RegisterAccount(ctx, request, params) +} + +func (handler *Handler) ResendEmailVerification( + ctx context.Context, + request *api.EmailVerificationResendRequest, +) (api.ResendEmailVerificationRes, error) { + if handler.identity == nil { + return handler.UnimplementedHandler.ResendEmailVerification(ctx, request) + } + return handler.identity.ResendEmailVerification(ctx, request) +} + +func (handler *Handler) ConfirmEmail( + ctx context.Context, + request *api.EmailVerificationRequest, + params api.ConfirmEmailParams, +) (api.ConfirmEmailRes, error) { + if handler.identity == nil || handler.identity.confirmation == nil { + return handler.UnimplementedHandler.ConfirmEmail(ctx, request, params) + } + return handler.identity.ConfirmEmail(ctx, request, params) +} + +func (handler *Handler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) { + if handler.identity == nil || handler.identity.sessions == nil { + return handler.UnimplementedHandler.Login(ctx, request) + } + return handler.identity.Login(ctx, request) +} + +func (handler *Handler) GetCurrentSession(ctx context.Context) (api.GetCurrentSessionRes, error) { + if handler.identity == nil || handler.identity.sessions == nil { + return handler.UnimplementedHandler.GetCurrentSession(ctx) + } + return handler.identity.GetCurrentSession(ctx) +} + +func (handler *Handler) Logout(ctx context.Context) (api.LogoutRes, error) { + if handler.identity == nil || handler.identity.sessions == nil { + return handler.UnimplementedHandler.Logout(ctx) + } + return handler.identity.Logout(ctx) +} + +func (handler *IdentityHandler) RegisterAccount( + ctx context.Context, + request *api.RegistrationRequest, + params api.RegisterAccountParams, +) (api.RegisterAccountRes, error) { + err := handler.registration.Register(ctx, identity.RegisterCommand{ + IdempotencyKey: params.IdempotencyKey, + Email: string(request.Email), + Password: string(request.Password), + Scenario: string(request.Scenario), + ConsentTextVersion: string(request.ConsentC1.TextVersion), + ClientKey: clientKey(ctx), + }) + switch { + case err == nil: + return accepted(), nil + case errors.Is(err, identity.ErrInvalidField): + return (*api.RegisterAccountBadRequest)(&invalidFieldProblem(ctx, err).Response), nil + case errors.Is(err, identity.ErrIdempotencyKeyReused): + return (*api.RegisterAccountUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil + } + if limited, ok := rateLimited(ctx, err); ok { + return limited, nil + } + return nil, err +} + +func (handler *IdentityHandler) ResendEmailVerification( + ctx context.Context, + request *api.EmailVerificationResendRequest, +) (api.ResendEmailVerificationRes, error) { + if handler.registration == nil { + return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured") + } + err := handler.registration.ResendVerification(ctx, identity.ResendCommand{ + Email: string(request.Email), + ClientKey: clientKey(ctx), + }) + switch { + case err == nil: + return accepted(), nil + case errors.Is(err, identity.ErrInvalidField): + return (*api.ResendEmailVerificationBadRequest)(&invalidFieldProblem(ctx, err).Response), nil + } + if limited, ok := rateLimited(ctx, err); ok { + return limited, nil + } + return nil, err +} + +func (handler *IdentityHandler) ConfirmEmail( + ctx context.Context, + request *api.EmailVerificationRequest, + params 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 { + return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil + } + + result, err := handler.confirmation.Confirm(ctx, identity.ConfirmCommand{ + Token: string(request.Token), + Password: request.Password, + ClientKey: clientKey(ctx), + }) + switch { + case err == nil: + return &api.EmailVerificationResult{ + EmailVerified: api.EmailVerificationResultEmailVerifiedTrue, + Scenario: api.AccountScenario(result.Scenario), + OnboardingStep: api.OnboardingStep(result.OnboardingStep), + }, nil + case errors.Is(err, identity.ErrVerificationTokenInvalid): + return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil + case errors.Is(err, identity.ErrVerificationTokenExpired): + return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenExpired).Response), nil + } + if limited, ok := rateLimited(ctx, err); ok { + return limited, nil + } + return nil, err +} + +func (handler *IdentityHandler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) { + if !originAllowed(ctx, handler.sessionOrigin) { + return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil + } + result, err := handler.sessions.Login(ctx, identity.LoginCommand{ + Email: string(request.Email), + Password: string(request.Password), + ClientKey: clientKey(ctx), + Incoming: httpmiddleware.IncomingSessionToken(ctx), + }) + switch { + case err == nil: + return &api.SessionHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + SetCookie: sessionCookie(result.Token, result.Session), + Response: api.Session{ + Account: accountFromUser(result.User), + CsrfToken: api.CsrfToken(result.CSRFToken), + }, + }, nil + case errors.Is(err, identity.ErrInvalidField): + return (*api.LoginBadRequest)(&invalidFieldProblem(ctx, err).Response), nil + case errors.Is(err, identity.ErrInvalidCredentials): + return (*api.LoginUnauthorized)(&problem.New(ctx, api.ProblemCodeInvalidCredentials).Response), nil + case errors.Is(err, identity.ErrEmailNotVerified): + return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil + } + if limited, ok := rateLimited(ctx, err); ok { + return limited, nil + } + return nil, err +} + +func (handler *IdentityHandler) GetCurrentSession(ctx context.Context) (api.GetCurrentSessionRes, error) { + session, ok := sessionFromContext(ctx) + if !ok || !session.EmailVerified { + return unauthenticatedProblemResponse(ctx), nil + } + return &api.GetCurrentSessionOKHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: api.Session{ + Account: accountFromUser(session.User), + CsrfToken: api.CsrfToken(session.CSRFToken), + }, + }, nil +} + +func (handler *IdentityHandler) Logout(ctx context.Context) (api.LogoutRes, error) { + session, ok := sessionFromContext(ctx) + if !ok || !session.EmailVerified { + return unauthenticatedProblemResponse(ctx), nil + } + if err := handler.sessions.Logout(ctx, session.SessionID); err != nil { + if errors.Is(err, identity.ErrUnauthenticated) { + return unauthenticatedProblemResponse(ctx), nil + } + return nil, err + } + return &api.LogoutNoContent{SetCookie: ExpiredSessionCookie()}, nil +} + +func accepted() *api.IdentityRequestAccepted { + return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted} +} + +// clientKey is the limiter key of the client address resolved through trusted +// proxies. Without the middleware only per-address limits apply. +func clientKey(ctx context.Context) string { + address, ok := httpmiddleware.ClientAddr(ctx) + if !ok { + return "" + } + return httpmiddleware.LimiterKey(address) +} + +func invalidFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode { + field, ok := errors.AsType[*identity.InvalidFieldError](err) + if !ok { + return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "") + } + location := api.ProblemFieldLocationBody + if field.Pointer == "/Idempotency-Key" { + location = api.ProblemFieldLocationHeader + } + return problem.InvalidField(ctx, location, field.Pointer) +} + +func rateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) { + limited, ok := errors.AsType[*identity.RateLimitedError](err) + if !ok { + return nil, false + } + return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), true +} + +func wholeSeconds(wait time.Duration) int32 { + return int32(min(math.Ceil(wait.Seconds()), math.MaxInt32)) +} + +func originAllowed(ctx context.Context, expected string) bool { + origin, ok := httpmiddleware.RequestOrigin(ctx) + return ok && origin == expected +} + +func unauthenticatedProblemResponse(ctx context.Context) *api.Problem { + response := problem.New(ctx, api.ProblemCodeUnauthenticated).Response + return &response +} + +func sessionCookie(token domain.SecretToken, session domain.Session) string { + maxAge := int(math.Ceil(session.ExpiresAt.Sub(session.CreatedAt).Seconds())) + cookie := &http.Cookie{ + Name: httpmiddleware.SessionCookieName, + Value: token.Reveal(), + Path: "/", + MaxAge: maxAge, + Expires: session.ExpiresAt.UTC(), + Secure: true, + HttpOnly: true, + SameSite: http.SameSiteStrictMode, + } + return cookie.String() +} + +func ExpiredSessionCookie() string { + return (&http.Cookie{ + Name: httpmiddleware.SessionCookieName, + Value: "", + Path: "/", + MaxAge: -1, + Expires: time.Unix(1, 0).UTC(), + Secure: true, + HttpOnly: true, + SameSite: http.SameSiteStrictMode, + }).String() +} diff --git a/backend/internal/adapter/primary/http/v1/handler.go b/backend/internal/adapter/primary/http/v1/handler.go deleted file mode 100644 index 3eb961b..0000000 --- a/backend/internal/adapter/primary/http/v1/handler.go +++ /dev/null @@ -1,98 +0,0 @@ -package v1 - -import ( - "context" - - "lincodex/backend/internal/adapter/primary/http/api" - "lincodex/backend/internal/adapter/primary/http/problem" -) - -// Handler is the composite implementation of the generated api.Handler. -// -// The embedded api.UnimplementedHandler keeps the backend compiling after the -// contract gains an operation that has no business implementation yet. Such an -// operation returns ht.ErrNotImplemented without side effects. The generated -// server passes that error to the ErrorHandler configured in the router, which -// answers 501 with code not_implemented, before it would call NewError. -// -// The contract's common default response makes ogen add NewError to -// api.Handler. The embedded api.UnimplementedHandler.NewError returns a zero -// status code that the generated encoder sends as HTTP 200, so Handler defines -// NewError explicitly: *ogenerrors.SecurityError, which the generated server -// passes to it directly, becomes 401, and every other error becomes 500 with a -// fixed body and is logged here, never exposing err.Error(). Errors of the -// generated *api.ProblemStatusCode type are encoded before NewError is called, -// so operations return them for expected failures such as 403 or 404. -// -// Each implemented operation gets an explicit method here that delegates to -// the handler owning it. Each implemented operation also gets a router test -// through v1.NewHandler that asserts a non-501 response, because renaming an -// operationId would otherwise silently fall back to the embedded 501 method. -type Handler struct { - api.UnimplementedHandler - - health *HealthHandler - identity *IdentityHandler - problems *problem.Responder -} - -var _ api.Handler = (*Handler)(nil) - -// HandlerOption adds the handler of a business area to Handler. -type HandlerOption func(*Handler) - -// WithIdentity serves the registration operations. A nil handler leaves them -// to the embedded api.UnimplementedHandler, as when no database is -// configured. -func WithIdentity(identity *IdentityHandler) HandlerOption { - return func(handler *Handler) { handler.identity = identity } -} - -func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler { - handler := &Handler{health: health, problems: problems} - for _, option := range options { - option(handler) - } - return handler -} - -func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) { - return handler.health.GetHealthz(ctx) -} - -func (handler *Handler) RegisterAccount( - ctx context.Context, - request *api.RegistrationRequest, - params api.RegisterAccountParams, -) (api.RegisterAccountRes, error) { - if handler.identity == nil { - return handler.UnimplementedHandler.RegisterAccount(ctx, request, params) - } - return handler.identity.RegisterAccount(ctx, request, params) -} - -func (handler *Handler) ResendEmailVerification( - ctx context.Context, - request *api.EmailVerificationResendRequest, -) (api.ResendEmailVerificationRes, error) { - if handler.identity == nil { - return handler.UnimplementedHandler.ResendEmailVerification(ctx, request) - } - return handler.identity.ResendEmailVerification(ctx, request) -} - -func (handler *Handler) ConfirmEmail( - ctx context.Context, - request *api.EmailVerificationRequest, - params api.ConfirmEmailParams, -) (api.ConfirmEmailRes, error) { - if handler.identity == nil || handler.identity.confirmation == nil { - return handler.UnimplementedHandler.ConfirmEmail(ctx, request, params) - } - return handler.identity.ConfirmEmail(ctx, request, params) -} - -// NewError implements api.Handler for errors returned by operations. -func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode { - return handler.problems.HandlerError(ctx, err) -} diff --git a/backend/internal/adapter/primary/http/v1/healthz.go b/backend/internal/adapter/primary/http/v1/healthz.go index 7a36989..2107b0c 100644 --- a/backend/internal/adapter/primary/http/v1/healthz.go +++ b/backend/internal/adapter/primary/http/v1/healthz.go @@ -23,6 +23,10 @@ func (handler *HealthHandler) GetHealthz(context.Context) (*api.HealthResponse, return &api.HealthResponse{Status: api.HealthResponseStatusOk}, nil } +func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) { + return handler.health.GetHealthz(ctx) +} + func (handler *HealthHandler) Healthz(w http.ResponseWriter, _ *http.Request) { writeStatus(w, http.StatusOK, "ok") } diff --git a/backend/internal/adapter/primary/http/v1/identity.go b/backend/internal/adapter/primary/http/v1/identity.go index 311e433..95f6996 100644 --- a/backend/internal/adapter/primary/http/v1/identity.go +++ b/backend/internal/adapter/primary/http/v1/identity.go @@ -2,14 +2,7 @@ package v1 import ( "context" - "errors" - "math" - "strings" - "time" - "lincodex/backend/internal/adapter/primary/http/api" - httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" - "lincodex/backend/internal/adapter/primary/http/problem" "lincodex/backend/internal/usecase/identity" ) @@ -28,12 +21,13 @@ type EmailConfirmation interface { // IdentityHandlerOption configures an optional identity operation. type IdentityHandlerOption func(*IdentityHandler) -// IdentityHandler serves anonymous registration, resend, and confirmation -// operations. +// IdentityHandler serves authentication and account identity operations. type IdentityHandler struct { registration AccountRegistration confirmation EmailConfirmation confirmationOrigin string + sessions *identity.SessionService + sessionOrigin string } func NewIdentityHandler(registration AccountRegistration, options ...IdentityHandlerOption) *IdentityHandler { @@ -53,130 +47,12 @@ func WithEmailConfirmation(confirmation EmailConfirmation, publicOrigin string) } } -func (handler *IdentityHandler) RegisterAccount( - ctx context.Context, - request *api.RegistrationRequest, - params api.RegisterAccountParams, -) (api.RegisterAccountRes, error) { - err := handler.registration.Register(ctx, identity.RegisterCommand{ - IdempotencyKey: params.IdempotencyKey, - Email: string(request.Email), - Password: string(request.Password), - Scenario: string(request.Scenario), - ConsentTextVersion: string(request.ConsentC1.TextVersion), - ClientKey: clientKey(ctx), - }) - switch { - case err == nil: - return accepted(), nil - case errors.Is(err, identity.ErrInvalidField): - return (*api.RegisterAccountBadRequest)(&invalidFieldProblem(ctx, err).Response), nil - case errors.Is(err, identity.ErrIdempotencyKeyReused): - return (*api.RegisterAccountUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil +// 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 { + return func(handler *IdentityHandler) { + handler.sessions = sessions + handler.sessionOrigin = publicOrigin } - if limited, ok := rateLimited(ctx, err); ok { - return limited, nil - } - return nil, err -} - -func (handler *IdentityHandler) ResendEmailVerification( - ctx context.Context, - request *api.EmailVerificationResendRequest, -) (api.ResendEmailVerificationRes, error) { - if handler.registration == nil { - return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured") - } - err := handler.registration.ResendVerification(ctx, identity.ResendCommand{ - Email: string(request.Email), - ClientKey: clientKey(ctx), - }) - switch { - case err == nil: - return accepted(), nil - case errors.Is(err, identity.ErrInvalidField): - return (*api.ResendEmailVerificationBadRequest)(&invalidFieldProblem(ctx, err).Response), nil - } - if limited, ok := rateLimited(ctx, err); ok { - return limited, nil - } - return nil, err -} - -func (handler *IdentityHandler) ConfirmEmail( - ctx context.Context, - request *api.EmailVerificationRequest, - params 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 { - return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil - } - - result, err := handler.confirmation.Confirm(ctx, identity.ConfirmCommand{ - Token: string(request.Token), - Password: request.Password, - ClientKey: clientKey(ctx), - }) - switch { - case err == nil: - return &api.EmailVerificationResult{ - EmailVerified: api.EmailVerificationResultEmailVerifiedTrue, - Scenario: api.AccountScenario(result.Scenario), - OnboardingStep: api.OnboardingStep(result.OnboardingStep), - }, nil - case errors.Is(err, identity.ErrVerificationTokenInvalid): - return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil - case errors.Is(err, identity.ErrVerificationTokenExpired): - return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenExpired).Response), nil - } - if limited, ok := rateLimited(ctx, err); ok { - return limited, nil - } - return nil, err -} - -func accepted() *api.IdentityRequestAccepted { - return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted} -} - -// clientKey is the limiter key of the client network address that the -// ClientIP middleware resolved. Without it, for example when the middleware -// is not mounted, the per-client limit is skipped and only the per-address -// limits apply: a shared bucket would let one client lock everyone out. -func clientKey(ctx context.Context) string { - address, ok := httpmiddleware.ClientAddr(ctx) - if !ok { - return "" - } - return httpmiddleware.LimiterKey(address) -} - -func invalidFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode { - field, ok := errors.AsType[*identity.InvalidFieldError](err) - if !ok { - return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "") - } - location := api.ProblemFieldLocationBody - if field.Pointer == "/Idempotency-Key" { - location = api.ProblemFieldLocationHeader - } - return problem.InvalidField(ctx, location, field.Pointer) -} - -func rateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) { - limited, ok := errors.AsType[*identity.RateLimitedError](err) - if !ok { - return nil, false - } - return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), true -} - -// wholeSeconds rounds a wait up, so a client that waits the stated time is -// not refused again for the remainder. -func wholeSeconds(wait time.Duration) int32 { - return int32(min(math.Ceil(wait.Seconds()), math.MaxInt32)) } diff --git a/backend/internal/adapter/primary/http/v1/principal.go b/backend/internal/adapter/primary/http/v1/principal.go new file mode 100644 index 0000000..b61577d --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/principal.go @@ -0,0 +1,59 @@ +package v1 + +import ( + "context" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/identity" +) + +type principalContextKey struct{} + +type sessionContextKey struct{} + +// Principal is the authenticated account identity available to handwritten +// HTTP handlers. The ID comes from PostgreSQL session state, never a request +// body or path parameter. +type Principal struct { + UserID uuid.UUID + EmailVerified bool +} + +type authenticatedSession struct { + Principal + + User domain.User + SessionID uuid.UUID + CSRFToken string +} + +// PrincipalFromContext returns the account identity installed by session +// security middleware, if the request has an authenticated session. +func PrincipalFromContext(ctx context.Context) (Principal, bool) { + if ctx == nil { + return Principal{}, false + } + principal, ok := ctx.Value(principalContextKey{}).(Principal) + return principal, ok && principal.UserID != uuid.Nil +} + +func withAuthenticatedSession(ctx context.Context, session identity.AuthenticatedSession) context.Context { + principal := Principal{UserID: session.User.ID, EmailVerified: session.User.EmailVerified()} + ctx = context.WithValue(ctx, principalContextKey{}, principal) + return context.WithValue(ctx, sessionContextKey{}, authenticatedSession{ + Principal: principal, + User: session.User, + SessionID: session.SessionID, + CSRFToken: session.CSRFToken, + }) +} + +func sessionFromContext(ctx context.Context) (authenticatedSession, bool) { + if ctx == nil { + return authenticatedSession{}, false + } + session, ok := ctx.Value(sessionContextKey{}).(authenticatedSession) + return session, ok && session.UserID != uuid.Nil && session.SessionID != uuid.Nil +} diff --git a/backend/internal/adapter/primary/http/v1/session.go b/backend/internal/adapter/primary/http/v1/session.go new file mode 100644 index 0000000..fb5daa2 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/session.go @@ -0,0 +1,89 @@ +package v1 + +import ( + "context" + "crypto/hmac" + "errors" + "fmt" + + "github.com/ogen-go/ogen/ogenerrors" + + "lincodex/backend/internal/adapter/primary/http/api" + httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" + "lincodex/backend/internal/usecase/identity" +) + +var errCsrfCheckFailed = errors.New("CSRF check failed") + +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. +type SessionSecurity struct { + authenticator SessionAuthenticator + publicOrigin string +} + +var _ api.SecurityHandler = (*SessionSecurity)(nil) + +func NewSessionSecurity(authenticator SessionAuthenticator, publicOrigin string) *SessionSecurity { + return &SessionSecurity{authenticator: authenticator, publicOrigin: publicOrigin} +} + +func (handler *IdentityHandler) SessionSecurity() *SessionSecurity { + if handler == nil || handler.sessions == nil { + return NewSessionSecurity(nil, "") + } + return NewSessionSecurity(handler.sessions, handler.sessionOrigin) +} + +func (security *SessionSecurity) HandleSessionCookie( + ctx context.Context, + operation api.OperationName, + cookie api.SessionCookie, +) (context.Context, error) { + if !sessionOperationAllowed(operation) || security == nil || security.authenticator == nil || + !httpmiddleware.SessionCookieMatches(ctx, cookie.APIKey) { + return ctx, ogenerrors.ErrSkipServerSecurity + } + authenticated, err := security.authenticator.Authenticate(ctx, cookie.APIKey) + if errors.Is(err, identity.ErrUnauthenticated) { + return ctx, ogenerrors.ErrSkipServerSecurity + } + if err != nil { + return ctx, fmt.Errorf("SessionSecurity.HandleSessionCookie - authenticate session: %w", err) + } + return withAuthenticatedSession(ctx, authenticated), nil +} + +func (security *SessionSecurity) HandleSessionCsrf( + ctx context.Context, + operation 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 == "" || + !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 new file mode 100644 index 0000000..2491252 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/session_test.go @@ -0,0 +1,200 @@ +package v1 + +import ( + "context" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "github.com/ogen-go/ogen/ogenerrors" + + "lincodex/backend/internal/adapter/primary/http/api" + httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware" + "lincodex/backend/internal/adapter/primary/http/problem" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/identity" +) + +type sessionAuthenticatorStub struct { + result identity.AuthenticatedSession + err error + calls int +} + +func (authenticator *sessionAuthenticatorStub) Authenticate(_ context.Context, _ string) (identity.AuthenticatedSession, error) { + authenticator.calls++ + return authenticator.result, authenticator.err +} + +func TestSessionSecurityAddsPrincipalOnlyForTheThreeEnabledOperations(t *testing.T) { + token, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + userID := uuid.New() + verifiedAt := time.Now() + authenticator := &sessionAuthenticatorStub{result: identity.AuthenticatedSession{ + User: domain.User{ID: userID, EmailVerifiedAt: &verifiedAt}, + SessionID: uuid.New(), + CSRFToken: "bound-csrf-token", + }} + security := NewSessionSecurity(authenticator, "https://app.example.com") + + for _, operation := range []api.OperationName{ + api.GetCurrentAccountOperation, + api.GetCurrentSessionOperation, + api.LogoutOperation, + } { + ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com") + authenticated, err := security.HandleSessionCookie(ctx, operation, api.SessionCookie{APIKey: token.Reveal()}) + if err != nil { + t.Fatalf("HandleSessionCookie(%s) error = %v", operation, err) + } + principal, ok := PrincipalFromContext(authenticated) + if !ok || principal.UserID != userID || !principal.EmailVerified { + 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) + } +} + +func TestLogoutRequiresExactOriginAndSessionBoundCSRF(t *testing.T) { + token, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + verifiedAt := time.Now() + authenticator := &sessionAuthenticatorStub{result: identity.AuthenticatedSession{ + User: domain.User{ID: uuid.New(), EmailVerifiedAt: &verifiedAt}, + SessionID: uuid.New(), + CSRFToken: "csrf-for-this-session", + }} + security := NewSessionSecurity(authenticator, "https://app.example.com") + + for _, test := range []struct { + name string + origin string + csrf string + wantErr error + }{ + {name: "valid pair", origin: "https://app.example.com", csrf: "csrf-for-this-session"}, + {name: "wrong token", origin: "https://app.example.com", csrf: "csrf-from-another-session", wantErr: errCsrfCheckFailed}, + {name: "wrong origin", origin: "https://attacker.example", csrf: "csrf-for-this-session", wantErr: errCsrfCheckFailed}, + {name: "missing origin", csrf: "csrf-for-this-session", wantErr: errCsrfCheckFailed}, + } { + 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()}) + if err != nil { + t.Fatalf("HandleSessionCookie() error = %v", err) + } + _, err = security.HandleSessionCsrf(ctx, api.LogoutOperation, api.SessionCsrf{APIKey: test.csrf}) + if !errors.Is(err, test.wantErr) { + t.Fatalf("HandleSessionCsrf() error = %v, want %v", err, test.wantErr) + } + }) + } +} + +func TestSecurityErrorsMapToUnauthenticatedOrCSRFProblem(t *testing.T) { + logger := slog.New(slog.NewTextHandler(&strings.Builder{}, nil)) + handler := NewHandler(nil, problem.NewResponder(logger)) + tests := []struct { + name string + ctx context.Context + err error + want api.ProblemCode + wantStatus int + }{ + {name: "missing cookie", ctx: context.Background(), err: &ogenerrors.SecurityError{Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied}, want: api.ProblemCodeUnauthenticated, wantStatus: http.StatusUnauthorized}, + {name: "missing csrf with principal", ctx: principalTestContext(), err: &ogenerrors.SecurityError{Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied}, want: api.ProblemCodeCsrfCheckFailed, wantStatus: http.StatusForbidden}, + {name: "bad csrf", err: &ogenerrors.SecurityError{Security: "SessionCsrf", Err: errCsrfCheckFailed}, want: api.ProblemCodeCsrfCheckFailed, wantStatus: http.StatusForbidden}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ctx := test.ctx + if ctx == nil { + ctx = context.Background() + } + response := handler.NewError(ctx, test.err) + if response.StatusCode != test.wantStatus || response.Response.Code != test.want { + t.Fatalf("NewError() = %d %s, want %d %s", response.StatusCode, response.Response.Code, test.wantStatus, test.want) + } + }) + } +} + +func TestSessionCookiesUseRequiredAttributesAndClearStaleValues(t *testing.T) { + token, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + start := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: uuid.New(), TokenHash: token.Hash(), StartedAt: start, AbsoluteLifetime: 168 * time.Hour, + }) + if err != nil { + t.Fatal(err) + } + response := &http.Response{Header: http.Header{"Set-Cookie": {sessionCookie(token, session)}}} + cookies := response.Cookies() + if len(cookies) != 1 { + t.Fatalf("login cookie count = %d", len(cookies)) + } + cookie := cookies[0] + if cookie.Name != httpmiddleware.SessionCookieName || cookie.Value != token.Reveal() || cookie.Path != "/" || + cookie.Domain != "" || !cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode || + cookie.MaxAge != int((168*time.Hour).Seconds()) || !cookie.Expires.Equal(session.ExpiresAt) { + t.Fatalf("login cookie attributes = %+v", cookie) + } + + clearResponse := &http.Response{Header: http.Header{"Set-Cookie": {ExpiredSessionCookie()}}} + cleared := clearResponse.Cookies() + if len(cleared) != 1 || cleared[0].Name != httpmiddleware.SessionCookieName || cleared[0].Value != "" || + cleared[0].Path != "/" || cleared[0].MaxAge >= 0 || !cleared[0].Secure || !cleared[0].HttpOnly || + cleared[0].SameSite != http.SameSiteStrictMode { + t.Fatalf("logout clearing cookie = %+v", cleared) + } +} + +func sessionRequestContext(t *testing.T, rawToken, origin string) context.Context { + t.Helper() + request := httptest.NewRequest(http.MethodGet, "/api/v1/identity/me", nil) + if origin != "" { + request.Header.Set("Origin", origin) + } + if rawToken != "" { + request.AddCookie(&http.Cookie{Name: httpmiddleware.SessionCookieName, Value: rawToken}) + } + capture := &sessionContextCapture{} + httpmiddleware.SessionRequestMetadata()(capture).ServeHTTP(httptest.NewRecorder(), request) + if capture.ctx == nil { + t.Fatal("session request middleware did not pass a context") + } + return capture.ctx +} + +type sessionContextCapture struct { + ctx context.Context +} + +func (capture *sessionContextCapture) ServeHTTP(_ http.ResponseWriter, request *http.Request) { + capture.ctx = request.Context() +} + +func principalTestContext() context.Context { + return context.WithValue(context.Background(), principalContextKey{}, Principal{UserID: uuid.New(), EmailVerified: true}) +} diff --git a/backend/internal/adapter/primary/http/v1/user.go b/backend/internal/adapter/primary/http/v1/user.go new file mode 100644 index 0000000..d232431 --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/user.go @@ -0,0 +1,37 @@ +package v1 + +import ( + "context" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/domain" +) + +func (handler *Handler) GetCurrentAccount(ctx context.Context) (api.GetCurrentAccountRes, error) { + if handler.identity == nil || handler.identity.sessions == nil { + return handler.UnimplementedHandler.GetCurrentAccount(ctx) + } + return handler.identity.GetCurrentAccount(ctx) +} + +func (handler *IdentityHandler) GetCurrentAccount(ctx context.Context) (api.GetCurrentAccountRes, error) { + session, ok := sessionFromContext(ctx) + if !ok || !session.EmailVerified { + return unauthenticatedProblemResponse(ctx), nil + } + return &api.AccountHeaders{ + CacheControl: api.CacheControlNoStoreNoStore, + Response: accountFromUser(session.User), + }, nil +} + +func accountFromUser(user domain.User) api.Account { + return api.Account{ + ID: user.ID, + Email: api.EmailAddress(user.Email.Address()), + EmailVerified: user.EmailVerified(), + Scenario: api.AccountScenario(user.Scenario), + OnboardingStep: api.OnboardingStep(user.OnboardingStep), + CreatedAt: api.Timestamp(user.CreatedAt), + } +} diff --git a/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go b/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go index 0762ffc..9e011bf 100644 --- a/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go +++ b/backend/internal/adapter/secondary/mail/resend/resendfixture/fixture.go @@ -47,6 +47,12 @@ type Reply struct { // Name is the Resend error name for a non-2xx answer, for example // "daily_quota_exceeded". Name string + // RetryAfter is copied to the response header for a rate-limit fixture. + RetryAfter string + // DropAfterAccept stores the message and closes the connection without an + // HTTP answer, like a provider accepting the request before the response + // is lost. + DropAfterAccept bool } // Server is the fixture. Create it with New. @@ -61,17 +67,22 @@ type Server struct { mu sync.Mutex requests []Request messages map[string]message // by idempotency key + accepted int scripted []Reply + clock func() time.Time } type message struct { - id string - body string + id string + body string + acceptedAt time.Time } +const providerIdempotencyWindow = 24 * time.Hour + // New starts the fixture on a loopback address. func New() *Server { - server := &Server{messages: make(map[string]message)} + server := &Server{messages: make(map[string]message), clock: time.Now} server.http = httptest.NewServer(http.HandlerFunc(server.serve)) return server } @@ -94,6 +105,18 @@ func (server *Server) Script(replies ...Reply) { // test can act while a send is in flight. func (server *Server) SetDelay(delay time.Duration) { server.delay.Store(int64(delay)) } +// SetClock replaces the provider clock so tests can expire idempotency keys +// without waiting in real time. +func (server *Server) SetClock(clock func() time.Time) { + server.mu.Lock() + defer server.mu.Unlock() + if clock == nil { + server.clock = time.Now + return + } + server.clock = clock +} + // Arrivals returns how many calls the fixture has received, answered or // not yet. func (server *Server) Arrivals() int { return int(server.arrivals.Load()) } @@ -110,7 +133,7 @@ func (server *Server) Requests() []Request { func (server *Server) Messages() int { server.mu.Lock() defer server.mu.Unlock() - return len(server.messages) + return server.accepted } func (server *Server) serve(response http.ResponseWriter, request *http.Request) { @@ -118,18 +141,26 @@ func (server *Server) serve(response http.ResponseWriter, request *http.Request) if delay := time.Duration(server.delay.Load()); delay > 0 { time.Sleep(delay) } + payload, record, ok := readRequest(response, request) + if !ok { + return + } + server.handleEmail(response, payload, record) +} + +func readRequest(response http.ResponseWriter, request *http.Request) ([]byte, Request, bool) { if request.Method != http.MethodPost || request.URL.Path != "/emails" { writeError(response, http.StatusNotFound, "not_found") - return + return nil, Request{}, false } if subtle.ConstantTimeCompare([]byte(request.Header.Get("Authorization")), []byte("Bearer "+APIKey)) != 1 { writeError(response, http.StatusUnauthorized, "invalid_api_key") - return + return nil, Request{}, false } payload, err := io.ReadAll(io.LimitReader(request.Body, maxRequestBytes)) if err != nil { writeError(response, http.StatusBadRequest, "invalid_parameter") - return + return nil, Request{}, false } var body struct { To []string `json:"to"` @@ -139,41 +170,78 @@ func (server *Server) serve(response http.ResponseWriter, request *http.Request) } if err := json.Unmarshal(payload, &body); err != nil { writeError(response, http.StatusBadRequest, "invalid_parameter") - return + return nil, Request{}, false } - key := request.Header.Get("Idempotency-Key") - record := Request{IdempotencyKey: key, To: body.To, Subject: body.Subject, Text: body.Text, HTML: body.HTML} + return payload, Request{ + IdempotencyKey: request.Header.Get("Idempotency-Key"), + To: body.To, + Subject: body.Subject, + Text: body.Text, + HTML: body.HTML, + }, true +} +func (server *Server) handleEmail(response http.ResponseWriter, payload []byte, record Request) { server.mu.Lock() - defer server.mu.Unlock() + reply := Reply{} if len(server.scripted) > 0 { - reply := server.scripted[0] + reply = server.scripted[0] server.scripted = server.scripted[1:] + } + now := server.clock() + known, seen := server.messages[record.IdempotencyKey] + if seen && now.Sub(known.acceptedAt) >= providerIdempotencyWindow { + delete(server.messages, record.IdempotencyKey) + seen = false + } + if reply.Status != 0 { server.requests = append(server.requests, record) + server.mu.Unlock() + if reply.RetryAfter != "" { + response.Header().Set("Retry-After", reply.RetryAfter) + } writeError(response, reply.Status, reply.Name) return } - known, seen := server.messages[key] - switch { - case seen && known.body != string(payload): - // The key was used with another body: Resend refuses it. - server.requests = append(server.requests, record) + messageID, replayed, conflict := server.recordAcceptanceLocked(record.IdempotencyKey, string(payload), now, known, seen) + record.Replayed = replayed + server.requests = append(server.requests, record) + server.mu.Unlock() + if conflict { writeError(response, http.StatusConflict, "invalid_idempotent_request") return - case seen: - record.Replayed = true - server.requests = append(server.requests, record) - writeAccepted(response, known.id) + } + if reply.DropAfterAccept { + dropConnection(response) return } - accepted := message{id: uuid.NewString(), body: string(payload)} + writeAccepted(response, messageID) +} + +func (server *Server) recordAcceptanceLocked(key, body string, now time.Time, known message, seen bool) (string, bool, bool) { + if seen { + if known.body != body { + return "", false, true + } + return known.id, true, false + } + accepted := message{id: uuid.NewString(), body: body, acceptedAt: now} if key != "" { server.messages[key] = accepted } else { server.messages[accepted.id] = accepted } - server.requests = append(server.requests, record) - writeAccepted(response, accepted.id) + server.accepted++ + return accepted.id, false, false +} + +func dropConnection(response http.ResponseWriter) { + if hijacker, ok := response.(http.Hijacker); ok { + connection, _, err := hijacker.Hijack() + if err == nil { + _ = connection.Close() + } + } } func writeAccepted(response http.ResponseWriter, id string) { diff --git a/backend/internal/adapter/secondary/postgres/delivery.go b/backend/internal/adapter/secondary/postgres/delivery.go index d53ea95..d4c5893 100644 --- a/backend/internal/adapter/secondary/postgres/delivery.go +++ b/backend/internal/adapter/secondary/postgres/delivery.go @@ -141,7 +141,95 @@ func (repository deliveryRepository) Get(ctx context.Context, id uuid.UUID) (dom if err != nil { return domain.Delivery{}, fmt.Errorf("deliveryRepository.Get - select delivery: %w", mapDeliveryError(err)) } - return deliveryFromRow(row) + return deliveryFromRow(sqlc.Delivery{ + ID: row.ID, + SourceEventID: row.SourceEventID, + RecipientUserID: row.RecipientUserID, + RecipientEmail: row.RecipientEmail, + Kind: row.Kind, + TemplateVersion: row.TemplateVersion, + Subject: row.Subject, + TextBody: row.TextBody, + HtmlBody: row.HtmlBody, + ContentSha256: row.ContentSha256, + Provider: row.Provider, + ProviderAccount: row.ProviderAccount, + IdempotencyKey: row.IdempotencyKey, + Status: row.Status, + AttemptCount: row.AttemptCount, + NextAttemptAt: row.NextAttemptAt, + LastAttemptAt: row.LastAttemptAt, + ProviderMessageID: row.ProviderMessageID, + Version: row.Version, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + EmailTokenID: row.EmailTokenID, + CancelReason: row.CancelReason, + ClaimOwner: row.ClaimOwner, + ClaimedUntil: row.ClaimedUntil, + FirstSendStartedAt: row.FirstSendStartedAt, + FailureCount: row.FailureCount, + BodyRedactedAt: row.BodyRedactedAt, + }) +} + +func (repository deliveryRepository) GetRetrySnapshot(ctx context.Context, id uuid.UUID) (outbound.DeliveryRetrySnapshot, error) { + const location = "deliveryRepository.GetRetrySnapshot" + row, err := repository.queries.GetDeliveryRetrySnapshot(ctx, pgUUID(id)) + if errors.Is(err, pgx.ErrNoRows) { + return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - select delivery: %w", location, outbound.ErrDeliveryNotFound) + } + if err != nil { + return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - select delivery: %w", location, mapDeliveryError(err)) + } + if _, err := domain.NewMailProviderAccount(row.Provider, row.ProviderAccount); err != nil { + return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - decode provider account: %w", location, err) + } + status, err := domain.ParseDeliveryStatus(row.Status) + if err != nil { + return outbound.DeliveryRetrySnapshot{}, fmt.Errorf("%s - decode status: %w", location, err) + } + return outbound.DeliveryRetrySnapshot{ + ID: uuid.UUID(row.ID.Bytes), + Provider: row.Provider, + ProviderAccount: row.ProviderAccount, + Status: status, + AttemptCount: row.AttemptCount, + NextAttemptAt: zeroableTime(row.NextAttemptAt), + FirstSendStartedAt: zeroableTime(row.FirstSendStartedAt), + ManualRetryStartedAt: zeroableTime(row.ManualRetryStartedAt), + }, nil +} + +func (repository deliveryRepository) AuthorizeUnknownRetry( + ctx context.Context, + id uuid.UUID, + account domain.MailProviderAccount, + actor domain.MailRetryActor, + acknowledgeDuplicateRisk bool, + at time.Time, + minimumAge time.Duration, +) error { + const location = "deliveryRepository.AuthorizeUnknownRetry" + if id == uuid.Nil || account.IsZero() || actor == "" || !acknowledgeDuplicateRisk || at.IsZero() || minimumAge < 0 { + return fmt.Errorf("%s - invalid authorization request: %w", location, outbound.ErrDeliveryRetryNotAllowed) + } + updated, err := repository.queries.AuthorizeUnknownDeliveryRetry(ctx, sqlc.AuthorizeUnknownDeliveryRetryParams{ + Actor: string(actor), + DuplicateRiskAcknowledged: acknowledgeDuplicateRisk, + DeliveryID: pgUUID(id), + Provider: account.Provider(), + ProviderAccount: account.Account(), + MinimumAgeSeconds: minimumAge.Seconds(), + Now: pgTime(at), + }) + if err != nil { + return fmt.Errorf("%s - authorize retry: %w", location, mapDeliveryError(err)) + } + if updated == 0 { + return fmt.Errorf("%s - current delivery state is not eligible: %w", location, outbound.ErrDeliveryRetryNotAllowed) + } + return nil } func (repository deliveryRepository) ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error) { @@ -265,6 +353,33 @@ func (repository deliveryRepository) Cancel(ctx context.Context, next domain.Del return repository.updateState(ctx, "deliveryRepository.Cancel", next, true) } +func (repository deliveryRepository) StopUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error { + const location = "deliveryRepository.StopUnknownRetry" + if next.IsZero() || next.Status() != domain.DeliveryStatusUnknown || !next.NextAttemptAt().IsZero() || owner == uuid.Nil || next.Version() <= 1 { + return fmt.Errorf("%s - state was not built by domain.Delivery.StopAutomaticRetry: %w", location, domain.ErrInvalidDelivery) + } + updated, err := repository.queries.StopUnknownDeliveryRetry(ctx, sqlc.StopUnknownDeliveryRetryParams{ + Now: pgTime(next.UpdatedAt()), + ID: pgUUID(next.ID()), + LeaseOwner: pgUUID(owner), + }) + if err != nil { + return fmt.Errorf("%s - stop retry: %w", location, mapDeliveryError(err)) + } + if updated == 0 { + return fmt.Errorf("%s - expected version %d: %w", location, next.Version()-1, outbound.ErrDeliveryVersionConflict) + } + return nil +} + +func (repository deliveryRepository) ScheduleUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error { + const location = "deliveryRepository.ScheduleUnknownRetry" + if owner == uuid.Nil || next.IsZero() || next.Status() != domain.DeliveryStatusUnknown || next.NextAttemptAt().IsZero() || next.Version() <= 1 { + return fmt.Errorf("%s - state was not built by domain.Delivery.ScheduleUnknownRetry: %w", location, domain.ErrInvalidDelivery) + } + return repository.updateState(ctx, location, next, true) +} + // updateState stores a state change without an attempt over the version // before it. releaseClaim ends the sending worker's lease with the change. func (repository deliveryRepository) updateState(ctx context.Context, location string, next domain.Delivery, releaseClaim bool) error { @@ -363,9 +478,13 @@ func (repository deliveryRepository) ClaimDue(ctx context.Context, claim outboun return outbound.ClaimedDelivery{}, fmt.Errorf("%s - decode claimed delivery: %w", location, unreadable) } claimed := outbound.ClaimedDelivery{ - Delivery: delivery, - PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil), - FailureCount: row.FailureCount, + Delivery: delivery, + PreviousClaimedUntil: zeroableTime(row.PreviousClaimedUntil), + ManualRetryPending: row.ManualRetryPending.Bool, + ManualRetryCycleStarted: row.ManualRetryCycleStarted, + SendStartUnsettled: row.SendStartUnsettled, + HasUncertainAttempt: row.HasUncertainAttempt, + FailureCount: row.FailureCount, } if row.SinceFirstSendSeconds >= 0 { claimed.FirstSendStarted = true @@ -385,11 +504,17 @@ func (repository deliveryRepository) LockClaimed(ctx context.Context, id, owner return true, nil } -func (repository deliveryRepository) MarkSendStarted(ctx context.Context, id, owner uuid.UUID) error { - if _, err := repository.queries.MarkDeliverySendStarted(ctx, sqlc.MarkDeliverySendStartedParams{ID: pgUUID(id), LeaseOwner: pgUUID(owner)}); err != nil { - return fmt.Errorf("deliveryRepository.MarkSendStarted - mark send started: %w", mapDeliveryError(err)) +func (repository deliveryRepository) MarkSendStarted(ctx context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (bool, error) { + started, err := repository.queries.MarkDeliverySendStarted(ctx, sqlc.MarkDeliverySendStartedParams{ + ID: pgUUID(id), + LeaseOwner: pgUUID(owner), + RequireDedupWindow: requireDedupWindow, + RetryWindowSeconds: safeWindow.Seconds(), + }) + if err != nil { + return false, fmt.Errorf("deliveryRepository.MarkSendStarted - mark send started: %w", mapDeliveryError(err)) } - return nil + return started == 1, nil } func (repository deliveryRepository) RecordFailure(ctx context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) { diff --git a/backend/internal/adapter/secondary/postgres/identity.go b/backend/internal/adapter/secondary/postgres/identity.go index 7c83169..5391d3e 100644 --- a/backend/internal/adapter/secondary/postgres/identity.go +++ b/backend/internal/adapter/secondary/postgres/identity.go @@ -28,9 +28,8 @@ const ( // consent records. consentSubjectForeignKey = "consent_records_subject_id_fkey" - // sessionTouchInterval is the minimum age of last_seen_at before Touch - // writes it again. It bounds session writes to one per minute per session - // at the cost of ending an idle session up to a minute early. + // sessionTouchInterval coalesces session activity writes for frequent + // requests. Touch also caps it at half the configured idle timeout. sessionTouchInterval = time.Minute ) @@ -614,11 +613,12 @@ func (repository sessionRepository) Touch(ctx context.Context, id uuid.UUID, at if err := validateSessionCheck("sessionRepository.Touch", at, idleTimeout); err != nil { return err } + touchInterval := min(sessionTouchInterval, idleTimeout/2) result, err := repository.queries.TouchSession(ctx, sqlc.TouchSessionParams{ ID: pgUUID(id), At: pgTime(at), IdleCutoff: pgTime(at.Add(-idleTimeout)), - TouchCutoff: pgTime(at.Add(-sessionTouchInterval)), + TouchCutoff: pgTime(at.Add(-touchInterval)), }) if err != nil { return fmt.Errorf("sessionRepository.Touch - update session: %w", mapIdentityError(err)) diff --git a/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go index 179edd2..d7427cc 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/delivery.sql.go @@ -11,6 +11,148 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const authorizeUnknownDeliveryRetry = `-- name: AuthorizeUnknownDeliveryRetry :execrows +WITH eligible AS MATERIALIZED ( + SELECT + due.id, + (due.claim_owner IS NOT NULL) AS previous_lease_expired, + ( + due.manual_retry_started_at IS NOT NULL + AND due.send_started_attempt_count = due.attempt_count + ) AS unsettled_manual_send, + greatest( + clock_timestamp(), + due.updated_at, + coalesce(due.last_attempt_at, due.updated_at) + ) AS lost_attempt_at + FROM deliveries AS due + WHERE + due.id = $3 + AND due.status = 'unknown' + AND due.next_attempt_at IS NULL + AND ( + due.claim_owner IS NULL + OR due.claimed_until <= clock_timestamp() + ) + AND due.attempt_count > 0 + AND due.provider = $4 + AND due.provider_account = $5 + AND due.first_send_started_at IS NOT NULL + AND clock_timestamp() - due.first_send_started_at + >= make_interval(secs => $6::float8) + AND $2::boolean + AND $1::text ~ '^operator:[a-z0-9][a-z0-9._-]*$' + FOR UPDATE +), authorized AS ( + UPDATE deliveries AS due + SET + attempt_count = due.attempt_count + CASE WHEN eligible.unsettled_manual_send THEN 1 ELSE 0 END, + last_attempt_at = CASE + WHEN eligible.unsettled_manual_send THEN eligible.lost_attempt_at + ELSE due.last_attempt_at + END, + next_attempt_at = greatest( + $7::timestamptz, + due.updated_at, + coalesce(eligible.lost_attempt_at, due.updated_at) + ), + manual_retry_authorized_at = clock_timestamp(), + manual_retry_started_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + version = due.version + 1, + updated_at = greatest( + due.updated_at, + $7::timestamptz, + coalesce(eligible.lost_attempt_at, due.updated_at) + ) + FROM eligible + WHERE due.id = eligible.id + RETURNING + due.id, + due.attempt_count, + eligible.previous_lease_expired, + eligible.unsettled_manual_send, + eligible.lost_attempt_at +), recorded_lost_attempt AS ( + -- A manual send whose lease expired after Mark but before settlement has + -- no provider answer. Preserve it as an unknown attempt before this new + -- explicit decision schedules another possible send. + INSERT INTO delivery_attempts ( + delivery_id, + attempt_number, + attempted_at, + outcome, + rejection, + provider_code, + provider_message_id, + retry_after_ns, + status_after, + next_attempt_at + ) + SELECT + authorized.id, + authorized.attempt_count, + authorized.lost_attempt_at, + 'unknown', + NULL, + NULL, + NULL, + 0, + 'unknown', + NULL + FROM authorized + WHERE authorized.unsettled_manual_send + RETURNING delivery_id +) +INSERT INTO delivery_retry_decisions ( + delivery_id, + attempt_count, + actor, + duplicate_risk_acknowledged, + previous_lease_expired, + decided_at +) +SELECT + authorized.id, + authorized.attempt_count, + $1, + $2, + authorized.previous_lease_expired, + clock_timestamp() +FROM authorized +` + +type AuthorizeUnknownDeliveryRetryParams struct { + Actor string + DuplicateRiskAcknowledged bool + DeliveryID pgtype.UUID + Provider string + ProviderAccount string + MinimumAgeSeconds float64 + Now pgtype.Timestamptz +} + +// Authorizes one retry of a terminal unknown delivery. The update and append- +// only decision share one statement and lock the current row, so a second or +// concurrent operator decision cannot schedule another send for the same +// unknown attempt. The provider account must still match the delivery's pin. +func (q *Queries) AuthorizeUnknownDeliveryRetry(ctx context.Context, arg AuthorizeUnknownDeliveryRetryParams) (int64, error) { + result, err := q.db.Exec(ctx, authorizeUnknownDeliveryRetry, + arg.Actor, + arg.DuplicateRiskAcknowledged, + arg.DeliveryID, + arg.Provider, + arg.ProviderAccount, + arg.MinimumAgeSeconds, + arg.Now, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const cancelUnreadableDelivery = `-- name: CancelUnreadableDelivery :execrows UPDATE deliveries SET @@ -64,12 +206,25 @@ WITH candidate AS ( coalesce( extract(EPOCH FROM clock_timestamp() - due.first_send_started_at), -1 - )::float8 AS since_first_send_seconds + )::float8 AS since_first_send_seconds, + (due.manual_retry_authorized_at IS NOT NULL AND due.manual_retry_started_at IS NULL) + AS manual_retry_pending, + (due.manual_retry_started_at IS NOT NULL)::boolean AS manual_retry_cycle_started, + ( + due.send_started_attempt_count IS NOT NULL + AND due.send_started_attempt_count = due.attempt_count + )::boolean AS send_start_unsettled, + EXISTS ( + SELECT 1 + FROM delivery_attempts AS prior_attempt + WHERE prior_attempt.delivery_id = due.id + AND prior_attempt.outcome = 'unknown' + )::boolean AS has_uncertain_attempt FROM deliveries AS due WHERE due.kind IN ('verification', 'password_reset') AND due.kind = any($3::text []) - AND due.status IN ('pending', 'waiting_quota') + AND due.status IN ('pending', 'waiting_quota', 'unknown') AND due.next_attempt_at IS NOT NULL AND due.next_attempt_at <= $4::timestamptz AND ( @@ -125,7 +280,11 @@ RETURNING claimed.created_at, claimed.updated_at, candidate.previous_claimed_until, - candidate.since_first_send_seconds + candidate.since_first_send_seconds, + candidate.manual_retry_pending, + candidate.manual_retry_cycle_started, + candidate.send_start_unsettled, + candidate.has_uncertain_attempt ` type ClaimDueDeliveryParams struct { @@ -139,37 +298,41 @@ type ClaimDueDeliveryParams struct { } type ClaimDueDeliveryRow struct { - ID pgtype.UUID - SourceEventID pgtype.UUID - RecipientUserID pgtype.UUID - RecipientEmail string - Kind string - TemplateVersion string - Subject string - TextBody string - HtmlBody string - ContentSha256 []byte - Provider string - ProviderAccount string - IdempotencyKey string - Status string - AttemptCount int32 - NextAttemptAt pgtype.Timestamptz - LastAttemptAt pgtype.Timestamptz - ProviderMessageID pgtype.Text - EmailTokenID pgtype.UUID - CancelReason pgtype.Text - BodyRedactedAt pgtype.Timestamptz - FailureCount int32 - Version int64 - CreatedAt pgtype.Timestamptz - UpdatedAt pgtype.Timestamptz - PreviousClaimedUntil pgtype.Timestamptz - SinceFirstSendSeconds float64 + ID pgtype.UUID + SourceEventID pgtype.UUID + RecipientUserID pgtype.UUID + RecipientEmail string + Kind string + TemplateVersion string + Subject string + TextBody string + HtmlBody string + ContentSha256 []byte + Provider string + ProviderAccount string + IdempotencyKey string + Status string + AttemptCount int32 + NextAttemptAt pgtype.Timestamptz + LastAttemptAt pgtype.Timestamptz + ProviderMessageID pgtype.Text + EmailTokenID pgtype.UUID + CancelReason pgtype.Text + BodyRedactedAt pgtype.Timestamptz + FailureCount int32 + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + PreviousClaimedUntil pgtype.Timestamptz + SinceFirstSendSeconds float64 + ManualRetryPending pgtype.Bool + ManualRetryCycleStarted bool + SendStartUnsettled bool + HasUncertainAttempt bool } // Claims the most overdue delivery that the sending worker may send, in one -// statement: a pending or waiting_quota delivery of the service mail kinds +// statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds // (the literals match the predicate of deliveries_due_idx, so an idle poll // reads only that small index) whose next_attempt_at has passed, pinned to the // configured provider account (or to rebind_provider before its first @@ -183,10 +346,15 @@ type ClaimDueDeliveryRow struct { // stay on the application clock that wrote them. Neither the version nor // updated_at changes: a claim is not a change of the delivery. // previous_claimed_until is the deadline of an abandoned lease, NULL for a -// delivery nobody held; since_first_send_seconds is how long ago, by the -// database clock, its first request started, -1 when none did. now is the -// application clock. Deliveries that are unknown or wait for an unknown quota -// reset have no due time here and wait for an operator. +// delivery nobody held; since_first_send_seconds always measures from the +// original first request by the database clock, and is -1 when none started. +// manual_retry_pending is true until the first provider call of the latest +// manual authorization starts. send_start_unsettled means a provider call +// started at the current attempt_count but no result was recorded afterward. +// has_uncertain_attempt keeps an earlier unknown result visible even if a +// later confirmed refusal moved the current delivery back to pending. +// now is the application clock. Unknown deliveries without a scheduled retry +// and quota waits with an unknown reset wait for an operator. func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error) { row := q.db.QueryRow(ctx, claimDueDelivery, arg.LeaseOwner, @@ -226,6 +394,10 @@ func (q *Queries) ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryPara &i.UpdatedAt, &i.PreviousClaimedUntil, &i.SinceFirstSendSeconds, + &i.ManualRetryPending, + &i.ManualRetryCycleStarted, + &i.SendStartUnsettled, + &i.HasUncertainAttempt, ) return i, err } @@ -277,9 +449,40 @@ FROM deliveries WHERE id = $1 ` -func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) { +type GetDeliveryByIDRow struct { + ID pgtype.UUID + SourceEventID pgtype.UUID + RecipientUserID pgtype.UUID + RecipientEmail string + Kind string + TemplateVersion string + Subject string + TextBody string + HtmlBody string + ContentSha256 []byte + Provider string + ProviderAccount string + IdempotencyKey string + Status string + AttemptCount int32 + NextAttemptAt pgtype.Timestamptz + LastAttemptAt pgtype.Timestamptz + ProviderMessageID pgtype.Text + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz + EmailTokenID pgtype.UUID + CancelReason pgtype.Text + ClaimOwner pgtype.UUID + ClaimedUntil pgtype.Timestamptz + FirstSendStartedAt pgtype.Timestamptz + FailureCount int32 + BodyRedactedAt pgtype.Timestamptz +} + +func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error) { row := q.db.QueryRow(ctx, getDeliveryByID, id) - var i Delivery + var i GetDeliveryByIDRow err := row.Scan( &i.ID, &i.SourceEventID, @@ -313,6 +516,49 @@ func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery return i, err } +const getDeliveryRetrySnapshot = `-- name: GetDeliveryRetrySnapshot :one +SELECT + id, + provider, + provider_account, + status, + attempt_count, + next_attempt_at, + first_send_started_at, + manual_retry_started_at +FROM deliveries +WHERE id = $1 +` + +type GetDeliveryRetrySnapshotRow struct { + ID pgtype.UUID + Provider string + ProviderAccount string + Status string + AttemptCount int32 + NextAttemptAt pgtype.Timestamptz + FirstSendStartedAt pgtype.Timestamptz + ManualRetryStartedAt pgtype.Timestamptz +} + +// Reads only the metadata needed by the local operator retry interface. It +// intentionally does not select the address, token, subject, or message body. +func (q *Queries) GetDeliveryRetrySnapshot(ctx context.Context, id pgtype.UUID) (GetDeliveryRetrySnapshotRow, error) { + row := q.db.QueryRow(ctx, getDeliveryRetrySnapshot, id) + var i GetDeliveryRetrySnapshotRow + err := row.Scan( + &i.ID, + &i.Provider, + &i.ProviderAccount, + &i.Status, + &i.AttemptCount, + &i.NextAttemptAt, + &i.FirstSendStartedAt, + &i.ManualRetryStartedAt, + ) + return i, err +} + const getDeliveryStatistics = `-- name: GetDeliveryStatistics :many SELECT kind, @@ -729,24 +975,53 @@ const markDeliverySendStarted = `-- name: MarkDeliverySendStarted :execrows UPDATE deliveries SET first_send_started_at = coalesce(deliveries.first_send_started_at, clock_timestamp()), + send_started_attempt_count = deliveries.attempt_count, + next_attempt_at = CASE + WHEN deliveries.manual_retry_authorized_at IS NOT NULL + AND deliveries.manual_retry_started_at IS NULL + THEN NULL + ELSE deliveries.next_attempt_at + END, + manual_retry_started_at = CASE + WHEN deliveries.manual_retry_authorized_at IS NOT NULL + AND deliveries.manual_retry_started_at IS NULL + THEN clock_timestamp() + ELSE deliveries.manual_retry_started_at + END, failure_count = 0 WHERE id = $1 AND claim_owner = $2 + AND ( + NOT $3::boolean + OR (deliveries.manual_retry_authorized_at IS NOT NULL AND deliveries.manual_retry_started_at IS NULL) + OR coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) IS NULL + OR clock_timestamp() - coalesce(deliveries.manual_retry_started_at, deliveries.first_send_started_at) + < make_interval(secs => $4::float8) + ) ` type MarkDeliverySendStartedParams struct { - ID pgtype.UUID - LeaseOwner pgtype.UUID + ID pgtype.UUID + LeaseOwner pgtype.UUID + RequireDedupWindow bool + RetryWindowSeconds float64 } -// Notes that the first request of a claimed delivery is about to start, by the -// database clock, and clears the count of worker failures: the claim and the -// preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted -// from this moment, so a later claim can tell whether repeating the request is -// still safe. It never moves. +// Notes that a request is about to start, by the database clock, and clears +// the count of worker failures. For an operator-authorized send, this sets +// its single-use marker without overwriting the original first-send time. The +// marker captures the current attempt_count so a lost result can be recovered +// as unknown instead of silently retried. When require_dedup_window is true, +// the age check is repeated here after quota work and the row lock, immediately +// before the network call; manual starts never reset that original window. func (q *Queries) MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error) { - result, err := q.db.Exec(ctx, markDeliverySendStarted, arg.ID, arg.LeaseOwner) + result, err := q.db.Exec(ctx, markDeliverySendStarted, + arg.ID, + arg.LeaseOwner, + arg.RequireDedupWindow, + arg.RetryWindowSeconds, + ) if err != nil { return 0, err } @@ -1002,6 +1277,39 @@ func (q *Queries) ReleaseDeliveryClaim(ctx context.Context, arg ReleaseDeliveryC return result.RowsAffected(), nil } +const stopUnknownDeliveryRetry = `-- name: StopUnknownDeliveryRetry :execrows +UPDATE deliveries +SET + status = 'unknown', + next_attempt_at = NULL, + claim_owner = NULL, + claimed_until = NULL, + version = deliveries.version + 1, + updated_at = greatest(deliveries.updated_at, $1::timestamptz) +WHERE + id = $2 + AND status IN ('pending', 'waiting_quota', 'unknown') + AND next_attempt_at IS NOT NULL + AND claim_owner = $3::uuid +` + +type StopUnknownDeliveryRetryParams struct { + Now pgtype.Timestamptz + ID pgtype.UUID + LeaseOwner pgtype.UUID +} + +// Stops a due automatic retry of an unknown delivery without recording a +// fictitious provider attempt, for example when the 23-hour safety cutoff is +// reached after the claim but before the provider call. +func (q *Queries) StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error) { + result, err := q.db.Exec(ctx, stopUnknownDeliveryRetry, arg.Now, arg.ID, arg.LeaseOwner) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + const updateDeliveryState = `-- name: UpdateDeliveryState :execrows UPDATE deliveries SET diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index e93ddc7..fbe633a 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -196,6 +196,12 @@ type Delivery struct { FailureCount int32 // Set when the bodies of a token mail were cleared after the delivery reached a terminal status, so a database dump holds no live or dead token. BodyRedactedAt pgtype.Timestamptz + // Database time of the latest audited operator authorization to retry a terminal unknown delivery; it does not replace the original send history. + ManualRetryAuthorizedAt pgtype.Timestamptz + // Database time when the first provider call of the latest manual authorization started; this is a single-use/recovery marker and never resets the provider deduplication window. + ManualRetryStartedAt pgtype.Timestamptz + // Attempt count when the latest provider call started. Equality with attempt_count means its result was not recorded; a greater attempt_count means a provider result was stored after that send-start. + SendStartedAttemptCount pgtype.Int4 } type DeliveryAttempt struct { @@ -211,6 +217,21 @@ type DeliveryAttempt struct { NextAttemptAt pgtype.Timestamptz } +// Append-only record of an operator decision to retry a terminal unknown mail delivery after its provider deduplication window. No foreign key so history survives account deletion. +type DeliveryRetryDecision struct { + DecisionID int64 + // Opaque ID of the delivery whose current unknown attempt was authorized for another send cycle. + DeliveryID pgtype.UUID + AttemptCount int32 + // Operator handle in the form operator:; never an email address or credential. + Actor string + // Must be true: after the provider key expires, reusing it does not guarantee deduplication. + DuplicateRiskAcknowledged bool + // True when this decision also cleared an expired worker lease after a manual send began but its result was not recorded. + PreviousLeaseExpired bool + DecidedAt pgtype.Timestamptz +} + type EmailToken struct { ID pgtype.UUID UserID pgtype.UUID diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 51058c8..983c82f 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -28,6 +28,11 @@ type Querier interface { // ends every earlier token, and deletes the registration C1 of the earlier // registrant like UpdateUserRegistration does. AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error) + // Authorizes one retry of a terminal unknown delivery. The update and append- + // only decision share one statement and lock the current row, so a second or + // concurrent operator decision cannot schedule another send for the same + // unknown attempt. The provider account must still match the delivery's pin. + AuthorizeUnknownDeliveryRetry(ctx context.Context, arg AuthorizeUnknownDeliveryRetryParams) (int64, error) // Cancels a job that has not finished. A job whose handler transaction is // in progress holds its row lock, so the statement waits for it: after the // handler committed the job is done and nothing is canceled; otherwise the @@ -40,7 +45,7 @@ type Querier interface { // application clock. CancelUnreadableDelivery(ctx context.Context, arg CancelUnreadableDeliveryParams) (int64, error) // Claims the most overdue delivery that the sending worker may send, in one - // statement: a pending or waiting_quota delivery of the service mail kinds + // statement: a pending, waiting_quota, or scheduled unknown delivery of the service mail kinds // (the literals match the predicate of deliveries_due_idx, so an idle poll // reads only that small index) whose next_attempt_at has passed, pinned to the // configured provider account (or to rebind_provider before its first @@ -54,10 +59,15 @@ type Querier interface { // stay on the application clock that wrote them. Neither the version nor // updated_at changes: a claim is not a change of the delivery. // previous_claimed_until is the deadline of an abandoned lease, NULL for a - // delivery nobody held; since_first_send_seconds is how long ago, by the - // database clock, its first request started, -1 when none did. now is the - // application clock. Deliveries that are unknown or wait for an unknown quota - // reset have no due time here and wait for an operator. + // delivery nobody held; since_first_send_seconds always measures from the + // original first request by the database clock, and is -1 when none started. + // manual_retry_pending is true until the first provider call of the latest + // manual authorization starts. send_start_unsettled means a provider call + // started at the current attempt_count but no result was recorded afterward. + // has_uncertain_attempt keeps an earlier unknown result visible even if a + // later confirmed refusal moved the current delivery back to pending. + // now is the application clock. Unknown deliveries without a scheduled retry + // and quota waits with an unknown reset wait for an operator. ClaimDueDelivery(ctx context.Context, arg ClaimDueDeliveryParams) (ClaimDueDeliveryRow, error) // Claims up to batch_limit jobs of the listed kinds in one statement: jobs // whose available_at has passed, and running jobs whose lease expired @@ -163,7 +173,10 @@ type Querier interface { // The database clock, which stamps the effective time of a policy version, so // "the version in force now" is judged against the same clock. GetDatabaseTime(ctx context.Context) (pgtype.Timestamptz, error) - GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) + GetDeliveryByID(ctx context.Context, id pgtype.UUID) (GetDeliveryByIDRow, error) + // Reads only the metadata needed by the local operator retry interface. It + // intentionally does not select the address, token, subject, or message body. + GetDeliveryRetrySnapshot(ctx context.Context, id pgtype.UUID) (GetDeliveryRetrySnapshotRow, error) // Aggregates the deliveries by kind and status for the metrics, at most once // per metrics interval. It reads only kind, status, and next_attempt_at, // never an address, a body, or an ID. No index covers status, so it scans @@ -406,11 +419,13 @@ type Querier interface { LockPendingOutboxEvents(ctx context.Context, batchLimit int32) ([]LockPendingOutboxEventsRow, error) // Locks the active registration C1 while its pending registration is applied. LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error) - // Notes that the first request of a claimed delivery is about to start, by the - // database clock, and clears the count of worker failures: the claim and the - // preparation succeeded, so the failures are no longer consecutive. The provider keeps the idempotency key for a window counted - // from this moment, so a later claim can tell whether repeating the request is - // still safe. It never moves. + // Notes that a request is about to start, by the database clock, and clears + // the count of worker failures. For an operator-authorized send, this sets + // its single-use marker without overwriting the original first-send time. The + // marker captures the current attempt_count so a lost result can be recovered + // as unknown instead of silently retried. When require_dedup_window is true, + // the age check is repeated here after quota work and the row lock, immediately + // before the network call; manual starts never reset that original window. MarkDeliverySendStarted(ctx context.Context, arg MarkDeliverySendStartedParams) (int64, error) // Records that the provider refused a send because the quota of a window is // used up: the usage rises to at least the configured limit, so the local @@ -553,6 +568,10 @@ type Querier interface { // never started on a lease that another worker may take over. now is the // application clock. StartScheduledJob(ctx context.Context, arg StartScheduledJobParams) (int64, error) + // Stops a due automatic retry of an unknown delivery without recording a + // fictitious provider attempt, for example when the 23-hour safety cutoff is + // reached after the claim but before the provider call. + StopUnknownDeliveryRetry(ctx context.Context, arg StopUnknownDeliveryRetryParams) (int64, error) // Records activity on an active session and reports whether it is active. // The row is written only when last_seen_at is older than touch_cutoff, so // frequent requests do not rewrite it. last_seen_at never moves back, and a diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go index 0505f65..b5a9509 100644 --- a/backend/internal/bootstrap/identity.go +++ b/backend/internal/bootstrap/identity.go @@ -35,10 +35,10 @@ func newAPIHandler(health *v1.HealthHandler, problems *problem.Responder, identi return v1.NewHandler(health, problems, v1.WithIdentity(identityHandler)) } -// newIdentityHandler builds the registration operations and the PostgreSQL -// pool they own. Nothing connects here, so an unavailable database never -// blocks startup. It returns no handler when DATABASE_URL is unset, and the -// operations then answer 501. The application clock is time.Now. +// newIdentityHandler builds the registration and session operations and the +// PostgreSQL pool they own. Nothing connects here, so an unavailable database +// never blocks startup. It returns no handler when DATABASE_URL is unset, and +// the operations then answer 501. The application clock is time.Now. func newIdentityHandler( ctx context.Context, settings config.Config, @@ -47,7 +47,7 @@ func newIdentityHandler( metrics *prometheus.Metrics, ) (*v1.IdentityHandler, func(), error) { if settings.DatabaseURL == "" { - logger.Warn("registration is not served because DATABASE_URL is not set") + logger.Warn("identity operations are not served because DATABASE_URL is not set") return nil, func() {}, nil } keyring, err := newIdentityKeyring(settings, logger) @@ -110,16 +110,40 @@ func newIdentityHandler( pool.Close() return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create confirmation: %w", err) } + sessions, err := identity.NewSessionService(identity.SessionDependencies{ + Transactor: transactor, + Users: store.Users(), + Sessions: store.Sessions(), + Credentials: credentials, + Limiter: cache, + Keyring: keyring, + Clock: time.Now, + Metrics: metrics, + Logger: logger, + }, identity.SessionSettings{ + ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(settings.IdentityLoginEmailHourlyLimit), + IdleTimeout: settings.IdentitySessionIdleTimeout, + AbsoluteLifetime: settings.IdentitySessionAbsoluteLifetime, + }) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create sessions: %w", err) + } // 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)), pool.Close, nil + return v1.NewIdentityHandler(registration, + v1.WithEmailConfirmation(confirmation, settings.AppPublicURL), + v1.WithSessionService(sessions, settings.AppPublicURL), + ), pool.Close, nil } -// newIdentityKeyring keys the idempotency scopes and rate limit buckets with -// IDENTITY_KEY_SECRET. Only with IDENTITY_ALLOW_EPHEMERAL_KEY, which the -// configuration check demands for an unset secret, a random one is drawn for -// this process: idempotency records and counters written before a restart no -// longer match, and instances of one deployment do not agree. +// newIdentityKeyring derives purpose keys for idempotency scopes, rate-limit +// buckets, and session CSRF tokens from IDENTITY_KEY_SECRET. Only with +// IDENTITY_ALLOW_EPHEMERAL_KEY, which the configuration check demands for an +// unset secret, a random one is drawn for this process. Idempotency records and +// counters no longer match after restart, and CSRF tokens differ between +// restarts and instances. func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) { secret := []byte(settings.IdentityKeySecret) if len(secret) == 0 { @@ -127,7 +151,7 @@ func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity. if _, err := rand.Read(secret); err != nil { return nil, fmt.Errorf("bootstrap.newIdentityKeyring - generate secret: %w", err) } - logger.Warn("IDENTITY_ALLOW_EPHEMERAL_KEY is set and IDENTITY_KEY_SECRET is not; a random secret is used, so idempotency records and rate limits do not survive a restart") + logger.Warn("IDENTITY_ALLOW_EPHEMERAL_KEY is set and IDENTITY_KEY_SECRET is not; a random secret is used, so idempotency records and rate limits do not survive a restart and session CSRF tokens differ between restarts and instances") } keyring, err := identity.NewKeyring(secret) if err != nil { diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index 5307ef8..0c6ae67 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -39,7 +39,7 @@ func initialize( wire.Bind(new(inbound.Readiness), new(*health.Readiness)), wire.Bind(new(httpmiddleware.RequestMetrics), new(*metrics.Metrics)), wire.Bind(new(apiadapter.Handler), new(*v1.Handler)), - wire.Bind(new(apiadapter.SecurityHandler), new(*v1.DenyAllSecurity)), + wire.Bind(new(apiadapter.SecurityHandler), new(*v1.SessionSecurity)), newReadiness, metrics.New, newHealthHandler, @@ -47,7 +47,7 @@ func initialize( newAPIHandler, newTrustedProxies, newIdentityHandler, - v1.NewDenyAllSecurity, + newSessionSecurity, httpadapter.NewRouter, newOutboxRelay, newEventConsumers, @@ -60,6 +60,10 @@ func initialize( return nil, nil, nil } +func newSessionSecurity(identityHandler *v1.IdentityHandler) *v1.SessionSecurity { + return identityHandler.SessionSecurity() +} + func newHealthHandler(readiness inbound.Readiness, config config.Config) *v1.HealthHandler { return v1.NewHealthHandler(readiness, config.ReadinessTimeout) } diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index b73f935..bb12d83 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -54,9 +54,9 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, return nil, nil, err } handler := newAPIHandler(healthHandler, responder, identityHandler) - denyAllSecurity := v1.NewDenyAllSecurity() + sessionSecurity := newSessionSecurity(identityHandler) v := newTrustedProxies(config2) - httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger, v) + httpHandler, err := httpadapter.NewRouter(healthHandler, handler, sessionSecurity, responder, metrics, logger, v) if err != nil { cleanup4() cleanup3() @@ -130,6 +130,10 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, // wire.go: +func newSessionSecurity(identityHandler *v1.IdentityHandler) *v1.SessionSecurity { + return identityHandler.SessionSecurity() +} + func newHealthHandler(readiness inbound.Readiness, config2 config.Config) *v1.HealthHandler { return v1.NewHealthHandler(readiness, config2.ReadinessTimeout) } diff --git a/backend/internal/domain/delivery.go b/backend/internal/domain/delivery.go index 1c91524..9f2f0e7 100644 --- a/backend/internal/domain/delivery.go +++ b/backend/internal/domain/delivery.go @@ -640,6 +640,47 @@ func (delivery Delivery) Rebind(at time.Time, providerAccount MailProviderAccoun return next, nil } +// StopAutomaticRetry ends the automatic retry schedule without claiming that +// an uncertain delivery was not sent. The delivery remains unknown, with no +// due time, so only an audited operator decision can start another send cycle. +// It also accepts pending or waiting_quota when a later confirmed refusal +// leaves an earlier unknown outcome unresolved after the automatic cutoff. +func (delivery Delivery) StopAutomaticRetry(at time.Time) (Delivery, error) { + const location = "Delivery.StopAutomaticRetry" + if err := delivery.checkChangeTime(location, at); err != nil { + return Delivery{}, err + } + if (delivery.status != DeliveryStatusUnknown && delivery.status != DeliveryStatusPending && delivery.status != DeliveryStatusWaitingQuota) || delivery.nextAttemptAt.IsZero() { + return Delivery{}, fmt.Errorf("%s - delivery is %s without a scheduled retry: %w", location, delivery.status, ErrDeliveryTransition) + } + next := delivery + next.status = DeliveryStatusUnknown + next.nextAttemptAt = time.Time{} + next.version = delivery.version + 1 + next.updatedAt = at + return next, nil +} + +// ScheduleUnknownRetry keeps an unknown delivery in the due queue until a +// provider quota reset. It does not change the outcome or append an attempt. +func (delivery Delivery) ScheduleUnknownRetry(at, nextAttemptAt time.Time) (Delivery, error) { + const location = "Delivery.ScheduleUnknownRetry" + if err := delivery.checkChangeTime(location, at); err != nil { + return Delivery{}, err + } + if delivery.status != DeliveryStatusUnknown || delivery.nextAttemptAt.IsZero() { + return Delivery{}, fmt.Errorf("%s - delivery is %s without an automatic retry: %w", location, delivery.status, ErrDeliveryTransition) + } + if nextAttemptAt.IsZero() || nextAttemptAt.Before(at) { + return Delivery{}, invalidDelivery(location, "next retry time must be set and not precede the decision") + } + next := delivery + next.nextAttemptAt = nextAttemptAt + next.version = delivery.version + 1 + next.updatedAt = at + return next, nil +} + // checkChangeTime rejects a zero delivery and a change time before the last // recorded change. func (delivery Delivery) checkChangeTime(location string, at time.Time) error { diff --git a/backend/internal/domain/delivery_test.go b/backend/internal/domain/delivery_test.go index 324ab78..e190195 100644 --- a/backend/internal/domain/delivery_test.go +++ b/backend/internal/domain/delivery_test.go @@ -317,6 +317,49 @@ func TestRecordAttemptRejectsInconsistentResults(t *testing.T) { } } +func TestStopAutomaticRetryKeepsAnUncertainDeliveryUnknown(t *testing.T) { + start := newTestDelivery(t) + scheduled := mustRecord(t, start, DeliveryAttemptInput{ + At: after(1), Outcome: DeliveryOutcomeUnknown, NextAttemptAt: after(2), + }) + stopped, err := scheduled.StopAutomaticRetry(after(3)) + if err != nil { + t.Fatalf("StopAutomaticRetry() error = %v", err) + } + if stopped.Status() != DeliveryStatusUnknown || !stopped.NextAttemptAt().IsZero() { + t.Fatalf("stopped delivery is %s due %s, want unknown without a due time", stopped.Status(), stopped.NextAttemptAt()) + } + if stopped.AttemptCount() != scheduled.AttemptCount() || stopped.Version() != scheduled.Version()+1 { + t.Fatalf("stopped delivery has %d attempts and version %d, want %d and %d", stopped.AttemptCount(), stopped.Version(), scheduled.AttemptCount(), scheduled.Version()+1) + } + if stopped.IdempotencyKey() != scheduled.IdempotencyKey() || stopped.Content().Hash() != scheduled.Content().Hash() { + t.Fatal("stopping retries changed the idempotency key or message content") + } + if _, err := stopped.StopAutomaticRetry(after(4)); !errors.Is(err, ErrDeliveryTransition) { + t.Fatalf("StopAutomaticRetry() without a scheduled retry error = %v, want ErrDeliveryTransition", err) + } + + quotaWait := mustRecord(t, newTestDelivery(t), DeliveryAttemptInput{ + At: after(1), Outcome: DeliveryOutcomeRejected, Rejection: DeliveryRejectionQuotaExhausted, NextAttemptAt: after(2), + }) + quotaStopped, err := quotaWait.StopAutomaticRetry(after(3)) + if err != nil || quotaStopped.Status() != DeliveryStatusUnknown || !quotaStopped.NextAttemptAt().IsZero() { + t.Fatalf("StopAutomaticRetry() after a manual-cycle quota refusal = %s due %s, %v; want unknown without a due time", + quotaStopped.Status(), quotaStopped.NextAttemptAt(), err) + } +} + +func TestParseMailRetryActor(t *testing.T) { + if got, err := ParseMailRetryActor("operator:mail-ops"); err != nil || got != "operator:mail-ops" { + t.Fatalf("ParseMailRetryActor() = %q, %v", got, err) + } + for _, value := range []string{"", "operator:Upper", "operator:has space", "person:mail-ops", "operator:" + strings.Repeat("a", 122)} { + if _, err := ParseMailRetryActor(value); !errors.Is(err, ErrInvalidDelivery) { + t.Fatalf("ParseMailRetryActor(%q) error = %v, want ErrInvalidDelivery", value, err) + } + } +} + func deliverySnapshot(delivery Delivery) DeliverySnapshot { return DeliverySnapshot{ ID: delivery.ID(), diff --git a/backend/internal/domain/mail_retry.go b/backend/internal/domain/mail_retry.go new file mode 100644 index 0000000..c8a7c36 --- /dev/null +++ b/backend/internal/domain/mail_retry.go @@ -0,0 +1,18 @@ +package domain + +import "regexp" + +var mailRetryActorPattern = regexp.MustCompile(`^operator:[a-z0-9][a-z0-9._-]*$`) + +// MailRetryActor identifies an operator who authorized a retry of an unknown +// delivery. It is a handle, not an account ID, email address, or credential. +type MailRetryActor string + +// ParseMailRetryActor accepts an operator handle in the form +// "operator:". +func ParseMailRetryActor(value string) (MailRetryActor, error) { + if len(value) > 128 || !mailRetryActorPattern.MatchString(value) { + return "", invalidDelivery("domain.ParseMailRetryActor", "actor must be operator: of at most 128 bytes in lowercase letters, digits, '.', '_', or '-'") + } + return MailRetryActor(value), nil +} diff --git a/backend/internal/port/outbound/delivery.go b/backend/internal/port/outbound/delivery.go index 57961a0..ac03883 100644 --- a/backend/internal/port/outbound/delivery.go +++ b/backend/internal/port/outbound/delivery.go @@ -19,6 +19,11 @@ var ( // exists. Nothing was written; read the delivery again. ErrDeliveryVersionConflict = errors.New("delivery changed concurrently") + // ErrDeliveryRetryNotAllowed reports that an operator retry did not match + // the current terminal unknown delivery, its provider account, the + // deduplication cutoff, or the required duplicate-risk acknowledgement. + ErrDeliveryRetryNotAllowed = errors.New("unknown delivery retry is not allowed in its current state") + // ErrDeliveryContentImmutable reports a statement that tried to change // the recipient, content, provider account, or idempotency key of a // stored delivery, or a recorded attempt. The database refuses it; it @@ -67,6 +72,11 @@ type DeliveryRepository interface { // no longer matches its hash. Get(ctx context.Context, id uuid.UUID) (domain.Delivery, error) + // GetRetrySnapshot returns operational state for one delivery without its + // recipient address or message content. It is used by the bounded local + // operator retry interface and logs. + GetRetrySnapshot(ctx context.Context, id uuid.UUID) (DeliveryRetrySnapshot, error) + // ListAttempts returns the recorded attempts in attempt order; an empty // list for a delivery without attempts or an unknown ID. ListAttempts(ctx context.Context, id uuid.UUID) ([]domain.DeliveryAttempt, error) @@ -100,6 +110,22 @@ type DeliveryRepository interface { // the sending worker's lease. Cancel(ctx context.Context, next domain.Delivery) error + // AuthorizeUnknownRetry atomically schedules one operator-approved retry + // and appends its immutable audit record. It succeeds only for an unknown + // delivery with no automatic retry or live lease, after the safe provider + // window, pinned to account, with an operator actor and explicit risk ack. + // It returns ErrDeliveryRetryNotAllowed when that state no longer matches. + AuthorizeUnknownRetry(ctx context.Context, id uuid.UUID, account domain.MailProviderAccount, actor domain.MailRetryActor, acknowledgeDuplicateRisk bool, at time.Time, safeWindow time.Duration) error + + // StopUnknownRetry stores next as returned by domain.Delivery.StopAutomaticRetry + // and releases owner lease without appending a provider attempt. + StopUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error + + // ScheduleUnknownRetry stores next as returned by + // domain.Delivery.ScheduleUnknownRetry and releases owner lease without an + // attempt, for a quota wait that applies to an uncertain retry. + ScheduleUnknownRetry(ctx context.Context, owner uuid.UUID, next domain.Delivery) error + // ClaimDue gives the claim's owner a lease on the most overdue delivery // it may send and returns it, or returns ErrNoDeliveryDue. A claimed row // that cannot be restored is reported as an *UnreadableDeliveryError; @@ -122,9 +148,12 @@ type DeliveryRepository interface { // lock before the quota rows, as the claim does. LockClaimed(ctx context.Context, id, owner uuid.UUID) (bool, error) - // MarkSendStarted records, by the database clock and only the first time, - // that the first request of the claimed delivery is about to start. - MarkSendStarted(ctx context.Context, id, owner uuid.UUID) error + // MarkSendStarted records, by the database clock, that the request is about + // to start. When requireDedupWindow is true it returns false if the provider + // safety window expired after claim; this check is the last storage action + // before the network call. An authorized manual cycle records a separate + // first-start timestamp without replacing the original history. + MarkSendStarted(ctx context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (started bool, err error) // RecordFailure counts a failure of the sending worker on the delivery // (not a provider answer), ends its lease, and makes it due again at @@ -151,6 +180,19 @@ type DeliveryRepository interface { ServiceMailState(ctx context.Context, id uuid.UUID) (domain.ServiceMailState, error) } +// DeliveryRetrySnapshot contains only the metadata needed to inspect an +// unknown delivery before an operator decision. +type DeliveryRetrySnapshot struct { + ID uuid.UUID + Provider string + ProviderAccount string + Status domain.DeliveryStatus + AttemptCount int32 + NextAttemptAt time.Time + FirstSendStartedAt time.Time + ManualRetryStartedAt time.Time +} + // DeliveryClaim selects and leases the next delivery for a sending worker. type DeliveryClaim struct { // Owner identifies the worker; a lease belongs to it. @@ -180,11 +222,23 @@ type ClaimedDelivery struct { // and let expire without finishing, so an attempt may be in doubt; zero // when no worker held the delivery before. PreviousClaimedUntil time.Time - // SinceFirstSend is how long ago, by the database clock, the first - // request of the delivery started; meaningful only when FirstSendStarted. - // The provider keeps the idempotency key for a window counted from then. + // SinceFirstSend is how long ago, by the database clock, the original + // first provider request started. A manual decision never resets this + // provider idempotency age. Meaningful only when FirstSendStarted. SinceFirstSend time.Duration FirstSendStarted bool + // ManualRetryPending is true after operator authorization and until the + // first provider call of that manual cycle starts. + ManualRetryPending bool + // ManualRetryCycleStarted is true after that first manual provider call + // starts. It is a single-use and recovery marker, not a new provider window. + ManualRetryCycleStarted bool + // SendStartUnsettled is true when the latest provider call started with the + // current attempt_count and no result was recorded afterward. + SendStartUnsettled bool + // HasUncertainAttempt is true when this delivery has any recorded unknown + // provider result, even if a later confirmed refusal moved it to pending. + HasUncertainAttempt bool // FailureCount is the number of consecutive failures of the worker on // this delivery so far. FailureCount int32 diff --git a/backend/internal/usecase/identity/credentials.go b/backend/internal/usecase/identity/credentials.go index 82cafde..67bb624 100644 --- a/backend/internal/usecase/identity/credentials.go +++ b/backend/internal/usecase/identity/credentials.go @@ -3,12 +3,16 @@ package identity import ( "context" + "errors" "fmt" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) +//nolint:gosec // G101: this fixed value is only used for dummy Argon2 work and never authenticates an account. +const dummyLoginPassword = "lincodex-login-dummy-password" + // Credentials applies the password rules in the order that keeps hashing // bounded: the cheap length and encoding checks first, the expensive KDF only // for a password that passes them. @@ -52,3 +56,18 @@ func (credentials *Credentials) VerifyLoginPassword(ctx context.Context, raw str } return nil } + +// VerifyDummyLoginPassword spends the same password-hash work for an unknown +// account as VerifyLoginPassword does for a known one. The result is always a +// mismatch unless the hasher fails for an operational reason. +func (credentials *Credentials) VerifyDummyLoginPassword(ctx context.Context, raw string) error { + password, err := domain.ParseLoginPassword(raw) + if err != nil { + password, _ = domain.ParseLoginPassword(dummyLoginPassword) + } + err = credentials.hasher.VerifyDummy(ctx, password) + if errors.Is(err, outbound.ErrPasswordMismatch) { + return outbound.ErrPasswordMismatch + } + return fmt.Errorf("Credentials.VerifyDummyLoginPassword - verify dummy hash: %w", err) +} diff --git a/backend/internal/usecase/identity/credentials_test.go b/backend/internal/usecase/identity/credentials_test.go index 28c3b14..c4b733e 100644 --- a/backend/internal/usecase/identity/credentials_test.go +++ b/backend/internal/usecase/identity/credentials_test.go @@ -20,6 +20,7 @@ type countingHasher struct { hashCalls int hashed domain.Password verifyCalls int + dummyCalls int verified domain.Password stored domain.PasswordHash verifyErr error @@ -39,7 +40,8 @@ func (hasher *countingHasher) Verify(_ context.Context, password domain.Password } func (hasher *countingHasher) VerifyDummy(context.Context, domain.Password) error { - return errors.New("countingHasher.VerifyDummy - not used") + hasher.dummyCalls++ + return outbound.ErrPasswordMismatch } var _ outbound.PasswordHasher = (*countingHasher)(nil) @@ -116,3 +118,16 @@ func TestVerifyLoginPasswordRejectsEmptyInputBeforeKDF(t *testing.T) { t.Fatalf("VerifyLoginPassword(empty) = %v after %d verify calls, want ErrInvalidPassword before KDF", err, hasher.verifyCalls) } } + +func TestVerifyDummyLoginPasswordAlwaysRunsDummyHashWork(t *testing.T) { + hasher := &countingHasher{} + credentials := NewCredentials(hasher) + for _, password := range []string{"correct horse battery staple", ""} { + if err := credentials.VerifyDummyLoginPassword(context.Background(), password); !errors.Is(err, outbound.ErrPasswordMismatch) { + t.Fatalf("VerifyDummyLoginPassword() error = %v, want ErrPasswordMismatch", err) + } + } + if hasher.dummyCalls != 2 || hasher.verifyCalls != 0 { + t.Fatalf("dummy calls=%d normal calls=%d, want two dummy calls", hasher.dummyCalls, hasher.verifyCalls) + } +} diff --git a/backend/internal/usecase/identity/errors.go b/backend/internal/usecase/identity/errors.go index 3584995..4c1486c 100644 --- a/backend/internal/usecase/identity/errors.go +++ b/backend/internal/usecase/identity/errors.go @@ -26,6 +26,18 @@ var ( // ErrVerificationTokenExpired reports an email verification token past its // expiry time. ErrVerificationTokenExpired = errors.New("verification token expired") + + // ErrInvalidCredentials represents an unknown account or an incorrect + // password with one public outcome. + ErrInvalidCredentials = errors.New("invalid credentials") + + // ErrEmailNotVerified reports correct credentials for an unverified + // account. It never creates a session. + ErrEmailNotVerified = errors.New("email not verified") + + // ErrUnauthenticated reports a missing, invalid, expired, idle, or revoked + // server session. + ErrUnauthenticated = errors.New("unauthenticated") ) // RateLimitedError carries how long the caller waits before a repeat can be diff --git a/backend/internal/usecase/identity/keyring.go b/backend/internal/usecase/identity/keyring.go index 9ee7fc8..166b045 100644 --- a/backend/internal/usecase/identity/keyring.go +++ b/backend/internal/usecase/identity/keyring.go @@ -3,9 +3,11 @@ package identity import ( "crypto/hmac" "crypto/sha256" + "encoding/base64" "encoding/hex" "fmt" + "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) @@ -20,6 +22,7 @@ const ( labelEmailBucket = "lincodex/identity/email-bucket/v1" labelClientBucket = "lincodex/identity/client-bucket/v1" labelTokenBucket = "lincodex/identity/verification-token-bucket/v1" + labelSessionCSRF = "lincodex/identity/session-csrf/v1" ) // Keyring computes the keyed digests of the anonymous identity operations: @@ -33,6 +36,7 @@ type Keyring struct { bucketKey []byte clientKey []byte tokenKey []byte + sessionCSRFKey []byte } // NewKeyring derives the purpose keys from secret. @@ -46,6 +50,7 @@ func NewKeyring(secret []byte) (*Keyring, error) { bucketKey: derive(secret, labelEmailBucket), clientKey: derive(secret, labelClientBucket), tokenKey: derive(secret, labelTokenBucket), + sessionCSRFKey: derive(secret, labelSessionCSRF), }, nil } @@ -99,3 +104,26 @@ func (keyring *Keyring) VerificationTokenBucket(rawToken string) string { mac.Write([]byte(rawToken)) return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil)) } + +// SessionCSRF derives a synchronizer token for exactly one session. The +// purpose key and message are both domain-separated from every other keyring +// use, and only the encoded result is returned to the HTTP adapter. +func (keyring *Keyring) SessionCSRF(token domain.SecretToken) string { + if token.IsZero() { + return "" + } + mac := hmac.New(sha256.New, keyring.sessionCSRFKey) + mac.Write([]byte(labelSessionCSRF)) + mac.Write([]byte{0}) + mac.Write([]byte(token.Reveal())) + return base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) +} + +// VerifySessionCSRF compares the supplied synchronizer token in constant +// time with the token bound to this session. +func (keyring *Keyring) VerifySessionCSRF(token domain.SecretToken, supplied string) bool { + if token.IsZero() { + return false + } + return hmac.Equal([]byte(keyring.SessionCSRF(token)), []byte(supplied)) +} diff --git a/backend/internal/usecase/identity/session.go b/backend/internal/usecase/identity/session.go new file mode 100644 index 0000000..0d6f55c --- /dev/null +++ b/backend/internal/usecase/identity/session.go @@ -0,0 +1,326 @@ +package identity + +import ( + "context" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +// SessionSettings bounds login attempts and the life of a server-side +// session. Session expiry is enforced by PostgreSQL on every lookup. +type SessionSettings struct { + ClientHourlyLimit int64 + EmailHourlyLimit int64 + IdleTimeout time.Duration + AbsoluteLifetime time.Duration +} + +// SessionDependencies are the collaborators of SessionService. Metrics and +// logger are optional; all other dependencies are required. +type SessionDependencies struct { + Transactor outbound.Transactor + Users outbound.UserRepository + Sessions outbound.SessionRepository + Credentials *Credentials + Limiter outbound.RateLimiter + Keyring *Keyring + Clock func() time.Time + Metrics RateLimitMetrics + Logger *slog.Logger +} + +// SessionService authenticates accounts and manages their server-side +// sessions. It keeps no mutable per-request state. +type SessionService struct { + deps SessionDependencies + settings SessionSettings +} + +func NewSessionService(deps SessionDependencies, settings SessionSettings) (*SessionService, error) { + switch { + case deps.Transactor == nil, deps.Users == nil, deps.Sessions == nil, deps.Credentials == nil, + deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil: + return nil, errors.New("identity.NewSessionService - every dependency must be set") + case settings.ClientHourlyLimit < 1, settings.EmailHourlyLimit < 1, + settings.IdleTimeout <= 0, settings.AbsoluteLifetime <= 0, + settings.IdleTimeout > settings.AbsoluteLifetime: + return nil, errors.New("identity.NewSessionService - invalid session settings") + } + if deps.Logger == nil { + deps.Logger = slog.Default() + } + return &SessionService{deps: deps, settings: settings}, nil +} + +// LoginCommand is the content of an unvalidated login request. +type LoginCommand struct { + Email string + Password string + ClientKey string + Incoming domain.SecretToken +} + +// LoginResult contains the user-facing session response and the raw cookie +// token. The token is redacted by domain.SecretToken and must only be revealed +// by the HTTP adapter when it writes Set-Cookie. +type LoginResult struct { + User domain.User + Session domain.Session + Token domain.SecretToken + CSRFToken string +} + +// AuthenticatedSession is the server-side identity resolved from a cookie. +// It contains no raw session token or credential material. +type AuthenticatedSession struct { + User domain.User + SessionID uuid.UUID + CSRFToken string +} + +// Login checks both rate limits before password verification. Unknown +// addresses receive the dummy password-hash work; an invalid stored hash is +// logged without account details and follows the same public failure path. +func (service *SessionService) Login(ctx context.Context, command LoginCommand) (LoginResult, error) { + const location = "SessionService.Login" + email, err := domain.NewEmailAddress(command.Email) + if err != nil { + return LoginResult{}, fmt.Errorf("%s - validate email: %w", location, invalidField(emailPointer, err)) + } + if err := service.takeLoginAttempt(ctx, email, command.ClientKey); err != nil { + return LoginResult{}, fmt.Errorf("%s - limit login: %w", location, err) + } + user, err := service.loginUser(ctx, email, command.Password) + if err != nil { + return LoginResult{}, err + } + + token, err := domain.NewSecretToken() + if err != nil { + return LoginResult{}, fmt.Errorf("%s - create session token: %w", location, err) + } + authenticatedUser, created, err := service.createLoginSession(ctx, user, command.Incoming, token) + if err != nil { + return LoginResult{}, fmt.Errorf("%s - rotate session: %w", location, err) + } + return LoginResult{ + User: authenticatedUser, + Session: created, + Token: token, + CSRFToken: service.deps.Keyring.SessionCSRF(token), + }, nil +} + +func (service *SessionService) loginUser(ctx context.Context, email domain.EmailAddress, password string) (domain.User, error) { + user, err := service.deps.Users.GetByEmail(ctx, email) + if errors.Is(err, outbound.ErrUserNotFound) { + if dummyErr := service.verifyDummyLoginPassword(ctx, password); dummyErr != nil { + return domain.User{}, dummyErr + } + return domain.User{}, ErrInvalidCredentials + } + if err != nil { + return domain.User{}, fmt.Errorf("SessionService.Login - read account: %w", err) + } + if err := service.verifyLoginPassword(ctx, password, user.PasswordHash); err != nil { + return domain.User{}, err + } + if !user.EmailVerified() { + return domain.User{}, ErrEmailNotVerified + } + return user, nil +} + +func (service *SessionService) verifyLoginPassword(ctx context.Context, password string, passwordHash domain.PasswordHash) error { + err := service.deps.Credentials.VerifyLoginPassword(ctx, password, passwordHash) + if err == nil { + return nil + } + if errors.Is(err, outbound.ErrPasswordMismatch) { + return ErrInvalidCredentials + } + if errors.Is(err, domain.ErrInvalidPassword) || errors.Is(err, outbound.ErrPasswordHashCorrupt) || + errors.Is(err, domain.ErrInvalidPasswordHash) { + if errors.Is(err, outbound.ErrPasswordHashCorrupt) || errors.Is(err, domain.ErrInvalidPasswordHash) { + service.deps.Logger.ErrorContext(ctx, "login rejected because the stored password hash is invalid") + } + if dummyErr := service.verifyDummyLoginPassword(ctx, password); dummyErr != nil { + return dummyErr + } + return ErrInvalidCredentials + } + return fmt.Errorf("SessionService.Login - verify password: %w", err) +} + +func (service *SessionService) verifyDummyLoginPassword(ctx context.Context, password string) error { + err := service.deps.Credentials.VerifyDummyLoginPassword(ctx, password) + if err == nil || errors.Is(err, outbound.ErrPasswordMismatch) { + return nil + } + return fmt.Errorf("SessionService.Login - verify dummy password: %w", err) +} + +func (service *SessionService) createLoginSession( + ctx context.Context, + loginSnapshot domain.User, + incoming, token domain.SecretToken, +) (domain.User, domain.Session, error) { + startedAt := service.deps.Clock() + var authenticatedUser domain.User + var created domain.Session + err := service.deps.Transactor.WithinTransaction(ctx, func(tx context.Context, unit outbound.UnitOfWork) error { + user, session, err := service.createLoginSessionInTransaction(tx, unit, loginSnapshot, incoming, token, startedAt) + if err != nil { + return err + } + authenticatedUser = user + created = session + return nil + }) + return authenticatedUser, created, err +} + +func (service *SessionService) createLoginSessionInTransaction( + ctx context.Context, + unit outbound.UnitOfWork, + loginSnapshot domain.User, + incoming, token domain.SecretToken, + startedAt time.Time, +) (domain.User, domain.Session, error) { + const location = "SessionService.Login" + user, err := unit.Users().GetByID(ctx, loginSnapshot.ID) + if errors.Is(err, outbound.ErrUserNotFound) { + return domain.User{}, domain.Session{}, ErrInvalidCredentials + } + if err != nil { + return domain.User{}, domain.Session{}, fmt.Errorf("%s - recheck account: %w", location, err) + } + if !user.EmailVerified() { + return domain.User{}, domain.Session{}, ErrEmailNotVerified + } + if !sameLoginCredentials(loginSnapshot, user) { + return domain.User{}, domain.Session{}, ErrInvalidCredentials + } + if err := service.revokeIncomingSession(ctx, unit.Sessions(), incoming, startedAt); err != nil { + return domain.User{}, domain.Session{}, err + } + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: user.ID, + TokenHash: token.Hash(), + StartedAt: startedAt, + AbsoluteLifetime: service.settings.AbsoluteLifetime, + }) + if err != nil { + return domain.User{}, domain.Session{}, fmt.Errorf("%s - build session: %w", location, err) + } + if err := unit.Sessions().Create(ctx, session); err != nil { + return domain.User{}, domain.Session{}, fmt.Errorf("%s - create session: %w", location, err) + } + return user, session, nil +} + +func sameLoginCredentials(snapshot, current domain.User) bool { + return snapshot.RegistrationVersion == current.RegistrationVersion && + snapshot.PasswordHash.PHC() == current.PasswordHash.PHC() +} + +func (service *SessionService) revokeIncomingSession( + ctx context.Context, + sessions outbound.SessionRepository, + incoming domain.SecretToken, + now time.Time, +) error { + if incoming.IsZero() { + return nil + } + old, err := sessions.FindActive(ctx, incoming.Hash(), now, service.settings.IdleTimeout) + if errors.Is(err, outbound.ErrSessionNotFound) { + return nil + } + if err != nil { + return fmt.Errorf("SessionService.Login - read incoming session: %w", err) + } + if err := sessions.Revoke(ctx, old.ID, now); err != nil && !errors.Is(err, outbound.ErrSessionNotFound) { + return fmt.Errorf("SessionService.Login - revoke incoming session: %w", err) + } + return nil +} + +// Authenticate validates the cookie against PostgreSQL, checks the account +// remains verified, and records activity subject to the session idle timeout. +func (service *SessionService) Authenticate(ctx context.Context, rawToken string) (AuthenticatedSession, error) { + const location = "SessionService.Authenticate" + token, err := domain.ParseSecretToken(rawToken) + if err != nil { + return AuthenticatedSession{}, ErrUnauthenticated + } + now := service.deps.Clock() + session, err := service.deps.Sessions.FindActive(ctx, token.Hash(), now, service.settings.IdleTimeout) + if errors.Is(err, outbound.ErrSessionNotFound) { + return AuthenticatedSession{}, ErrUnauthenticated + } + if err != nil { + return AuthenticatedSession{}, fmt.Errorf("%s - read session: %w", location, err) + } + user, err := service.deps.Users.GetByID(ctx, session.UserID) + if errors.Is(err, outbound.ErrUserNotFound) || err == nil && !user.EmailVerified() { + return AuthenticatedSession{}, ErrUnauthenticated + } + if err != nil { + return AuthenticatedSession{}, fmt.Errorf("%s - read account: %w", location, err) + } + if err := service.deps.Sessions.Touch(ctx, session.ID, now, service.settings.IdleTimeout); errors.Is(err, outbound.ErrSessionNotFound) { + return AuthenticatedSession{}, ErrUnauthenticated + } else if err != nil { + return AuthenticatedSession{}, fmt.Errorf("%s - record activity: %w", location, err) + } + return AuthenticatedSession{ + User: user, + SessionID: session.ID, + CSRFToken: service.deps.Keyring.SessionCSRF(token), + }, nil +} + +// Logout revokes the session ID placed in context by authentication. A +// repeated logout is treated as an unauthenticated stale session. +func (service *SessionService) Logout(ctx context.Context, sessionID uuid.UUID) error { + if sessionID == uuid.Nil { + return ErrUnauthenticated + } + if err := service.deps.Sessions.Revoke(ctx, sessionID, service.deps.Clock()); errors.Is(err, outbound.ErrSessionNotFound) { + return ErrUnauthenticated + } else if err != nil { + return fmt.Errorf("SessionService.Logout - revoke session: %w", err) + } + return nil +} + +func (service *SessionService) takeLoginAttempt(ctx context.Context, email domain.EmailAddress, clientKey string) error { + if clientKey != "" { + if err := service.take(ctx, ScopeClient, service.deps.Keyring.ClientBucket(clientKey), service.settings.ClientHourlyLimit); err != nil { + return err + } + } + return service.take(ctx, ScopeAddress, service.deps.Keyring.EmailBucket(email.Normalized()), service.settings.EmailHourlyLimit) +} + +func (service *SessionService) take(ctx context.Context, scope, bucket string, limit int64) error { + decision, err := service.deps.Limiter.Take(ctx, bucket, outbound.RateLimitRule{Window: time.Hour, Limit: limit}) + if err != nil { + return fmt.Errorf("take %s login limit: %w", scope, err) + } + if !decision.Allowed { + if service.deps.Metrics != nil { + service.deps.Metrics.ObserveIdentityRateLimited(scope) + } + return &RateLimitedError{RetryAfter: decision.RetryAfter} + } + return nil +} diff --git a/backend/internal/usecase/identity/session_test.go b/backend/internal/usecase/identity/session_test.go new file mode 100644 index 0000000..dcc164e --- /dev/null +++ b/backend/internal/usecase/identity/session_test.go @@ -0,0 +1,445 @@ +package identity + +import ( + "context" + "errors" + "log/slog" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +type sessionTestUserRepository struct { + outbound.UserRepository + + users map[uuid.UUID]domain.User + byEmail map[string]domain.User + getByEmailCalls int + afterGetByEmail func() +} + +func (repository *sessionTestUserRepository) GetByID(_ context.Context, id uuid.UUID) (domain.User, error) { + user, ok := repository.users[id] + if !ok { + return domain.User{}, outbound.ErrUserNotFound + } + return user, nil +} + +func (repository *sessionTestUserRepository) GetByEmail(_ context.Context, email domain.EmailAddress) (domain.User, error) { + repository.getByEmailCalls++ + user, ok := repository.byEmail[email.Normalized()] + if !ok { + return domain.User{}, outbound.ErrUserNotFound + } + if repository.afterGetByEmail != nil { + repository.afterGetByEmail() + } + return user, nil +} + +type sessionTestSessionRepository struct { + outbound.SessionRepository + + active map[domain.SecretTokenHash]domain.Session + created []domain.Session + revoked []uuid.UUID + touched []uuid.UUID +} + +func (repository *sessionTestSessionRepository) Create(_ context.Context, session domain.Session) error { + repository.active[session.TokenHash] = session + repository.created = append(repository.created, session) + return nil +} + +func (repository *sessionTestSessionRepository) FindActive( + _ context.Context, + hash domain.SecretTokenHash, + at time.Time, + idleTimeout time.Duration, +) (domain.Session, error) { + session, ok := repository.active[hash] + if !ok || session.RevokedAt != nil || !session.ExpiresAt.After(at) || !session.LastSeenAt.After(at.Add(-idleTimeout)) { + return domain.Session{}, outbound.ErrSessionNotFound + } + return session, nil +} + +func (repository *sessionTestSessionRepository) Touch(_ context.Context, id uuid.UUID, at time.Time, idleTimeout time.Duration) error { + for hash, session := range repository.active { + if session.ID != id { + continue + } + if session.RevokedAt != nil || !session.ExpiresAt.After(at) || !session.LastSeenAt.After(at.Add(-idleTimeout)) { + return outbound.ErrSessionNotFound + } + session.LastSeenAt = at + repository.active[hash] = session + repository.touched = append(repository.touched, id) + return nil + } + return outbound.ErrSessionNotFound +} + +func (repository *sessionTestSessionRepository) Revoke(_ context.Context, id uuid.UUID, at time.Time) error { + for hash, session := range repository.active { + if session.ID != id { + continue + } + if session.RevokedAt != nil { + return outbound.ErrSessionNotFound + } + session.RevokedAt = &at + repository.active[hash] = session + repository.revoked = append(repository.revoked, id) + return nil + } + return outbound.ErrSessionNotFound +} + +type sessionTestUnit struct { + outbound.UnitOfWork + + users outbound.UserRepository + sessions outbound.SessionRepository +} + +func (unit sessionTestUnit) Users() outbound.UserRepository { return unit.users } +func (unit sessionTestUnit) Sessions() outbound.SessionRepository { return unit.sessions } + +type sessionTestTransactor struct{ unit outbound.UnitOfWork } + +func (transactor sessionTestTransactor) WithinTransaction(ctx context.Context, fn func(context.Context, outbound.UnitOfWork) error) error { + return fn(ctx, transactor.unit) +} + +type sessionTestLimiter struct { + decision outbound.RateLimitDecision + keys []string +} + +func (limiter *sessionTestLimiter) Take(_ context.Context, key string, _ ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) { + limiter.keys = append(limiter.keys, key) + return limiter.decision, nil +} + +type sessionTestHasher struct { + verifyErr error + dummyErr error + verifyCalls int + dummyCalls int +} + +func (*sessionTestHasher) Hash(context.Context, domain.Password) (domain.PasswordHash, error) { + return domain.NewPasswordHash(testPasswordPHC) +} + +func (hasher *sessionTestHasher) Verify(context.Context, domain.Password, domain.PasswordHash) (bool, error) { + hasher.verifyCalls++ + return false, hasher.verifyErr +} + +func (hasher *sessionTestHasher) VerifyDummy(context.Context, domain.Password) error { + hasher.dummyCalls++ + if hasher.dummyErr != nil { + return hasher.dummyErr + } + return outbound.ErrPasswordMismatch +} + +type sessionTestFixture struct { + service *SessionService + users *sessionTestUserRepository + sessions *sessionTestSessionRepository + limiter *sessionTestLimiter + hasher *sessionTestHasher + keyring *Keyring + now time.Time +} + +func newSessionTestFixture(t *testing.T, user domain.User, limiterDecision outbound.RateLimitDecision, verifyErr error) sessionTestFixture { + t.Helper() + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + users := &sessionTestUserRepository{ + users: map[uuid.UUID]domain.User{user.ID: user}, + byEmail: map[string]domain.User{user.Email.Normalized(): user}, + } + sessions := &sessionTestSessionRepository{active: make(map[domain.SecretTokenHash]domain.Session)} + unit := sessionTestUnit{users: users, sessions: sessions} + transactor := sessionTestTransactor{unit: unit} + limiter := &sessionTestLimiter{decision: limiterDecision} + hasher := &sessionTestHasher{verifyErr: verifyErr} + keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes))) + if err != nil { + t.Fatal(err) + } + service, err := NewSessionService(SessionDependencies{ + Transactor: transactor, + Users: users, + Sessions: sessions, + Credentials: NewCredentials(hasher), + Limiter: limiter, + Keyring: keyring, + Clock: func() time.Time { return now }, + Logger: slog.New(slog.NewTextHandler(&strings.Builder{}, nil)), + }, SessionSettings{ + ClientHourlyLimit: 30, + EmailHourlyLimit: 10, + IdleTimeout: 24 * time.Hour, + AbsoluteLifetime: 7 * 24 * time.Hour, + }) + if err != nil { + t.Fatal(err) + } + return sessionTestFixture{service: service, users: users, sessions: sessions, limiter: limiter, hasher: hasher, keyring: keyring, now: now} +} + +func sessionTestUser(t *testing.T, address string, verified bool, at time.Time) domain.User { + t.Helper() + email, err := domain.NewEmailAddress(address) + if err != nil { + t.Fatal(err) + } + hash, err := domain.NewPasswordHash(testPasswordPHC) + if err != nil { + t.Fatal(err) + } + user, err := domain.NewUser(domain.Registration{ + Email: email, + PasswordHash: hash, + Scenario: domain.ScenarioCandidate, + RegisteredAt: at, + }) + if err != nil { + t.Fatal(err) + } + if verified { + verifiedAt := at + user.EmailVerifiedAt = &verifiedAt + } + return user +} + +func TestSessionServiceLoginRotatesIncomingSessionAtomically(t *testing.T) { + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + user := sessionTestUser(t, "person@example.com", true, now) + fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil) + incoming, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + old, err := domain.NewSession(domain.NewSessionInput{ + UserID: user.ID, + TokenHash: incoming.Hash(), + StartedAt: now.Add(-time.Hour), + AbsoluteLifetime: 7 * 24 * time.Hour, + }) + if err != nil { + t.Fatal(err) + } + fixture.sessions.active[old.TokenHash] = old + + result, err := fixture.service.Login(context.Background(), LoginCommand{ + Email: "PERSON@example.com", + Password: "correct horse battery staple", + ClientKey: "client-address", + Incoming: incoming, + }) + if err != nil { + t.Fatalf("Login() error = %v", err) + } + if len(fixture.sessions.created) != 1 || len(fixture.sessions.revoked) != 1 || fixture.sessions.revoked[0] != old.ID { + t.Fatalf("rotation created %d sessions and revoked %v", len(fixture.sessions.created), fixture.sessions.revoked) + } + if result.Session.TokenHash == incoming.Hash() || result.Session.UserID != user.ID || !result.Session.ExpiresAt.Equal(now.Add(7*24*time.Hour)) { + t.Fatalf("new session = %+v, want a fresh token for the verified user with the configured deadline", result.Session) + } + if result.Token.Hash() != result.Session.TokenHash || !fixture.keyring.VerifySessionCSRF(result.Token, result.CSRFToken) { + t.Fatal("login result did not bind the cookie token, database hash, and CSRF token") + } + if fixture.hasher.verifyCalls != 1 || fixture.limiter.keys[0] != fixture.keyring.ClientBucket("client-address") || + fixture.limiter.keys[1] != fixture.keyring.EmailBucket(user.Email.Normalized()) { + t.Fatalf("login checks: hash calls=%d, limiter keys=%v", fixture.hasher.verifyCalls, fixture.limiter.keys) + } +} + +func TestSessionServiceLoginKeepsUnknownAndWrongCredentialsIndistinguishable(t *testing.T) { + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + for _, test := range []struct { + name string + user *domain.User + verifyErr error + wantDummy int + }{ + {name: "unknown account", wantDummy: 1}, + {name: "wrong password", verifyErr: outbound.ErrPasswordMismatch}, + } { + t.Run(test.name, func(t *testing.T) { + var user domain.User + if test.user != nil { + user = *test.user + } else if test.verifyErr != nil { + user = sessionTestUser(t, "person@example.com", true, now) + } + fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, test.verifyErr) + _, err := fixture.service.Login(context.Background(), LoginCommand{Email: "person@example.com", Password: "not the password"}) + if !errors.Is(err, ErrInvalidCredentials) || fixture.hasher.dummyCalls != test.wantDummy || len(fixture.sessions.created) != 0 { + t.Fatalf("Login() error=%v dummy=%d sessions=%d", err, fixture.hasher.dummyCalls, len(fixture.sessions.created)) + } + }) + } +} + +func TestSessionServiceLoginDoesNotCreateOrRotateForUnverifiedAccount(t *testing.T) { + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + user := sessionTestUser(t, "pending@example.com", false, now) + fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil) + incoming, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + old, err := domain.NewSession(domain.NewSessionInput{ + UserID: user.ID, TokenHash: incoming.Hash(), StartedAt: now.Add(-time.Hour), AbsoluteLifetime: 7 * 24 * time.Hour, + }) + if err != nil { + t.Fatal(err) + } + fixture.sessions.active[old.TokenHash] = old + + _, err = fixture.service.Login(context.Background(), LoginCommand{ + Email: "pending@example.com", Password: "correct horse battery staple", Incoming: incoming, + }) + if !errors.Is(err, ErrEmailNotVerified) || len(fixture.sessions.created) != 0 || len(fixture.sessions.revoked) != 0 { + t.Fatalf("Login() error=%v created=%d revoked=%v", err, len(fixture.sessions.created), fixture.sessions.revoked) + } +} + +func TestSessionServiceLoginRejectsChangedCredentialSnapshot(t *testing.T) { + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + changedPasswordHash, err := domain.NewPasswordHash(strings.Replace(testPasswordPHC, "aGFza", "bGFza", 1)) + if err != nil { + t.Fatal(err) + } + for _, test := range []struct { + name string + change func(domain.User) domain.User + }{ + { + name: "registration version", + change: func(user domain.User) domain.User { + user.RegistrationVersion++ + return user + }, + }, + { + name: "password hash", + change: func(user domain.User) domain.User { + user.PasswordHash = changedPasswordHash + return user + }, + }, + } { + t.Run(test.name, func(t *testing.T) { + user := sessionTestUser(t, "person@example.com", true, now) + fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil) + fixture.users.afterGetByEmail = func() { + changed := fixture.users.users[user.ID] + fixture.users.users[user.ID] = test.change(changed) + } + + _, err := fixture.service.Login(context.Background(), LoginCommand{ + Email: "person@example.com", Password: "correct horse battery staple", + }) + if !errors.Is(err, ErrInvalidCredentials) || len(fixture.sessions.created) != 0 || len(fixture.sessions.revoked) != 0 { + t.Fatalf("Login() error=%v created=%d revoked=%v, want changed snapshot rejected without session writes", err, len(fixture.sessions.created), fixture.sessions.revoked) + } + }) + } +} + +func TestSessionServiceLoginAppliesEmailLimitBeforeAccountLookup(t *testing.T) { + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + user := sessionTestUser(t, "person@example.com", true, now) + fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: false, RetryAfter: time.Minute}, nil) + _, err := fixture.service.Login(context.Background(), LoginCommand{Email: "person@example.com", Password: "correct horse battery staple"}) + var limited *RateLimitedError + if !errors.As(err, &limited) || limited.RetryAfter != time.Minute || fixture.users.getByEmailCalls != 0 || fixture.hasher.verifyCalls != 0 { + t.Fatalf("Login() error=%v, lookups=%d, verifies=%d", err, fixture.users.getByEmailCalls, fixture.hasher.verifyCalls) + } +} + +func TestSessionServiceAuthenticateUsesDatabaseSessionState(t *testing.T) { + now := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC) + user := sessionTestUser(t, "person@example.com", true, now) + fixture := newSessionTestFixture(t, user, outbound.RateLimitDecision{Allowed: true}, nil) + token, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + session, err := domain.NewSession(domain.NewSessionInput{ + UserID: user.ID, TokenHash: token.Hash(), StartedAt: now.Add(-time.Minute), AbsoluteLifetime: 7 * 24 * time.Hour, + }) + if err != nil { + t.Fatal(err) + } + fixture.sessions.active[session.TokenHash] = session + + authenticated, err := fixture.service.Authenticate(context.Background(), token.Reveal()) + if err != nil || authenticated.SessionID != session.ID || authenticated.User.ID != user.ID || len(fixture.sessions.touched) != 1 { + t.Fatalf("Authenticate() = %+v, %v, touches=%v", authenticated, err, fixture.sessions.touched) + } + if !fixture.keyring.VerifySessionCSRF(token, authenticated.CSRFToken) { + t.Fatal("authenticated session returned a CSRF token for a different session") + } + if _, err := fixture.service.Authenticate(context.Background(), "bad"); !errors.Is(err, ErrUnauthenticated) { + t.Fatalf("Authenticate(malformed) error = %v, want ErrUnauthenticated", err) + } + + expired, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + expiredSession, err := domain.NewSession(domain.NewSessionInput{ + UserID: user.ID, TokenHash: expired.Hash(), StartedAt: now.Add(-8 * 24 * time.Hour), AbsoluteLifetime: 7 * 24 * time.Hour, + }) + if err != nil { + t.Fatal(err) + } + fixture.sessions.active[expiredSession.TokenHash] = expiredSession + if _, err := fixture.service.Authenticate(context.Background(), expired.Reveal()); !errors.Is(err, ErrUnauthenticated) { + t.Fatalf("Authenticate(expired) error = %v, want ErrUnauthenticated", err) + } +} + +func TestKeyringSessionCSRFIsDomainSeparatedAndFailsClosed(t *testing.T) { + keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes))) + if err != nil { + t.Fatal(err) + } + first, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + second, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + csrf := keyring.SessionCSRF(first) + if len(csrf) != 43 || !keyring.VerifySessionCSRF(first, csrf) || keyring.VerifySessionCSRF(second, csrf) || + keyring.VerifySessionCSRF(domain.SecretToken{}, "") { + t.Fatal("session CSRF derivation did not stay bound to a valid session token") + } +} + +var _ outbound.UserRepository = (*sessionTestUserRepository)(nil) +var _ outbound.SessionRepository = (*sessionTestSessionRepository)(nil) +var _ outbound.UnitOfWork = sessionTestUnit{} +var _ outbound.Transactor = sessionTestTransactor{} +var _ outbound.RateLimiter = (*sessionTestLimiter)(nil) +var _ outbound.PasswordHasher = (*sessionTestHasher)(nil) diff --git a/backend/internal/usecase/notification/delivery_retry_operator.go b/backend/internal/usecase/notification/delivery_retry_operator.go new file mode 100644 index 0000000..8554f29 --- /dev/null +++ b/backend/internal/usecase/notification/delivery_retry_operator.go @@ -0,0 +1,130 @@ +package notification + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +var ErrDuplicateRiskAcknowledgementRequired = errors.New("duplicate-risk acknowledgement is required") + +const DuplicateRiskWarning = "The earlier send may already have been accepted. After the provider's deduplication window, the old key does not guarantee deduplication; retrying can send a duplicate." + +// DeliveryRetryInspection contains the metadata an operator needs to decide +// whether an unknown delivery is eligible for a manual retry. It has no +// recipient address, token, subject, or body. +type DeliveryRetryInspection struct { + DeliveryID uuid.UUID + Provider string + ProviderAccount string + Status domain.DeliveryStatus + AttemptCount int32 + NextAttemptAt time.Time + FirstSendStartedAt time.Time + ManualCycleStarted time.Time +} + +// DeliveryRetryOperator inspects and authorizes retries of terminal unknown +// deliveries. Authorization only schedules work; the normal sender uses the +// delivery's pinned provider account, key, and stored body for the call. +type DeliveryRetryOperator struct { + transactor outbound.Transactor + deliveries outbound.DeliveryRepository + account domain.MailProviderAccount + providerWindow time.Duration + clock func() time.Time +} + +func NewDeliveryRetryOperator( + transactor outbound.Transactor, + deliveries outbound.DeliveryRepository, + account domain.MailProviderAccount, + providerWindow time.Duration, + clock func() time.Time, +) (*DeliveryRetryOperator, error) { + switch { + case transactor == nil: + return nil, errors.New("notification.NewDeliveryRetryOperator - transactor must be set") + case deliveries == nil: + return nil, errors.New("notification.NewDeliveryRetryOperator - delivery repository must be set") + case account.IsZero(): + return nil, errors.New("notification.NewDeliveryRetryOperator - provider account must be set") + case providerWindow < 0: + return nil, errors.New("notification.NewDeliveryRetryOperator - provider window must not be negative") + case clock == nil: + return nil, errors.New("notification.NewDeliveryRetryOperator - clock must be set") + } + return &DeliveryRetryOperator{ + transactor: transactor, + deliveries: deliveries, + account: account, + providerWindow: providerWindow, + clock: clock, + }, nil +} + +func (operator *DeliveryRetryOperator) Inspect(ctx context.Context, id uuid.UUID) (DeliveryRetryInspection, error) { + if id == uuid.Nil { + return DeliveryRetryInspection{}, fmt.Errorf("DeliveryRetryOperator.Inspect - delivery ID is required: %w", domain.ErrInvalidDelivery) + } + snapshot, err := operator.deliveries.GetRetrySnapshot(ctx, id) + if err != nil { + return DeliveryRetryInspection{}, fmt.Errorf("DeliveryRetryOperator.Inspect - read delivery: %w", err) + } + return DeliveryRetryInspection{ + DeliveryID: snapshot.ID, + Provider: snapshot.Provider, + ProviderAccount: snapshot.ProviderAccount, + Status: snapshot.Status, + AttemptCount: snapshot.AttemptCount, + NextAttemptAt: snapshot.NextAttemptAt, + FirstSendStartedAt: snapshot.FirstSendStartedAt, + ManualCycleStarted: snapshot.ManualRetryStartedAt, + }, nil +} + +// RetryUnknown requires the operator identity and explicit duplicate-risk +// acknowledgement, then atomically schedules the current terminal unknown +// attempt and appends its audit record. +func (operator *DeliveryRetryOperator) RetryUnknown( + ctx context.Context, + id uuid.UUID, + actor string, + acknowledgeDuplicateRisk bool, +) (string, error) { + if id == uuid.Nil { + return "", fmt.Errorf("DeliveryRetryOperator.RetryUnknown - delivery ID is required: %w", domain.ErrInvalidDelivery) + } + if !acknowledgeDuplicateRisk { + return "", ErrDuplicateRiskAcknowledgementRequired + } + parsedActor, err := domain.ParseMailRetryActor(actor) + if err != nil { + return "", err + } + minimumAge := time.Duration(0) + if operator.providerWindow > 0 { + minimumAge = max(operator.providerWindow-dedupSafetyMargin, 0) + } + err = operator.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return unit.Deliveries().AuthorizeUnknownRetry( + ctx, + id, + operator.account, + parsedActor, + acknowledgeDuplicateRisk, + operator.clock(), + minimumAge, + ) + }) + if err != nil { + return "", fmt.Errorf("DeliveryRetryOperator.RetryUnknown - authorize retry: %w", err) + } + return DuplicateRiskWarning, nil +} diff --git a/backend/internal/usecase/notification/delivery_retry_operator_test.go b/backend/internal/usecase/notification/delivery_retry_operator_test.go new file mode 100644 index 0000000..115fca0 --- /dev/null +++ b/backend/internal/usecase/notification/delivery_retry_operator_test.go @@ -0,0 +1,218 @@ +package notification + +import ( + "errors" + "testing" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/port/outbound" +) + +func TestDeliveryRetryOperatorAuthorizesOneRetryAfterTheAutomaticCutoff(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"} + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial pass = %+v, want unknown", result) + } + operator, err := NewDeliveryRetryOperator(h.transactor, h.deliveries, testAccount(t, "resend"), testIdempotencyWindow, func() time.Time { return h.now }) + if err != nil { + t.Fatalf("NewDeliveryRetryOperator() error = %v", err) + } + + inspection, err := operator.Inspect(t.Context(), h.delivery.ID()) + if err != nil || inspection.DeliveryID != h.delivery.ID() || inspection.Status != domain.DeliveryStatusUnknown || + inspection.ProviderAccount != "main" || inspection.AttemptCount != 1 { + t.Fatalf("Inspect() = %+v, %v; want only delivery retry metadata", inspection, err) + } + if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", false); !errors.Is(err, ErrDuplicateRiskAcknowledgementRequired) { + t.Fatalf("RetryUnknown() without acknowledgement error = %v, want acknowledgement required", err) + } + if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) { + t.Fatalf("RetryUnknown() before cutoff error = %v, want not allowed", err) + } + if len(h.deliveries.retryDecisions) != 0 || len(h.transport.mails) != 1 { + t.Fatal("a denied operator decision changed audit history or sent mail") + } + + h.now = h.now.Add(23 * time.Hour) + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass at the safety cutoff = %+v, want the automatic retry to stop as unknown", result) + } + if got := h.stored().delivery; got.Status() != domain.DeliveryStatusUnknown || !got.NextAttemptAt().IsZero() { + t.Fatalf("delivery at the safety cutoff is %s due %s, want unknown without a due time", got.Status(), got.NextAttemptAt()) + } + + warning, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true) + if err != nil || warning != DuplicateRiskWarning { + t.Fatalf("RetryUnknown() after cutoff = %q, %v; want the duplicate-risk warning", warning, err) + } + if len(h.deliveries.retryDecisions) != 1 || h.deliveries.retryDecisions[0].actor != "operator:mail-ops" || + !h.deliveries.retryDecisions[0].duplicateRiskAcknowledged || h.deliveries.retryDecisions[0].previousLeaseExpired { + t.Fatalf("retry audit = %+v, want one acknowledged operator decision", h.deliveries.retryDecisions) + } + if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); !errors.Is(err, outbound.ErrDeliveryRetryNotAllowed) { + t.Fatalf("second RetryUnknown() error = %v, want not allowed", err) + } + + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("manual retry pass = %+v, want accepted", result) + } + if len(h.transport.mails) != 2 || h.transport.mails[0].IdempotencyKey != h.transport.mails[1].IdempotencyKey || + h.transport.mails[0].IdempotencyKey != h.delivery.IdempotencyKey() || + h.transport.mails[0].TextBody != h.transport.mails[1].TextBody || + h.transport.mails[0].To.Address() != h.transport.mails[1].To.Address() { + t.Fatal("the manual retry did not reuse the pinned key and original message") + } +} + +func TestDeliveryRetryOperatorRequiresAnotherDecisionAfterManualUnknown(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"} + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial pass = %+v, want unknown", result) + } + operator, err := NewDeliveryRetryOperator(h.transactor, h.deliveries, testAccount(t, "resend"), testIdempotencyWindow, func() time.Time { return h.now }) + if err != nil { + t.Fatalf("NewDeliveryRetryOperator() error = %v", err) + } + h.now = h.now.Add(23 * time.Hour) + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("pass at cutoff = %+v, want unknown", result) + } + if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil { + t.Fatalf("RetryUnknown() after cutoff error = %v", err) + } + + h.transport.result = outbound.SendResult{ + Outcome: outbound.MailOutcomeRejected, + Rejection: outbound.MailRejectionRateLimited, + RetryAfter: 5 * time.Minute, + } + if result := h.pass(t); result.Outcome != inbound.MailPassRetry { + t.Fatalf("manual rate-limit pass = %+v, want a scheduled retry", result) + } + pending := h.stored().delivery + if pending.Status() != domain.DeliveryStatusPending || !pending.NextAttemptAt().Equal(h.now.Add(5*time.Minute)) { + t.Fatalf("manual rate-limit state = %s due %s, want pending with Retry-After", pending.Status(), pending.NextAttemptAt()) + } + h.now = pending.NextAttemptAt() + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"} + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("manual uncertain pass = %+v, want unknown", result) + } + unknown := h.stored().delivery + if unknown.Status() != domain.DeliveryStatusUnknown || !unknown.NextAttemptAt().IsZero() || len(h.deliveries.retryDecisions) != 1 { + t.Fatalf("manual uncertain state = %s due %s with %d decisions, want terminal unknown and one audit decision", unknown.Status(), unknown.NextAttemptAt(), len(h.deliveries.retryDecisions)) + } + calls := len(h.transport.mails) + if result := h.pass(t); result.Outcome != inbound.MailPassIdle || len(h.transport.mails) != calls { + t.Fatalf("pass after manual unknown = %+v with %d calls, want idle without a retry", result, len(h.transport.mails)) + } + if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil { + t.Fatalf("second RetryUnknown() after explicit acknowledgement = %v, want a fresh decision against the original cutoff", err) + } + if len(h.deliveries.retryDecisions) != 2 { + t.Fatalf("manual decisions = %d, want a new audit decision after the second unknown", len(h.deliveries.retryDecisions)) + } + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass after the new decision = %+v, want accepted", result) + } +} + +func TestDeliveryRetryOperatorKeepsConfirmedRefusalRetriesAfterTheDeduplicationCutoff(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"} + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial pass = %+v, want unknown", result) + } + operator, err := NewDeliveryRetryOperator(h.transactor, h.deliveries, testAccount(t, "resend"), testIdempotencyWindow, func() time.Time { return h.now }) + if err != nil { + t.Fatalf("NewDeliveryRetryOperator() error = %v", err) + } + h.now = h.now.Add(23 * time.Hour) + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("automatic pass at cutoff = %+v, want unknown", result) + } + if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil { + t.Fatalf("RetryUnknown() after cutoff error = %v", err) + } + refusal := outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionRateLimited, RetryAfter: 5 * time.Minute} + h.transport.result = refusal + if result := h.pass(t); result.Outcome != inbound.MailPassRetry { + t.Fatalf("first manual refusal = %+v, want retry", result) + } + h.now = h.stored().delivery.NextAttemptAt().Add(25 * time.Hour) + if result := h.pass(t); result.Outcome != inbound.MailPassRetry { + t.Fatalf("confirmed refusal after the old provider window = %+v, want a scheduled retry", result) + } + if got := h.stored().delivery; got.Status() != domain.DeliveryStatusPending || got.AttemptCount() != 3 || got.NextAttemptAt().IsZero() { + t.Fatalf("delivery after repeated confirmed refusals is %s after %d attempts due %s; want pending without a fabricated unknown", got.Status(), got.AttemptCount(), got.NextAttemptAt()) + } + h.now = h.stored().delivery.NextAttemptAt() + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"} + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("manual unknown result = %+v, want terminal unknown", result) + } + unknown := h.stored().delivery + if unknown.Status() != domain.DeliveryStatusUnknown || !unknown.NextAttemptAt().IsZero() { + t.Fatalf("delivery after unknown is %s due %s, want terminal unknown", unknown.Status(), unknown.NextAttemptAt()) + } + calls := len(h.transport.mails) + if result := h.pass(t); result.Outcome != inbound.MailPassIdle || len(h.transport.mails) != calls { + t.Fatalf("pass after unknown = %+v with %d calls, want idle", result, len(h.transport.mails)) + } +} + +func TestDeliveryRetryOperatorRecoversManualSendStartedWithoutAResult(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"} + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial pass = %+v, want unknown", result) + } + operator, err := NewDeliveryRetryOperator(h.transactor, h.deliveries, testAccount(t, "resend"), testIdempotencyWindow, func() time.Time { return h.now }) + if err != nil { + t.Fatalf("NewDeliveryRetryOperator() error = %v", err) + } + h.now = h.now.Add(23 * time.Hour) + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("automatic pass at cutoff = %+v, want unknown", result) + } + if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil { + t.Fatalf("RetryUnknown() after cutoff error = %v", err) + } + refusal := outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: outbound.MailRejectionRateLimited, RetryAfter: time.Minute} + h.transport.result = refusal + if result := h.pass(t); result.Outcome != inbound.MailPassRetry { + t.Fatalf("first manual rate limit = %+v, want a confirmed refusal retry", result) + } + h.now = h.stored().delivery.NextAttemptAt() + h.transactor.calls, h.transactor.settlementDown = 0, true + if _, err := h.service.ProcessNext(t.Context(), t.Context()); !errors.Is(err, errSettlementDown) { + t.Fatalf("ProcessNext() error = %v, want lost settlement after a started manual send", err) + } + if len(h.transport.mails) != 3 || !h.stored().hasSendStarted || h.stored().sendStartedAttemptCount != h.stored().delivery.AttemptCount() { + t.Fatalf("manual send starts = %d, marker = %d, attempt_count = %d; want an unresolved send after a confirmed refusal", len(h.transport.mails), h.stored().sendStartedAttemptCount, h.stored().delivery.AttemptCount()) + } + h.now = h.now.Add(testSenderLease) + h.transactor.settlementDown = false + calls := len(h.transport.mails) + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown || len(h.transport.mails) != calls { + t.Fatalf("recovery after lost manual result = %+v with %d calls, want terminal unknown without a provider call", result, len(h.transport.mails)-calls) + } + if _, err := operator.RetryUnknown(t.Context(), h.delivery.ID(), "operator:mail-ops", true); err != nil { + t.Fatalf("new decision after expired manual send lease = %v, want authorization from the original cutoff", err) + } + if len(h.deliveries.retryDecisions) != 2 || h.deliveries.retryDecisions[1].attemptCount != 3 || + len(h.stored().attempts) != 3 || h.stored().attempts[1].Outcome != domain.DeliveryOutcomeRejected || + h.stored().attempts[2].Outcome != domain.DeliveryOutcomeUnknown { + t.Fatalf("retry audit = %+v, attempts = %+v; want confirmed refusal then recovered unknown before the second decision", h.deliveries.retryDecisions, h.stored().attempts) + } + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + if result := h.pass(t); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("pass after a new manual decision = %+v, want accepted", result) + } +} diff --git a/backend/internal/usecase/notification/service_sender.go b/backend/internal/usecase/notification/service_sender.go index a83c10e..32b36de 100644 --- a/backend/internal/usecase/notification/service_sender.go +++ b/backend/internal/usecase/notification/service_sender.go @@ -150,8 +150,14 @@ func NewServiceMailSender( // claimedSend is a delivery that passed the claim transaction and is ready to // be sent, or the final result of a delivery the transaction already decided. type claimedSend struct { - delivery domain.Delivery - permit QuotaPermit + delivery domain.Delivery + permit QuotaPermit + firstSendStarted bool + sinceFirstSend time.Duration + manualRetryPending bool + manualRetryCycleStarted bool + sendStartUnsettled bool + requireDedupWindow bool // decided is set when the claim transaction ended the pass: the result // is final and nothing is sent. decided bool @@ -353,19 +359,23 @@ func (sender *ServiceMailSender) beforeSend(ctx context.Context, claim claimedSe return fmt.Errorf("read token and account: %w", err) } now := sender.clock() - if reason := delivery.CheckServiceMail(state, now); reason != "" { - if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil { - return fmt.Errorf("give the reservation back: %w", err) + if result, handled, err := sender.handleInvalidClaim(ctx, unit, claim, delivery, state, now); err != nil || handled { + if handled { + decided = &result } - cancelled, err := sender.cancel(ctx, unit, delivery, now, reason) + return err + } + started, err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner, + claim.requireDedupWindow, sender.safeRetryWindow()) + if err != nil { + return fmt.Errorf("mark send started: %w", err) + } + if !started { + result, err := sender.handleUnmarkedSend(ctx, unit, claim, delivery, now) if err != nil { return err } - decided = &cancelled.result - return nil - } - if err := unit.Deliveries().MarkSendStarted(ctx, delivery.ID(), sender.owner); err != nil { - return fmt.Errorf("mark send started: %w", err) + decided = &result } return nil }) @@ -375,6 +385,64 @@ func (sender *ServiceMailSender) beforeSend(ctx context.Context, claim claimedSe return decided, nil } +func (sender *ServiceMailSender) handleInvalidClaim( + ctx context.Context, + unit outbound.UnitOfWork, + claim claimedSend, + delivery domain.Delivery, + state domain.ServiceMailState, + now time.Time, +) (inbound.MailPassResult, bool, error) { + reason := delivery.CheckServiceMail(state, now) + if reason == "" { + return inbound.MailPassResult{}, false, nil + } + if delivery.Status() == domain.DeliveryStatusUnknown { + if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil { + return inbound.MailPassResult{}, true, err + } + stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now) + return stopped.result, true, err + } + if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil { + return inbound.MailPassResult{}, true, fmt.Errorf("give the reservation back: %w", err) + } + cancelled, err := sender.cancel(ctx, unit, delivery, now, reason) + return cancelled.result, true, err +} + +func (sender *ServiceMailSender) handleUnmarkedSend( + ctx context.Context, + unit outbound.UnitOfWork, + claim claimedSend, + delivery domain.Delivery, + now time.Time, +) (inbound.MailPassResult, error) { + if delivery.Status() == domain.DeliveryStatusUnknown { + if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil { + return inbound.MailPassResult{}, err + } + stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now) + return stopped.result, err + } + if claim.sendStartUnsettled { + inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now) + return inDoubt.result, err + } + if claim.requireDedupWindow && claim.firstSendStarted { + if err := sender.releaseUnsentReservation(ctx, unit, claim); err != nil { + return inbound.MailPassResult{}, err + } + stopped, err := sender.stopAutomaticRetry(ctx, unit, delivery, now) + return stopped.result, err + } + if claim.firstSendStarted { + inDoubt, err := sender.recordInDoubt(ctx, unit, delivery, now) + return inDoubt.result, err + } + return resultOf(inbound.MailPassLeaseLost, delivery), nil +} + // errNotSent stands for "the message did not leave the process" when a // reservation is given back before the transport was called. var errNotSent = errors.New("message was not sent") @@ -401,9 +469,17 @@ func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.Unit } delivery = rebound } - if sender.abandonedBeyondDeduplication(claimed) { + if claimed.ManualRetryCycleStarted && claimed.SendStartUnsettled { + // A manually authorized send started but its result was not recorded. + // Do not spend that authorization on another provider call. return sender.recordInDoubt(ctx, unit, delivery, now) } + if sender.retryBeyondDeduplication(claimed) { + if claimed.SendStartUnsettled { + return sender.recordInDoubt(ctx, unit, delivery, now) + } + return sender.stopAutomaticRetry(ctx, unit, delivery, now) + } state, err := unit.Deliveries().ServiceMailState(ctx, delivery.ID()) if err != nil { return claimedSend{}, fmt.Errorf("read token and account: %w", err) @@ -416,9 +492,39 @@ func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.Unit return claimedSend{}, fmt.Errorf("prepare send: %w", err) } if !decision.Proceed() { + return sender.waitForQuota(ctx, unit, delivery, decision, now) + } + return claimedSend{ + delivery: decision.Delivery, + permit: decision.Permit, + firstSendStarted: claimed.FirstSendStarted, + sinceFirstSend: claimed.SinceFirstSend, + manualRetryPending: claimed.ManualRetryPending, + manualRetryCycleStarted: claimed.ManualRetryCycleStarted, + sendStartUnsettled: claimed.SendStartUnsettled, + requireDedupWindow: sender.requiresDedupWindow(claimed), + }, nil +} + +func (sender *ServiceMailSender) waitForQuota( + ctx context.Context, + unit outbound.UnitOfWork, + delivery domain.Delivery, + decision SendDecision, + now time.Time, +) (claimedSend, error) { + if delivery.Status() != domain.DeliveryStatusUnknown || decision.ResetAt.IsZero() { return claimedSend{decided: true, result: resultOf(inbound.MailPassWaitingQuota, decision.Delivery)}, nil } - return claimedSend{delivery: decision.Delivery, permit: decision.Permit}, nil + at := latest(now, delivery.UpdatedAt()) + deferred, err := delivery.ScheduleUnknownRetry(at, latest(decision.ResetAt, at)) + if err != nil { + return claimedSend{}, fmt.Errorf("schedule uncertain quota retry: %w", err) + } + if err := unit.Deliveries().ScheduleUnknownRetry(ctx, sender.owner, deferred); err != nil { + return claimedSend{}, fmt.Errorf("store uncertain quota retry: %w", err) + } + return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, deferred)}, nil } // abandonedBeyondDeduplication reports a delivery whose earlier sender let its @@ -430,15 +536,31 @@ func (sender *ServiceMailSender) prepare(ctx context.Context, unit outbound.Unit // less a safety margin. A transport without provider-side deduplication // (window zero) never repeats a request that may have been sent. A lease // that never reached the request leaves nothing in doubt. -func (sender *ServiceMailSender) abandonedBeyondDeduplication(claimed outbound.ClaimedDelivery) bool { - if claimed.PreviousClaimedUntil.IsZero() || !claimed.FirstSendStarted { - return false - } - window := sender.gate.IdempotencyWindow() - if window <= 0 { +func (sender *ServiceMailSender) requiresDedupWindow(claimed outbound.ClaimedDelivery) bool { + if claimed.SendStartUnsettled { return true } - return claimed.SinceFirstSend >= max(window-dedupSafetyMargin, 0) + if claimed.ManualRetryPending { + return false + } + if claimed.Delivery.Status() == domain.DeliveryStatusUnknown { + return true + } + return claimed.HasUncertainAttempt && !claimed.ManualRetryCycleStarted +} + +func (sender *ServiceMailSender) retryBeyondDeduplication(claimed outbound.ClaimedDelivery) bool { + if !sender.requiresDedupWindow(claimed) { + return false + } + if !claimed.FirstSendStarted { + return true + } + return claimed.SinceFirstSend >= sender.safeRetryWindow() +} + +func (sender *ServiceMailSender) safeRetryWindow() time.Duration { + return max(sender.gate.IdempotencyWindow()-dedupSafetyMargin, 0) } // recordInDoubt records the lost attempt as unknown, without a next attempt, @@ -460,6 +582,35 @@ func (sender *ServiceMailSender) recordInDoubt(ctx context.Context, unit outboun return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil } +func (sender *ServiceMailSender) stopAutomaticRetry( + ctx context.Context, + unit outbound.UnitOfWork, + delivery domain.Delivery, + now time.Time, +) (claimedSend, error) { + next, err := delivery.StopAutomaticRetry(latest(now, delivery.UpdatedAt())) + if err != nil { + return claimedSend{}, fmt.Errorf("stop automatic retry: %w", err) + } + if err := unit.Deliveries().StopUnknownRetry(ctx, sender.owner, next); err != nil { + return claimedSend{}, fmt.Errorf("store stopped retry: %w", err) + } + sender.logger.WarnContext(ctx, "automatic retries stopped before the provider deduplication cutoff; the delivery remains unknown for an operator decision", + slog.String("delivery_id", delivery.ID().String()), + slog.String("kind", string(delivery.Kind()))) + return claimedSend{decided: true, result: resultOf(inbound.MailPassUnknown, next)}, nil +} + +func (sender *ServiceMailSender) releaseUnsentReservation(ctx context.Context, unit outbound.UnitOfWork, claim claimedSend) error { + if claim.permit.IsZero() || claim.permit.Reused() { + return nil + } + if _, err := sender.gate.SettleSend(ctx, unit, claim.permit, outbound.SendResult{}, errNotSent); err != nil { + return fmt.Errorf("release unused reservation: %w", err) + } + return nil +} + func (sender *ServiceMailSender) cancel( ctx context.Context, unit outbound.UnitOfWork, @@ -572,7 +723,8 @@ func (sender *ServiceMailSender) applyResult( return sender.applyNotSent(ctx, unit, claim, now, sendErr) } at := latest(now, delivery.UpdatedAt()) - next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until)) + manualRetry := claim.manualRetryPending || claim.manualRetryCycleStarted + next, attempt, err := delivery.RecordAttempt(sender.attemptInput(delivery, result, at, until, manualRetry)) if err != nil { return inbound.MailPassResult{}, fmt.Errorf("record attempt: %w", err) } @@ -588,7 +740,7 @@ func (sender *ServiceMailSender) applyResult( // attemptInput maps a transport answer to the attempt the delivery records. // until is the quota reset that SettleSend returned for a provider quota // refusal. -func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time) domain.DeliveryAttemptInput { +func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result outbound.SendResult, at, until time.Time, manualRetry bool) domain.DeliveryAttemptInput { input := domain.DeliveryAttemptInput{ At: at, Outcome: domain.DeliveryAttemptOutcome(result.Outcome), @@ -608,6 +760,8 @@ func (sender *ServiceMailSender) attemptInput(delivery domain.Delivery, result o // Zero means that the reset is unknown, and the delivery waits for an // operator. input.NextAttemptAt = latest(until, at) + case result.Outcome == outbound.MailOutcomeUnknown && !manualRetry && sender.gate.IdempotencyWindow() > 0: + input.NextAttemptAt = sender.settings.Retry.NextAttemptAt(at, delivery.AttemptCount()+1, result.RetryAfter) } return input } diff --git a/backend/internal/usecase/notification/service_sender_test.go b/backend/internal/usecase/notification/service_sender_test.go index b1588fd..b8bec37 100644 --- a/backend/internal/usecase/notification/service_sender_test.go +++ b/backend/internal/usecase/notification/service_sender_test.go @@ -36,8 +36,12 @@ type leasedRow struct { attempts []domain.DeliveryAttempt // firstSend is when the first request started, by the fake clock; zero // when none did. failures counts failures of the worker on the row. - firstSend time.Time - failures int32 + firstSend time.Time + manualRetryAuthorizedAt time.Time + manualRetryStartedAt time.Time + sendStartedAttemptCount int32 + hasSendStarted bool + failures int32 // seq is the insertion order, so the fake claims in a stable order like // the store, which orders by the due time and then by identifier. seq int @@ -60,8 +64,18 @@ type memoryDeliveries struct { brokenDecode uuid.UUID // stateErr makes the token and account read fail; stateSeq, when set, // answers successive reads with successive states. - stateErr error - stateSeq []domain.ServiceMailState + stateErr error + stateSeq []domain.ServiceMailState + retryDecisions []memoryRetryDecision +} + +type memoryRetryDecision struct { + deliveryID uuid.UUID + attemptCount int32 + actor string + duplicateRiskAcknowledged bool + previousLeaseExpired bool + decidedAt time.Time } func (store *memoryDeliveries) Get(_ context.Context, id uuid.UUID) (domain.Delivery, error) { @@ -88,7 +102,7 @@ func (store *memoryDeliveries) ClaimDue(_ context.Context, claim outbound.Delive due := !delivery.NextAttemptAt().IsZero() && !delivery.NextAttemptAt().After(claim.Now) pinned := delivery.ProviderAccount() == claim.Account || (delivery.ProviderAccount().Provider() == claim.RebindProvider && delivery.AttemptCount() == 0) - waiting := delivery.Status() == domain.DeliveryStatusPending || delivery.Status() == domain.DeliveryStatusWaitingQuota + waiting := delivery.Status() == domain.DeliveryStatusPending || delivery.Status() == domain.DeliveryStatusWaitingQuota || delivery.Status() == domain.DeliveryStatusUnknown free := row.owner == uuid.Nil || !row.until.After(claim.Now) if !due || !pinned || !waiting || !free || !containsKind(claim.Kinds, delivery.Kind()) { continue @@ -109,7 +123,17 @@ func (store *memoryDeliveries) ClaimDue(_ context.Context, claim outbound.Delive return outbound.ClaimedDelivery{}, &outbound.UnreadableDeliveryError{DeliveryID: delivery.ID(), Cancelled: true, Err: domain.ErrMailContentIntegrity} } row.owner, row.until = claim.Owner, claim.Now.Add(claim.Lease) - claimed := outbound.ClaimedDelivery{Delivery: delivery, PreviousClaimedUntil: previous, FailureCount: row.failures} + claimed := outbound.ClaimedDelivery{ + Delivery: delivery, + PreviousClaimedUntil: previous, + ManualRetryPending: !row.manualRetryAuthorizedAt.IsZero() && row.manualRetryStartedAt.IsZero(), + ManualRetryCycleStarted: !row.manualRetryStartedAt.IsZero(), + SendStartUnsettled: row.hasSendStarted && row.sendStartedAttemptCount == delivery.AttemptCount(), + HasUncertainAttempt: slices.ContainsFunc(row.attempts, func(attempt domain.DeliveryAttempt) bool { + return attempt.Outcome == domain.DeliveryOutcomeUnknown + }), + FailureCount: row.failures, + } if !row.firstSend.IsZero() { claimed.FirstSendStarted, claimed.SinceFirstSend = true, claim.Now.Sub(row.firstSend) } @@ -127,6 +151,76 @@ func containsKind(kinds []domain.MailKind, kind domain.MailKind) bool { return false } +func (store *memoryDeliveries) GetRetrySnapshot(_ context.Context, id uuid.UUID) (outbound.DeliveryRetrySnapshot, error) { + row := store.rows[id] + if row == nil { + return outbound.DeliveryRetrySnapshot{}, outbound.ErrDeliveryNotFound + } + return outbound.DeliveryRetrySnapshot{ + ID: id, + Provider: row.delivery.ProviderAccount().Provider(), + ProviderAccount: row.delivery.ProviderAccount().Account(), + Status: row.delivery.Status(), + AttemptCount: row.delivery.AttemptCount(), + NextAttemptAt: row.delivery.NextAttemptAt(), + FirstSendStartedAt: row.firstSend, + ManualRetryStartedAt: row.manualRetryStartedAt, + }, nil +} + +func (store *memoryDeliveries) AuthorizeUnknownRetry( + _ context.Context, + id uuid.UUID, + account domain.MailProviderAccount, + actor domain.MailRetryActor, + acknowledgeDuplicateRisk bool, + at time.Time, + minimumAge time.Duration, +) error { + row := store.rows[id] + if row == nil || account != row.delivery.ProviderAccount() || row.delivery.Status() != domain.DeliveryStatusUnknown || + !row.delivery.NextAttemptAt().IsZero() || row.delivery.AttemptCount() == 0 || actor == "" || + !acknowledgeDuplicateRisk || minimumAge < 0 || + (row.owner != uuid.Nil && row.until.After(store.now())) { + return outbound.ErrDeliveryRetryNotAllowed + } + started := row.firstSend + if started.IsZero() || at.Sub(started) < minimumAge { + return outbound.ErrDeliveryRetryNotAllowed + } + previousLeaseExpired := row.owner != uuid.Nil + if !row.manualRetryStartedAt.IsZero() && row.hasSendStarted && row.sendStartedAttemptCount == row.delivery.AttemptCount() { + lostAttemptAt := latest(at, latest(row.delivery.UpdatedAt(), row.delivery.LastAttemptAt())) + lost, attempt, err := row.delivery.RecordAttempt(domain.DeliveryAttemptInput{ + At: lostAttemptAt, + Outcome: domain.DeliveryOutcomeUnknown, + }) + if err != nil { + return err + } + row.delivery = lost + row.attempts = append(row.attempts, attempt) + } + updatedAt := latest(at, row.delivery.UpdatedAt()) + next, err := restoreMemoryDelivery(row.delivery, updatedAt, updatedAt, row.delivery.Version()+1) + if err != nil { + return err + } + row.delivery = next + row.manualRetryAuthorizedAt = at + row.manualRetryStartedAt = time.Time{} + row.owner, row.until = uuid.Nil, time.Time{} + store.retryDecisions = append(store.retryDecisions, memoryRetryDecision{ + deliveryID: id, + attemptCount: row.delivery.AttemptCount(), + actor: string(actor), + duplicateRiskAcknowledged: acknowledgeDuplicateRisk, + previousLeaseExpired: previousLeaseExpired, + decidedAt: at, + }) + return nil +} + func (store *memoryDeliveries) ReleaseClaim(_ context.Context, id, owner uuid.UUID) (bool, error) { row := store.rows[id] if row == nil || row.owner != owner { @@ -162,6 +256,44 @@ func (store *memoryDeliveries) replace(next domain.Delivery, release bool) error return nil } +func restoreMemoryDelivery(delivery domain.Delivery, nextAttemptAt, updatedAt time.Time, version int64) (domain.Delivery, error) { + return domain.RestoreDelivery(domain.DeliverySnapshot{ + ID: delivery.ID(), + SourceEventID: delivery.SourceEventID(), + RecipientUserID: delivery.RecipientUserID(), + RecipientAddress: delivery.Recipient().Address(), + Content: delivery.Content(), + ProviderAccount: delivery.ProviderAccount(), + IdempotencyKey: delivery.IdempotencyKey(), + Status: delivery.Status(), + AttemptCount: delivery.AttemptCount(), + NextAttemptAt: nextAttemptAt, + LastAttemptAt: delivery.LastAttemptAt(), + ProviderMessageID: delivery.ProviderMessageID(), + EmailTokenID: delivery.EmailTokenID(), + CancelReason: delivery.CancelReason(), + Version: version, + CreatedAt: delivery.CreatedAt(), + UpdatedAt: updatedAt, + }) +} + +func (store *memoryDeliveries) StopUnknownRetry(_ context.Context, owner uuid.UUID, next domain.Delivery) error { + row := store.rows[next.ID()] + if row == nil || row.owner != owner || next.Status() != domain.DeliveryStatusUnknown || !next.NextAttemptAt().IsZero() { + return outbound.ErrDeliveryVersionConflict + } + return store.replace(next, true) +} + +func (store *memoryDeliveries) ScheduleUnknownRetry(_ context.Context, owner uuid.UUID, next domain.Delivery) error { + row := store.rows[next.ID()] + if row == nil || row.owner != owner || next.Status() != domain.DeliveryStatusUnknown || next.NextAttemptAt().IsZero() { + return outbound.ErrDeliveryVersionConflict + } + return store.replace(next, true) +} + func (store *memoryDeliveries) RecordAttempt(_ context.Context, next domain.Delivery, attempt domain.DeliveryAttempt) error { if err := store.replace(next, true); err != nil { return err @@ -185,11 +317,31 @@ func (store *memoryDeliveries) LockClaimed(_ context.Context, id, owner uuid.UUI return row != nil && row.owner == owner, nil } -func (store *memoryDeliveries) MarkSendStarted(_ context.Context, id, owner uuid.UUID) error { - if row := store.rows[id]; row != nil && row.owner == owner && row.firstSend.IsZero() { +func (store *memoryDeliveries) MarkSendStarted(_ context.Context, id, owner uuid.UUID, requireDedupWindow bool, safeWindow time.Duration) (bool, error) { + row := store.rows[id] + if row == nil || row.owner != owner { + return false, nil + } + manualPending := !row.manualRetryAuthorizedAt.IsZero() && row.manualRetryStartedAt.IsZero() + startedAt := row.firstSend + if requireDedupWindow && !manualPending && !startedAt.IsZero() && store.now().Sub(startedAt) >= safeWindow { + return false, nil + } + if row.firstSend.IsZero() { row.firstSend = store.now() } - return nil + row.sendStartedAttemptCount = row.delivery.AttemptCount() + row.hasSendStarted = true + if manualPending { + row.manualRetryStartedAt = store.now() + next, err := restoreMemoryDelivery(row.delivery, time.Time{}, row.delivery.UpdatedAt(), row.delivery.Version()) + if err != nil { + return false, err + } + row.delivery = next + } + row.failures = 0 + return true, nil } func (store *memoryDeliveries) RecordFailure(_ context.Context, id, owner uuid.UUID, at, nextAttemptAt time.Time, maxFailures int32, countFailure bool) (bool, error) { @@ -435,14 +587,14 @@ func TestServiceMailSenderMapsEveryTransportResultToTheDeliveryState(t *testing. wantOutcome: inbound.MailPassWaitingQuota, wantStatus: domain.DeliveryStatusWaitingQuota, wantAttempts: 1, }, { - name: "an uncertain answer is unknown, counted, and not retried", + name: "an uncertain answer is unknown and retried within the provider window", result: outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"}, - wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1, + wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantNext: start.Add(time.Minute), wantAttempts: 1, wantUsed: 1, }, { - name: "a transport that answers without an outcome is unknown, never not sent", + name: "a transport that answers without an outcome is unknown and retried within the provider window", result: outbound.SendResult{}, - wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantAttempts: 1, wantUsed: 1, + wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantNext: start.Add(time.Minute), wantAttempts: 1, wantUsed: 1, }, { name: "no transport leaves the delivery as it was", @@ -490,6 +642,53 @@ func TestServiceMailSenderMapsEveryTransportResultToTheDeliveryState(t *testing. } } +func TestServiceMailSenderKeepsEarlierUnknownVisibleAcrossConfirmedRefusal(t *testing.T) { + for _, test := range []struct { + name string + age time.Duration + wantOutcome inbound.MailPassOutcome + wantStatus domain.DeliveryStatus + wantCalls int + }{ + {name: "before cutoff continues under the same key", age: 22 * time.Hour, wantOutcome: inbound.MailPassAccepted, wantStatus: domain.DeliveryStatusAccepted, wantCalls: 3}, + {name: "at cutoff stops without inventing an attempt", age: 23 * time.Hour, wantOutcome: inbound.MailPassUnknown, wantStatus: domain.DeliveryStatusUnknown, wantCalls: 2}, + } { + t.Run(test.name, func(t *testing.T) { + h := newSenderTestHarness(t, testIdempotencyWindow) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, ProviderCode: "application_error"} + if result := h.pass(t); result.Outcome != inbound.MailPassUnknown { + t.Fatalf("initial pass = %+v, want unknown", result) + } + + h.now = h.now.Add(time.Minute) + h.transport.result = outbound.SendResult{ + Outcome: outbound.MailOutcomeRejected, + Rejection: outbound.MailRejectionRateLimited, + RetryAfter: time.Minute, + } + if result := h.pass(t); result.Outcome != inbound.MailPassRetry { + t.Fatalf("confirmed 429 pass = %+v, want retry", result) + } + row := h.stored() + if row.delivery.Status() != domain.DeliveryStatusPending || len(row.attempts) != 2 || + row.attempts[0].Outcome != domain.DeliveryOutcomeUnknown || row.attempts[1].Rejection != domain.DeliveryRejectionRateLimited { + t.Fatalf("delivery = %s with attempts %+v, want pending after unknown then confirmed 429", row.delivery.Status(), row.attempts) + } + + h.now = row.firstSend.Add(test.age) + h.transport.result = outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: testMessageID} + result := h.pass(t) + if result.Outcome != test.wantOutcome || row.delivery.Status() != test.wantStatus || len(h.transport.mails) != test.wantCalls { + t.Fatalf("pass = %+v, delivery %s, provider calls %d; want %s and %d calls", result, row.delivery.Status(), len(h.transport.mails), test.wantOutcome, test.wantCalls) + } + if test.wantStatus == domain.DeliveryStatusUnknown && + (len(row.attempts) != 2 || !row.delivery.NextAttemptAt().IsZero()) { + t.Fatalf("cutoff stop added an attempt or remained due: %s, due %s, attempts %+v", row.delivery.Status(), row.delivery.NextAttemptAt(), row.attempts) + } + }) + } +} + func TestServiceMailSenderCancelsBeforeTheTransportWhenTheMailIsNoLongerValid(t *testing.T) { tests := map[string]struct { change func(*domain.ServiceMailState, time.Time) diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 59c7a52..9630da1 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -229,12 +229,15 @@ services: SMTP_TLS_MODE: ${SMTP_TLS_MODE:-} # Argon2id derivations that may run at once, 64 MiB each (1 to 4). PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-1} - # Required: keys the registration idempotency records and rate limits. + # Required: keys idempotency records, rate limits, and session CSRF tokens. # Generate with: openssl rand -base64 48 IDENTITY_KEY_SECRET: ${IDENTITY_KEY_SECRET:?set IDENTITY_KEY_SECRET in .env (openssl rand -base64 48)} VERIFICATION_MAIL_MIN_INTERVAL: ${VERIFICATION_MAIL_MIN_INTERVAL:-1m} VERIFICATION_MAIL_DAILY_LIMIT: ${VERIFICATION_MAIL_DAILY_LIMIT:-5} IDENTITY_CLIENT_HOURLY_LIMIT: ${IDENTITY_CLIENT_HOURLY_LIMIT:-30} + IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT: ${IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT:-10} + IDENTITY_SESSION_IDLE_TIMEOUT: ${IDENTITY_SESSION_IDLE_TIMEOUT:-24h} + IDENTITY_SESSION_ABSOLUTE_LIFETIME: ${IDENTITY_SESSION_ABSOLUTE_LIFETIME:-168h} # Proxies whose X-Forwarded-For is believed: only the frontend container, # which has a fixed address on the pinned app network below. Other # containers of that network (Prometheus, exporters, Alloy) are not diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index c6e92a9..cc3891b 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -6,7 +6,7 @@ This document separates the target product architecture from the technical scaff The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port. -Registration and email confirmation work through the backend API. Frontend registration and confirmation screens remain placeholders; login and the other listed product workflows are not implemented: roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, and FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. +Registration, email confirmation, login, and basic current-session operations work through the backend API. Frontend registration and confirmation screens remain placeholders; the other listed product workflows are not implemented: roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, and FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow. See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage. @@ -202,11 +202,11 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai - `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading. - `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`. -- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Provider deduplication has a window (24 hours for Resend); after it a retry may send the message twice, so the delivery layer must stop retrying and escalate to an operator. +- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Resend keeps an idempotency key for 24 hours. The worker stops automatic retries at 23 hours, leaving a one-hour safety margin; after that an operator must decide whether to retry because the old key may no longer prevent a duplicate. `rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A `quota_exhausted` rejection also names the exhausted window in `QuotaPeriod` (`day` or `month`) when the provider said which; it is empty otherwise. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store. -A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. +A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. The transport makes one request; the worker owns retries, backoff, and outcome storage. The verification flows must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses. The Resend transport uses `net/http` without an SDK. One `Send` is one `POST https://api.resend.com/emails` with `from` (`EMAIL_FROM`), `to` (one recipient), `subject`, `text`, and `html` (a blank part is omitted), an `Authorization: Bearer` key, a `User-Agent`, and `Idempotency-Key` set to the message's key. Resend keeps a key for 24 hours and answers the same key and body with the original result without sending again, so a retry must repeat the stored body under the same key; a changed body under an old key is a conflict, not a reason to make a new key. `EMAIL_TIMEOUT` bounds the whole attempt. The client follows no redirects, uses HTTP/1.1, and opens a fresh connection for every send: a kept-alive connection that the server closed while idle would fail after the request was handed to it and turn a message Resend never saw into a false `unknown`. The request also has no `GetBody`, because `net/http` treats a POST with `Idempotency-Key` as replayable on a broken reused connection. The adapter has no retry loop and does not log. An answer is read up to 64 KiB; only the message ID and the error `name` are parsed, and the provider's message and body are not kept. @@ -230,11 +230,11 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt | Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend | | The caller's context ended before the request was written | the context error; nothing was sent | -Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy, the sending worker applies only the minimum schedule described in [Sending service mail](#sending-service-mail), and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas). +Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy, the sending worker applies the minimum schedule described in [Sending service mail](#sending-service-mail), and automatic retries of uncertain sends stop at 23 hours, one hour before Resend's 24-hour key window ends. Waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas). ### Mail deliveries -Implemented: the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented; see [Mail quotas](#mail-quotas). Implemented: the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy, and sending product notifications with the permission check before a send. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). Product flows do not call `MailRequester` yet, so notification requests remain queued. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented. +Implemented: the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented; see [Mail quotas](#mail-quotas). Implemented: the service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql`; see [Sending service mail](#sending-service-mail). Sending product notifications with the permission check before a send is not implemented. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). Product flows do not call `MailRequester` yet, so notification requests remain queued. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented. A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds: @@ -272,7 +272,7 @@ Statuses. The values follow the `MailSender` outcomes: | `pending` | Waits for its first attempt, or for a retry after a `temporary` or `rate_limited` rejection | Required: when it is due | | `accepted` | The provider accepted the message and returned `provider_message_id`: "accepted by the provider". Not delivery to or reading by a person; no status claims that | None; terminal | | `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal | -| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": a retry reuses the key and the stored body | Optional; none means no automatic retry | +| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": an eligible automatic or operator-approved retry uses the pinned key and stored body | Optional; none means operator review is required | | `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal | | `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides | @@ -285,7 +285,7 @@ Transitions: Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`. -Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The history is what an operator needs to judge an unknown outcome, what the end of the 24-hour key window counts from (the first attempt), and what an audit of a manual decision refers to. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt. +Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The first provider-call start is recorded by the database clock and is the age source for the automatic cutoff. Operator decisions are kept separately in `delivery_retry_decisions`, including the delivery ID, current attempt count, actor handle, explicit duplicate-risk acknowledgement, whether an expired lease was recovered, and decision time. It has no foreign key, so deleting the account does not erase the audit; row-level UPDATE/DELETE and statement-level TRUNCATE are refused. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt. Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. The quota therefore has its own counter that does not cascade, keyed by provider, provider account, and UTC day or month; see [Mail quotas](#mail-quotas). @@ -293,7 +293,7 @@ Provider account. Each delivery is pinned to the transport and account configure Migration `00012_add_delivery_sending.sql` is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission. -The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`. +The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`. Migration `00017_retry_unknown_mail.sql` adds the manual-cycle markers, the append-only decision journal, and `unknown` to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required. ### Mail quotas @@ -342,7 +342,7 @@ Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quot ### Sending service mail -Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Registration queues a verification email, and `ConfirmEmail` consumes its link. Product notification sending and the password reset flow are not implemented. +Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the retry schedule `RetryPolicy` (`send_retry.go`), bounded retries of unknown Resend outcomes, audited operator decisions through `DeliveryRetryOperator`, and the local command `backend/cmd/mail-retry/`. `Delivery.CheckServiceMail` and `Delivery.Cancel` hold the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop is in `backend/internal/worker/mailsender/`, and the inbound port is `inbound.MailPass` (`port/inbound/mail_sender.go`). The repository and migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql` store attempts, leases, retry cutoffs, and operator decisions. Registration queues a verification email, and `ConfirmEmail` consumes its link. Product notification sending and the password reset flow are not implemented. Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent. @@ -352,8 +352,8 @@ Links. The token travels only in the URL fragment: `/verify-emai One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps: -1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending` or `waiting_quota`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. A delivery in `unknown`, or in `waiting_quota` without a time, has no due time and waits for an operator. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows. -2. Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with `ServiceMailState`, so a revocation after the claim committed is honored, and notes `first_send_started_at` the first time. A mail that is no longer valid is cancelled and its reservation given back. Then one call to `MailSender.Send` with the stored content and the stable idempotency key `delivery/`. The sender never retries. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace. +1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending`, `waiting_quota`, or a scheduled `unknown`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. An initial uncertain result is scheduled only while the delivery is inside the automatic cutoff; terminal unknown rows and unknown rows without a due time wait for an operator. A single-use manual authorization also makes an unknown row due. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows. +2. Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with `ServiceMailState`, so a revocation after the claim committed is honored, and records `first_send_started_at` by the database clock. For an uncertain retry, it rechecks the age against the 23-hour cutoff here, after quota and lease waits, immediately before any network call. A manual authorization is consumed only when this send-start is recorded. A mail that is no longer valid is cancelled and its reservation given back. Then one call to `MailSender.Send` with the stored content and the stable idempotency key `delivery/`. The transport never retries internally. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace. 3. Settlement transaction. It locks the delivery row first (only while this worker still holds the lease), then `QuotaGate.SettleSend` and `DeliveryRepository.RecordClaimedAttempt` commit together, and the lease ends with the attempt. `RecordClaimedAttempt` applies only over the delivery's version and only for the lease owner, so a worker whose lease was taken over cannot record, and if two workers reach this step for one delivery only the first is kept; the other rolls back, including its quota settlement, and reports `lease_lost`. A database failure while storing the answer is repeated up to three times inside a settlement budget, because the answer exists only in memory until it is stored. Time budget. The lease is `EMAIL_TIMEOUT` plus one minute. The claim and the check come first; the call gets what remains of the lease minus the settlement budget (20 seconds), so claim, call, and the whole settlement fit inside the lease. When shutdown has begun the settlement budget is the shorter of 5 seconds and `SHUTDOWN_TIMEOUT` minus the 3-second shutdown grace (at least 1 second), so the process stops within its shutdown timeout, which is 10 seconds by default (the Compose stop grace period is 30 seconds). A result that cannot be stored in time is covered by the takeover below. @@ -385,22 +385,22 @@ What a provider answer becomes. The delivery state machine of `domain.Delivery` | `rejected` `permanent` or `invalid_request` | `rejected` | none | released | | `rejected` `temporary` or `rate_limited` | `pending` | now plus `RetryPolicy`: 1 minute, doubling to at most 30 minutes, never shorter than the provider's `Retry-After` | released | | `rejected` `quota_exhausted` | `waiting_quota` | the reset the gate returns (next 00:00 UTC for a day, the first of the next month for a month); none when the provider named no window | window marked full | -| `unknown` | `unknown` | none: no automatic retry | counted | +| `unknown` | `unknown` | minimum retry schedule until the 23-hour cutoff; after that, none until an operator decision | counted | | `Send` error: no transport (`ErrMailChannelUnavailable`) or the context ended | unchanged, lease released | still due | released | | `Send` error: invalid message (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | none | released | | `Send` error: anything else without an answer | not counted against the row; it moves back by `RetryPolicy` and the worker backs off | now plus `RetryPolicy` | released | -The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with `token_expired`. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. `unknown` is never read as not sent and is never repeated by the worker; an operator decides, and the alert `LincodexMailDeliveryUnknownOutcome` fires. +The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with `token_expired`. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. Confirmed `temporary` and `rate_limited` refusals are retried with the same pinned account, key, and body; the `Retry-After` value is a lower bound. A confirmed refusal proves that request was not accepted, but it does not clear uncertainty from an earlier unknown attempt. Automatic retries of uncertain Resend outcomes use the same key and exact body only until 23 hours after the database-recorded first send, one hour before Resend's documented 24-hour key expiry. The last storage check repeats this cutoff immediately before the provider call. An unknown answer or a lost lease after send-start ends automatic retries and requires operator review. A pending manual decision permits a potential send; confirmed temporary or 429 refusals may continue under that decision, but an unknown result or lost lease after send-start requires another explicit decision. Recovery records a lost send as an unknown attempt before it schedules the new decision, and does not call the provider. A manual decision does not restart Resend's key window. The local `mail-retry` command uses the database credential as its operator boundary: `make -C backend mail-retry ARGS='inspect --delivery '` shows metadata and the duplicate warning, while `make -C backend mail-retry ARGS='retry --delivery --actor operator: --acknowledge-duplicate-risk'` prints the warning before atomically scheduling and auditing a single-use decision. It never calls a provider. The actor is an audit handle, not an authentication mechanism; there is no HTTP operator endpoint. Reusing an expired key may send a duplicate despite the acknowledgement. The alert `LincodexMailDeliveryUnknownOutcome` fires while an outcome needs review. -A worker lost after the call. If a worker stops after it called the provider but before it stored the answer, its lease expires and another worker claims the delivery on the same attempt and repeats the request with the same idempotency key. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from `first_send_started_at` (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an `unknown` attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt. +Automatic retry after a lost worker. If a worker stops after a provider call but before storing the answer, another worker may claim that attempt and repeat the request with the same key while the 23-hour cutoff has not passed. A lost result after a manual send-start is recorded as unknown and waits for another operator decision; recovery does not call the provider. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from `first_send_started_at` (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an `unknown` attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt. Failing rows. A fault in one row must not hold the head of the queue. When the claim transaction fails after it took a row, its lease rolls back with it, so the same row would be claimed again at once and every delivery behind it would wait. Only a fault that the row itself causes is counted against it: a domain rule it breaks (`ErrInvalidDelivery`, `ErrDeliveryTransition`, invalid content or address), a row that cannot be restored for a reason other than a hash mismatch, or a data or integrity constraint refusal (SQLSTATE classes 22 and 23, `outbound.ErrRowFault`). Everything else says nothing about the row and is never counted: a context that ended, a timeout, a deadlock, a lost connection (SQLSTATE 08, 40, 53, 57, XX), an I/O error, a missing quota configuration. Such an error is returned to the worker, which backs off like for any global failure, and the lease expires or rolls back. For a counted fault the sender records the failure in a short transaction of its own (`RecordFailure`): `failure_count` is incremented, the lease ends, and the row is due again by `RetryPolicy` (outcome `row_failed`; the next pass takes the delivery behind it). The statement leaves a row alone that another worker holds under a live lease, so a claim that rolled back cannot disturb a row that someone else has just claimed. The count means consecutive failures: a successful claim and preparation (the check before the send) clears it, and so does a recorded attempt. A circuit breaker in the worker stops the counting when failures hit different rows pass after pass: three passes in a row that fail on three different rows are read as a global fault, the worker waits with a growing backoff (a `row_failed` pass never loops at once), and failures are moved back but not counted, and no row is cancelled, until a pass succeeds. After 3 consecutive counted failures the row is cancelled with the reason `processing_failed`, the existing terminal status that fits: it is visible to the operator and the alert below fires, and a new status was not needed. A database outage that also stops this record leaves the row under its lease, which expires. -`EMAIL_PROVIDER=disabled`. Bootstrap does not start the loop: `newMailSenderWorker` returns no worker and logs `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, so `lincodex_mail_sender_running` stays 0 and `LincodexMailDeliveriesOverdue` stays silent. Stored mail waits, pinned to `disabled`; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. A worker that is run against the disabled transport anyway (tests) gets `ErrMailChannelUnavailable` from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins. +`EMAIL_PROVIDER=disabled`. Bootstrap does not start the loop: `newMailSenderWorker` returns no worker and logs `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, so `lincodex_mail_sender_running` stays 0 and `LincodexMailDeliveriesOverdue` stays silent. Stored mail waits, pinned to `disabled`; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. The local operator command is available only with the Resend transport selected. A worker that is run against the disabled transport anyway (tests) gets `ErrMailChannelUnavailable` from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins. Loop and shutdown. `worker/mailsender` repeats passes: a pass that handled a delivery is followed at once by the next, an idle pass waits 5 seconds, and a database failure, a missing transport, or an interrupted call waits with the growing backoff. When the context ends the worker claims nothing more, lets the send in progress continue for 5 seconds, stores its result, and returns; the gauge is 0 from then on. The loop is a goroutine of the backend process on its own pool of two connections, like the other workers; more throughput comes from more instances, and each handles one delivery at a time, which suits service mail under the Resend Free quota. -Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches `accepted`, `rejected`, or `cancelled` (by any path: an attempt, a cancellation, the broken-row cancellation, or `processing_failed`), the same statement sets `text_body` and `html_body` to empty and `body_redacted_at`; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK `deliveries_body_present` accepts an empty body only with the mark; the domain restores such a row as redacted content (`RestoreRedactedMailContent`), which cannot be sent. `unknown` is not terminal and keeps its body, because a retry resends it; an operator who resolves it must clear it. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies. +Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches `accepted`, `rejected`, or `cancelled` (by any path: an attempt, a cancellation, the broken-row cancellation, or `processing_failed`), the same statement sets `text_body` and `html_body` to empty and `body_redacted_at`; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK `deliveries_body_present` accepts an empty body only with the mark; the domain restores such a row as redacted content (`RestoreRedactedMailContent`), which cannot be sent. `unknown` keeps its body while it waits for review or a retry, because the worker may need to resend the stored content. The local command does not display or edit the body. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies. Privacy. Logs name a delivery only by `delivery_id`, its kind, and closed values (the outcome and the cancel reason); no address, token, link, subject, or body appears in a log line, an error, or a metric label, and the metric has no labels at all. `ServiceMailSender` builds the outgoing message from the stored content and never logs it; `OutgoingMail` and `Delivery` redact themselves. @@ -408,7 +408,7 @@ Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`resendfixture`, an `httptest` server speaking the part of the API the transport uses, reached through `resend.NewLoopbackSender`, which accepts only a loopback endpoint) against PostgreSQL; see [TESTING.md](TESTING.md). It is a test fixture only; production binds the real Resend transport with its fixed endpoint. -Open points. Automatic retry or escalation for `unknown` is not implemented. Sending product notifications, and the permission check they need, are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume. +Open points. Sending product notifications and the permission check they need are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume. ### Product policy versions @@ -536,7 +536,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, and confirmation, 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 and confirmation, 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. Login and sessions, 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 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. `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/`. @@ -646,7 +646,7 @@ The brief references Russian Federal Law 152-FZ. The system design calls for sep ### Identity storage -Identity storage is implemented in migration `backend/db/migrations/00002_create_identity_tables.sql`, the queries in `backend/db/queries/identity.sql`, the domain types, outbound ports, and the PostgreSQL adapter. The backend API implements registration, verification resend, and `ConfirmEmail`. The frontend registration and confirmation screens are placeholders; login and sessions are not implemented; see the [API contract](../../api/README.en.md#identity-sessions-cookie-and-csrf). +Identity storage is implemented in migration `backend/db/migrations/00002_create_identity_tables.sql`, the queries in `backend/db/queries/identity.sql`, the domain types, outbound ports, and the PostgreSQL adapter. The backend API implements registration, verification resend, `ConfirmEmail`, login, and basic current-session operations. The frontend registration and confirmation screens are placeholders; see the [API contract](../../api/README.en.md#identity-sessions-cookie-and-csrf). - `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case. - `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists allowed purposes, so password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. Migration 00014 adds `pending_password_hash`, `pending_scenario`, and `pending_onboarding_step`, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated. @@ -659,14 +659,14 @@ Decisions: - The database stores hashes, never passwords or raw tokens. A token carries 256 bits from crypto/rand, so an unsalted SHA-256 cannot be reversed by guessing and a lookup stays one index probe; passwords need the slow Argon2id KDF instead. `bytea` keeps the digest at half the size of hex text, with an exact length CHECK and no letter-case variants. `domain.SecretToken`, `domain.PasswordHash`, and `domain.EmailAddress` redact themselves in `fmt` (every verb) and `slog` output, so printing a `domain.User` shows neither the address nor the hash; explicit accessors return the real values. Unmapped PostgreSQL errors from the identity repositories keep only the SQLSTATE and the constraint name, because the message and detail can quote row values. - Enum-like columns are text with CHECK constraints rather than PostgreSQL enum types. A new scenario, step, or purpose replaces one constraint in a reversible migration; an enum value cannot be removed and cannot be used in the transaction that adds it. - Every stored time comes from the application clock that the caller passes, so deadlines and the checks against them use one clock. Repositories reject the zero time. -- There is no CSRF column. `GetCurrentSession` must return the session's CSRF token after a reload, which a stored hash cannot reproduce. Session authentication can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration. +- There is no CSRF column. `GetCurrentSession` returns the token after a reload: the server derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, so it needs no database storage. Comparison is constant-time; the session token itself is stored in the database only as a SHA-256 hash. What the ports guarantee: - `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version, and deletes the registration C1 of the earlier registrant (see [Consent ledger](#consent-ledger)). `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise. - `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose. - Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase maps that outcome to `verification_token_invalid`. -- `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` writes `last_seen_at` only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`. +- `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` coalesces writes with a cutoff equal to the smaller of one minute and half the idle timeout, so frequent requests do not rewrite the row and even the shortest supported idle timeout can be extended; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`. - `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, their mail deliveries, and their consent records with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, delivery, or consent row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade; the consent records, which restrict the delete, are deleted explicitly in the same statement. - `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection. - Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text. @@ -674,17 +674,25 @@ What the ports guarantee: ### Password hashing -Implemented and tested: registration creates the hasher from configuration and calls it; login will do the same. +Implemented and tested: registration and login use the hasher created from configuration. - `domain.Password` holds the password normalized to Unicode NFKC. `domain.NewPassword` applies the registration policy, 15 to 128 code points after normalization; `domain.ParseLoginPassword` accepts 1 to 128. Before normalizing, both reject raw input over 512 bytes (128 code points of at most 4 UTF-8 bytes, so every value the contract schema accepts fits) and invalid UTF-8. These checks run before any hashing and fail with `domain.ErrInvalidPassword`, naming the rule but never the value. The blocklist of common or breached passwords is a separate planned check. - The `outbound.PasswordHasher` port (`port/outbound/password.go`) has `Hash`, `Verify`, and `VerifyDummy`; the `adapter/secondary/argon2id` adapter implements it with `golang.org/x/crypto/argon2`. New hashes use Argon2id v19 with m=65536 KiB, t=3, p=4 (the second recommended option of RFC 9106, above the OWASP baseline of 19 MiB, t=2, p=1), a 16-byte salt from crypto/rand, and a 32-byte key, encoded as `$argon2id$v=19$m=65536,t=3,p=4$$` in unpadded base64, the format that `domain.NewPasswordHash` and the `users_password_hash_format` CHECK accept. One hash took about 26 to 33 ms on an Apple M5 development machine (`BenchmarkHashRecommendedParameters`, also with one CPU); this is not a production latency figure. -- Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; request rate limiting comes with the HTTP operations. -- `Verify` parses the stored PHC string strictly and recomputes the key with the stored parameters, salt, and key length, then compares in constant time. A wrong password returns `outbound.ErrPasswordMismatch`. A malformed hash, or one outside the stored-hash bounds (memory from 8 KiB per lane to 128 MiB and within the hashing budget, 1 to 16 passes, 1 to 16 lanes, a salt of 8 to 64 bytes, a digest of 16 to 64 bytes), returns `outbound.ErrPasswordHashCorrupt` without any derivation, so a crafted row cannot demand unbounded memory or time. `ErrPasswordHashCorrupt` wraps `domain.ErrInvalidPasswordHash`, which the repository returns for a stored hash that fails `domain.NewPasswordHash`. On a match `needsRehash` reports parameters, salt, or key length that differ from the current ones, so a login can store a new hash. -- `VerifyDummy` runs `Verify` against a hash with the current parameters, a random salt, and a random digest, and returns `ErrPasswordMismatch` (or the context error). Login will call it for an unknown email, so both branches parse, wait for memory, derive, and compare alike. -- Login must answer `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it must also log an error and call `VerifyDummy`. Remaining timing differences: a corrupt hash is refused without a derivation, which `VerifyDummy` compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it. +- Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; identity HTTP limits are described in the server-side sessions section. +- `Verify` parses the stored PHC string strictly and recomputes the key with the stored parameters, salt, and key length, then compares in constant time. A wrong password returns `outbound.ErrPasswordMismatch`. A malformed hash, or one outside the stored-hash bounds (memory from 8 KiB per lane to 128 MiB and within the hashing budget, 1 to 16 passes, 1 to 16 lanes, a salt of 8 to 64 bytes, a digest of 16 to 64 bytes), returns `outbound.ErrPasswordHashCorrupt` without any derivation, so a crafted row cannot demand unbounded memory or time. `ErrPasswordHashCorrupt` wraps `domain.ErrInvalidPasswordHash`, which the repository returns for a stored hash that fails `domain.NewPasswordHash`. On a match `needsRehash` reports parameters, salt, or key length that differ from the current ones; login does not yet update such hashes automatically. +- `VerifyDummy` runs `Verify` against a hash with the current parameters, a random salt, and a random digest, and returns `ErrPasswordMismatch` (or the context error). Login calls it for an unknown email and an invalid stored hash, so those branches also perform a full Argon2id verification. +- Login answers `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it also logs an error and calls `VerifyDummy`. A valid password for an unverified account answers `email_not_verified` and creates no session. Verification time is not uniform: unknown emails and corrupt hashes run `VerifyDummy`, while stored hashes with different Argon2id parameters take different amounts of time. - `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration calls it on every branch before looking up the email. - Errors and logs never contain the password or the hash. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken`, and `domain.EmailAddress` redact themselves in `fmt`, `slog`, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address. +### 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. + +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. + +`IDENTITY_KEY_SECRET` must contain at least 32 bytes and stay the same across backend restarts and instances. It also derives the CSRF key with the purpose label `lincodex/identity/session-csrf/v1`; changing the shared secret invalidates old CSRF values but does not revoke PostgreSQL sessions, and `GetCurrentSession` returns the new value. After a successful password check, creation of a new session and revocation of an incoming active session commit in one transaction. A failed login does not revoke the old session. Logout clears an expired or revoked cookie; an Origin or CSRF failure neither revokes nor clears a valid session. + ### Consent ledger Consent storage, ports, the read contract, and grants through `consent.Service` are implemented: migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Registration records C1 through `GrantAtRegistration` in the account creation or re-registration transaction; confirmation checks the C1 record for the same registration version as the token. HTTP consent grants and revocation, revocation effects, and C4 at invitation acceptance are not implemented. @@ -734,21 +742,21 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo ### Registration, email verification, and resend -Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/identity.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`. +Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/auth.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`. One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account. Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns `pending_*` of `email_tokens`, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the `users` row: `UserRepository.AdvanceRegistration` only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The `password_hash`, `scenario`, and `onboarding_step` of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on `domain.User`). Invalidating a token (`InvalidateActive`) clears its `pending_*` columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing. -Email confirmation (`ConfirmEmail`) is implemented. It requires the password saved with that token's registration and checks it against the pending hash. In one transaction the backend checks the current registration version and its C1 record, consumes the token, verifies the address, applies the token's password hash, scenario, and onboarding step to the account, clears `pending_*`, and records exactly one secret-free `identity.email_verified` event. Any refusal leaves the account and token unchanged. Unknown, used, replaced, or superseded tokens, a wrong password, and missing pending credentials answer `verification_token_invalid`; an expired token answers `verification_token_expired`. The Origin must match exactly `APP_PUBLIC_URL`. Confirmation does not create a session. The frontend confirmation screen is still a placeholder; login and session recovery are not implemented. +Email confirmation (`ConfirmEmail`) is implemented. It requires the password saved with that token's registration and checks it against the pending hash. In one transaction the backend checks the current registration version and its C1 record, consumes the token, verifies the address, applies the token's password hash, scenario, and onboarding step to the account, clears `pending_*`, and records exactly one secret-free `identity.email_verified` event. Any refusal leaves the account and token unchanged. Unknown, used, replaced, or superseded tokens, a wrong password, and missing pending credentials answer `verification_token_invalid`; an expired token answers `verification_token_expired`. The Origin must match exactly `APP_PUBLIC_URL`. Confirmation does not create a session. The frontend confirmation screen is still a placeholder. -Planned login behavior: an unverified account will not be able to sign in. Login will answer as for a wrong password (or `email_not_verified` only where the contract allows it) without comparing the password with the row of an unverified account or with pending credentials. +Login accepts only a verified email and checks the account's stored password, never pending registration credentials. An unknown address, wrong password, and invalid stored hash receive the same `invalid_credentials`; unknown addresses and invalid hashes also run `VerifyDummy`, and an invalid stored hash is logged without the email or hash. A correct password for an unverified account answers `email_not_verified` and creates no session. Successful login creates a new session; if the request carried a valid session cookie, the backend revokes it and creates the new session in one transaction. Failed login does not revoke an existing session, and a malformed cookie cannot become a principal. Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit. Idempotency. The key is scoped by `HMAC(secret, operation | key | normalized email)` and the request is fingerprinted by `HMAC(secret, canonical body)` (`identity.Keyring`, secret `IDENTITY_KEY_SECRET`; required; a development stand may set `IDENTITY_ALLOW_EPHEMERAL_KEY=true` to draw a random one per process, which loses records and counters on restart). The record lives in `idempotency_records` (migration 00014) for 24 hours and is written in the registration transaction, so a visible record always belongs to a committed registration. A retry with the same key and body replays the neutral 202 and consumes no limit; the same key with another body answers 422 `idempotency_key_reused`. A concurrent identical request waits on the row of the first and is then replayed, so this implementation never answers 409 `idempotency_in_progress`. Each registration purges up to 10 expired records, which keeps the table bounded without a job. -Rate limits (Redis, fixed windows, `outbound.RateLimiter`, `redis.Cache.Take`, one atomic Lua script per take). The counters are keyed by the HMAC of the normalized address and count every request whether or not an account exists, so a 429 reveals nothing about the account. Registration and every resend share the per-address counters: at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between two messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per window of 24 hours that starts with the first. Confirmation allows five attempts per token per hour. A per-client counter, `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour), is keyed by `middleware.LimiterKey` of `ClientAddr`, hashed with the secret, and is skipped when the address is unknown (a shared bucket would let one client lock out everyone). A rejected `Take` does not increase its own counter; if an earlier limit check passed, its counter already records the attempt even when the next check refuses it. A refusal answers 429 `rate_limited` with `Retry-After` in whole seconds rounded up and issues no token. Counters are ephemeral: a Redis restart resets them, and the mail provider quota remains the last bound. A Redis failure answers 500 and never lets the request through. Neither address nor token is logged. +Rate limits (Redis, fixed windows, `outbound.RateLimiter`, `redis.Cache.Take`, one atomic Lua script per take). The counters are keyed by the HMAC of the normalized address and count every request whether or not an account exists, so a 429 reveals nothing about the account. Registration and every resend share the per-address counters: at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between two messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per window of 24 hours that starts with the first. Confirmation allows five attempts per token per hour. A per-client counter, `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour), applies to registration, confirmation, resend, and login; it is keyed by `middleware.LimiterKey` of `ClientAddr`, hashed with the secret, and is skipped when the address is unknown (a shared bucket would let one client lock out everyone). Login also uses `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour) for normalized email, whether or not an account exists. Both configurable identity limits accept values from 1 to 10000. A rejected `Take` does not increase its own counter; if an earlier limit check passed, its counter already records the attempt even when the next check refuses it. A refusal answers 429 `rate_limited` with `Retry-After` in whole seconds rounded up. Counters are ephemeral: a Redis restart resets them, and the mail provider quota remains the last bound. A Redis failure answers 500 and never lets the request through. Neither address nor token is logged. Token replacement policy. Every issue of a verification token (registration, re-registration, resend) first invalidates all unused verification tokens of the account and then stores the new one, so at most one link works at a time. A resend keeps the password, the scenario, the consent record, and the registration version; only the token changes. The message of an invalidated token is cancelled by the sending worker, so only the current link is delivered. The token lifetime comes from the product policy (`identity.verification_token_lifetime_hours`, 24 in the demo version), not from configuration. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 54bb032..82162f8 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -70,9 +70,9 @@ The Compose health check runs `kafka-broker-api-versions.sh` against `localhost: The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The outbox relay connects to these brokers in the background: the backend does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue. -`PASSWORD_HASH_CONCURRENCY` sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from `.env`, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets `GOMEMLIMIT=600MiB`, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login will use it once they are implemented. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing). +`PASSWORD_HASH_CONCURRENCY` sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from `.env`, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets `GOMEMLIMIT=600MiB`, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login use it. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing). -`IDENTITY_KEY_SECRET` is required in the production `.env` (at least 32 bytes; generate it with `openssl rand -base64 48` and keep it between restarts and across instances). It keys the registration idempotency records and the rate limit counters; Compose refuses to start without it, and the backend refuses to start without it unless `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, which is for development stands only. Changing it forgets the idempotency records and counters of the last 24 hours. `VERIFICATION_MAIL_MIN_INTERVAL` (default `1m`), `VERIFICATION_MAIL_DAILY_LIMIT` (default `5`), and `IDENTITY_CLIENT_HOURLY_LIMIT` (default `30`) bound verification mail per address and requests per client; an empty value means the default. Confirmation is also limited to 5 attempts per token per hour. The metric `lincodex_identity_rate_limit_refusals_total{scope}` counts refusals; a large share of `scope="client"` hints at a broken proxy chain (see `TRUSTED_PROXY_CIDRS`). See [ARCHITECTURE.md](ARCHITECTURE.md#registration-email-verification-and-resend). +`IDENTITY_KEY_SECRET` is required in the production `.env` (at least 32 bytes; generate it with `openssl rand -base64 48` and keep it between restarts and across instances). It keys idempotency records and rate limits, and derives the session CSRF key; Compose refuses to start without it, and the backend refuses to start without it unless `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, which is for development stands only. Changing it changes the lookup keys for the last 24 hours of counters and idempotency records and invalidates existing CSRF values, but it does not revoke sessions stored in PostgreSQL. `VERIFICATION_MAIL_MIN_INTERVAL` (default `1m`) and `VERIFICATION_MAIL_DAILY_LIMIT` (default `5`) bound verification mail per address; an empty value means the default. `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to `30` and accepts `1` to `10000`; it limits registration, confirmation, resend, and login attempts per client address when that address is resolved through the trusted proxy chain. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to `10` and accepts `1` to `10000`; it limits login attempts per normalized email whether or not an account exists. Confirmation is also limited to 5 attempts per token per hour. `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 must not exceed the absolute lifetime; invalid values stop backend startup. The metric `lincodex_identity_rate_limit_refusals_total{scope}` counts refusals; a large share of `scope="client"` hints at a broken proxy chain (see `TRUSTED_PROXY_CIDRS`). See [ARCHITECTURE.md](ARCHITECTURE.md#registration-email-verification-and-resend) and [server-side sessions](ARCHITECTURE.md#server-side-sessions). down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. @@ -237,7 +237,7 @@ Current state: this build contains the `disabled` and `resend` transports. With Release compatibility: `ConfirmEmail` requires both `token` and the password selected for that registration. Clients that send only the token must be updated. Migration `00016_bind_registration_consent.sql` adds the registration version to C1 and backfills legacy records from the current account version without requiring a live token. It checks that a registration C1 is not older than the latest registration and that an account has at most one active registration C1; on inconsistency, the migration stops without partial changes. A trigger fills the version when an old backend omits it and rejects a mismatched version sent by the new backend. A partial unique index allows at most one unrevoked registration C1 per account and registration version. Apply the migration before updating the backend. To roll back, deploy the old backend before reverting the migration. No new environment variable is needed. `APP_PUBLIC_URL` also defines the Origin that confirmation requests must send. -`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, and outcome records belong to the planned delivery layer, and the wait for a daily or monthly quota reset is decided by the quota gate (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). +`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; the sending worker owns retries, backoff, rate-limit pacing, and outcome records, while the quota gate schedules a known daily or monthly reset (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). `disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning. @@ -260,7 +260,7 @@ Compose passes these variables from the root `.env`; it passes an unset `EMAIL_Q ### Mail deliveries -A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until product notification sending is implemented. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line. +A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; migration 00017 adds the unknown-outcome decision journal and rebuilds the due partial index under a table lock. Rolling 00017 back drops that journal and its audit history, so export the decisions before rollback. Neither migration needs a setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until product notification sending is implemented. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line. - Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand. - The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet. @@ -280,7 +280,7 @@ Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quo - The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up. - Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused. - `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan. -- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy. +- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. The local operator command is for terminal unknown outcomes, not quota-waiting deliveries. - Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching `EMAIL_PROVIDER` to `smtp` starts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit. ### Sending service mail @@ -290,11 +290,11 @@ The backend process runs one sending loop for service identity mail (email verif - Several backend instances may run at once. Each claims a delivery with `FOR UPDATE SKIP LOCKED` and a lease, so one delivery is sent by one instance, and the provider call carries the stable idempotency key `delivery/`. During a rolling deployment the instance that stops finishes its send within 5 seconds, stores the result, and exits. - With `EMAIL_PROVIDER=disabled` the loop does not start and the log says `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` is 0, nothing is sent, and stored service mail waits for the next start with a transport. The worker never spins: after a pass that could not send it backs off. - Before it sends, the worker checks the token and the account. A delivery that must not go out ends as `cancelled` with a `cancel_reason`, no attempt, and no quota use: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. The user-caused reasons are normal: a user asked for a new link, confirmed the address, registered again, or waited too long. To see the reasons: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. A user sees a cancelled mail as "not sent, request a new one". -- Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A refusal for now (`temporary`, `rate_limited`) leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the same key and body; it repeats until it succeeds, is refused for good, or the token expires and the delivery is cancelled. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas). -- `unknown` is never retried by the worker. It means that the provider may have accepted the mail (a lost answer, a 5xx answer) or that the worker that sent it was lost for longer than the provider's 24-hour idempotency window. Check the provider's own log for the message; the alert `LincodexMailDeliveryUnknownOutcome` fires meanwhile. A manual retry with an audit record is planned with the retry policy. +- Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A confirmed temporary or 429 refusal means the provider did not accept the message: it leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the pinned account, key, and body. Resend's `Retry-After` is a lower bound. Such a refusal does not erase uncertainty from an earlier unknown attempt. After the 23-hour cutoff, confirmed refusals continue only under a pending manual decision; without it, the worker stops and leaves the earlier unknown for operator review. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas). +- An uncertain Resend outcome is retried automatically with the same pinned account, key, and stored body only until 23 hours after the database-recorded first send, one hour before the provider's documented 24-hour idempotency expiry. The worker checks this cutoff again immediately before the network call. After the cutoff, or after a manually authorized send-start whose result is lost, automatic retries stop and the alert `LincodexMailDeliveryUnknownOutcome` asks for review. Check the provider's own log first. For a terminal `unknown` row, use `make -C backend mail-retry ARGS='inspect --delivery '` to see metadata and the duplicate warning, then `make -C backend mail-retry ARGS='retry --delivery --actor operator: --acknowledge-duplicate-risk'` to schedule one audited decision. The command requires the local database credential, is available only with `EMAIL_PROVIDER=resend`, prints its warning before changing state, and never sends mail. The actor is an audit handle rather than authentication, and there is no HTTP operator endpoint. A manual decision does not restart the provider's key window: after another unknown or lost manual send result, the worker stops and requires another decision. An expired idempotency key may produce a duplicate despite the warning. - A claimed delivery holds a lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. A row whose `claimed_until` is long past means that its worker died; another instance takes it over by itself. Do not clear leases by hand. - `content_invalid` and `processing_failed` are not user actions: the first means that a stored row does not match its content hash (a manual edit) or holds a message no transport accepts, the second that the worker failed on the row three times in a row (the retries are spaced by the retry schedule). The alert `LincodexMailCancelledBroken` fires on an increase; read the worker logs for the `delivery_id` and inspect the row's metadata. A row that keeps failing does not block the others: it is retried later (`failure_count`, `next_attempt_at`) and then cancelled. -- The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. Do not copy bodies of waiting mail anywhere. +- The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. The retry command displays no address, body, key, or token. Do not copy bodies of waiting mail anywhere. - The lease is measured by the database clock, so clock differences between instances do not matter; only the database's clock does. The call to the provider is bounded by what is left of the lease; with `SHUTDOWN_TIMEOUT` at its default of 10 seconds a stopping instance finishes within 3 seconds of grace plus 5 seconds to store the answer. Lowering `SHUTDOWN_TIMEOUT` shortens the second part (at least 1 second); a result that cannot be stored in time is covered by the takeover. - Logs name a delivery only by `delivery_id`, its kind, and the outcome or cancel reason, for example `service mail was not sent because it is no longer valid`; never an address, a token, a link, or a body. If a token or link appears in a log, treat it as a defect. - The internal /metrics endpoint shows `lincodex_mail_sender_running` (1 while this instance's loop runs, 0 otherwise; no labels) and `lincodex_mail_sender_cancelled_total{reason}` (a counter per cancel reason, zero included) next to the delivery gauges, which also have the status `cancelled`. @@ -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 planned session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict`. Browsers accept it only from an HTTPS page, with `Path=/` and no `Domain`, which the single HTTPS origin gives. 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://`, which is the only origin value the backend reads. +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. -Registration, verification resend, and email confirmation are available through the API, but login is not implemented. Frontend registration and confirmation screens remain placeholders, and the backend does not read `X-Forwarded-Proto`. The browser confirmation and sign-in paths through the edge are not verified end to end; the cookie transport is checked (HTTPS, one origin, and the forwarded original host and scheme). +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. ### Request handling at the edge @@ -488,7 +488,7 @@ Ubuntu's `certbot.timer` runs `certbot renew` twice a day and renews a certifica systemctl list-timers certbot.timer sudo certbot certificates -A reload starts new workers with the new certificate and configuration and lets the old workers finish their open connections, so in-flight requests and keep-alive connections are not dropped. Sessions are not held by nginx at all: the planned design keeps them in PostgreSQL behind an opaque cookie, so reloading or restarting nginx or the tunnel does not sign anyone out. Because sign-in is not implemented yet, the available proof is a request in flight and a kept connection across `systemctl reload nginx`: both complete without a 5xx, and the next request on the same connection succeeds. +A reload starts new workers with the new certificate and configuration and lets the old workers finish their open connections, so in-flight requests and keep-alive connections are not dropped. The backend stores session state in PostgreSQL, not nginx: reloading or restarting nginx or the tunnel does not revoke a session while the backend and database remain available. The check below verifies only an in-flight request and keep-alive behavior across `systemctl reload nginx`; browser sign-in persistence after reload has not been verified end to end. ### Verification diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index ec348ff..2d80686 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -6,7 +6,7 @@ Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту. -Регистрация и подтверждение email работают через API backend. Экраны регистрации и подтверждения во frontend остаются заглушками; вход и остальные перечисленные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. +Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Экраны регистрации и подтверждения во frontend остаются заглушками; остальные перечисленные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий. Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md). @@ -202,11 +202,11 @@ Offsets и партиции. Каждый обработчик - один уча - `accepted`: провайдер принял запрос и вернул `ProviderMessageID`. Это не доставка и не прочтение. - `rejected`: провайдер не принял письмо. Либо он ответил отказом, либо транспорт сломался до полной записи запроса (DNS, соединение или TLS), и полный запрос до провайдера не дошел; второй случай всегда `temporary`, и повтор не может продублировать письмо. `Rejection` равен `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted` или `temporary`. -- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`), например таймаут, обрыв соединения после записи запроса или ошибка провайдера во время обработки. Это не «не отправлено»: повтор использует тот же ключ идемпотентности и то же содержимое. Дедупликация у провайдера ограничена окном (24 часа у Resend); после него повтор может отправить письмо дважды, поэтому слой доставки обязан прекратить повторы и передать случай оператору. +- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`), например таймаут, обрыв соединения после записи запроса или ошибка провайдера во время обработки. Это не «не отправлено»: повтор использует тот же ключ идемпотентности и то же содержимое. Resend хранит ключ идемпотентности 24 часа. Worker прекращает автоматические повторы через 23 часа, оставляя часовой запас; после этого оператор решает, запускать ли повтор, поскольку старый ключ может уже не защитить от дубля. `rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Отказ `quota_exhausted` еще и называет исчерпанное окно в `QuotaPeriod` (`day` или `month`), если провайдер это сообщил; иначе поле пустое. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить. -Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. +Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Транспорт делает один запрос; worker доставки отвечает за повторы, задержки и запись исходов. Сценарии подтверждения обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера. Транспорт Resend использует `net/http` без SDK. Один `Send` - это один `POST https://api.resend.com/emails` с полями `from` (`EMAIL_FROM`), `to` (один получатель), `subject`, `text` и `html` (пустая или пробельная часть не передается), ключом в `Authorization: Bearer`, заголовком `User-Agent` и `Idempotency-Key`, равным ключу письма. Resend хранит ключ 24 часа и на тот же ключ с тем же телом возвращает исходный результат без повторной отправки, поэтому повтор обязан передать сохраненное тело под тем же ключом; измененное тело под старым ключом - это конфликт, а не повод создать новый ключ. `EMAIL_TIMEOUT` ограничивает всю попытку. Клиент не следует редиректам, использует HTTP/1.1 и открывает новое соединение для каждой отправки: keep-alive соединение, которое сервер закрыл по простою, сломалось бы уже после передачи запроса и превратило бы письмо, которого Resend не видел, в ложный `unknown`. У запроса также нет `GetBody`, потому что `net/http` считает POST с `Idempotency-Key` повторяемым после обрыва переиспользованного соединения. В адаптере нет цикла повторов, и он ничего не логирует. Ответ читается не больше 64 KiB; разбираются только идентификатор письма и `name` ошибки, а сообщение провайдера и тело ответа не сохраняются. @@ -234,7 +234,7 @@ Offsets и партиции. Каждый обработчик - один уча ### Доставки писем -Реализовано: агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован; см. [Квоты почты](#квоты-почты). Реализовано: worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода и отправка продуктовых уведомлений с проверкой разрешений перед отправкой. Gauges состояний доставки реализованы; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Продуктовые сценарии пока не вызывают `MailRequester`, поэтому запросы уведомлений ждут отправки. Регистрация и повторная отправка создают письма подтверждения через `ServiceMailer`; сброс пароля не реализован. +Реализовано: агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован; см. [Квоты почты](#квоты-почты). Реализовано: worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Реализованы повторы служебной почты и политика неизвестного исхода, включая локальную команду оператора. Отправка продуктовых уведомлений с проверкой разрешений перед отправкой не реализована. Gauges состояний доставки реализованы; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Продуктовые сценарии пока не вызывают `MailRequester`, поэтому запросы уведомлений ждут отправки. Регистрация и повторная отправка создают письма подтверждения через `ServiceMailer`; сброс пароля не реализован. Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит: @@ -243,7 +243,7 @@ Offsets и партиции. Каждый обработчик - один уча - Получателя: `recipient_user_id`, внешний ключ на `users` с `ON DELETE CASCADE`, и `recipient_email`, форма адреса аккаунта для доставки на момент создания. - Содержимое: `kind` (`verification`, `password_reset` или `notification`), `template_version` (`.v`), `subject`, `text_body`, `html_body` и `content_sha256` по версии, теме и обеим частям - тот же digest, что у шаблонов писем (`domain.MailContentHash`). - Аккаунт провайдера: `provider` и `provider_account`, значения `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` на момент создания. Это идентичность конфигурации, а не секрет. -- Состояние попыток: `status`, `attempt_count`, `next_attempt_at`, `last_attempt_at`, `provider_message_id`, оптимистичная `version`, `created_at` и `updated_at`; все время берется из часов приложения. +- Состояние попыток: `status`, `attempt_count`, `next_attempt_at`, `last_attempt_at`, `provider_message_id`, оптимистичная `version`, `created_at` и `updated_at`. Время создания, изменения и следующей попытки берется из часов приложения; начало первого запроса и lease - из часов базы. Путь создания: @@ -272,7 +272,7 @@ Offsets и партиции. Каждый обработчик - один уча | `pending` | Ждет первую попытку или повтор после отказа `temporary` или `rate_limited` | Обязательно: когда доставка должна быть отправлена | | `accepted` | Провайдер принял письмо и вернул `provider_message_id`: "принято провайдером". Это не доставка человеку и не прочтение; ни один статус этого не утверждает | Нет; конечный | | `rejected` | Отказ `permanent` или `invalid_request`; причину нужно устранить | Нет; конечный | -| `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Это никогда не "не отправлено": повтор использует тот же ключ и сохраненное тело | Необязательно; отсутствие значит, что автоматического повтора нет | +| `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Повтор использует закрепленные аккаунт, ключ и тело | Необязательно; без срока требуется решение оператора | | `cancelled` | Письмо намеренно не отправлено и не будет: токен или аккаунт перестали соответствовать доставке, или сохраненное письмо нельзя отправить. `cancel_reason` говорит почему; попытка не записывается | Нет; конечный | | `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс (см. [Квоты почты](#квоты-почты)); отсутствует, когда момент сброса неизвестен, например после ответа провайдера о квоте без окна и без паузы, и решение принимает оператор | @@ -285,7 +285,7 @@ Offsets и партиции. Каждый обработчик - один уча Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода, и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`. -Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. История нужна оператору, чтобы оценить неизвестный исход, от нее (от первой попытки) отсчитывается конец 24-часового окна ключа, и на нее ссылается аудит ручного решения. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки. +Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. Возраст для 23-часового автоматического cutoff отсчитывается от `first_send_started_at`, который БД записывает при первом начале запроса. Если ручной вызов начался, но его lease истек до записи ответа, восстановление добавляет `unknown` попытку до планирования нового решения; время этой записи не раньше прошлого изменения доставки. Решения хранятся в `delivery_retry_decisions`: ID доставки, номер попытки, handle оператора, явное подтверждение риска дубля, факт истекшего lease и время решения. В журнале нет внешнего ключа, поэтому удаление аккаунта не удаляет аудит; триггеры запрещают UPDATE, DELETE и TRUNCATE. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки. Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `delivery_attempts` потерял бы отправки удаленных аккаунтов и позволил бы превысить квоту провайдера. Поэтому у квоты собственный счетчик без каскада с ключом из провайдера, аккаунта провайдера и UTC-суток или месяца; см. [Квоты почты](#квоты-почты). @@ -293,7 +293,7 @@ Offsets и партиции. Каждый обработчик - один уча Миграция `00012_add_delivery_sending.sql` аддитивна; существующие строки остаются корректными. Она добавляет в `deliveries`: `email_token_id` (необязательный внешний ключ на `email_tokens.id` для писем с токеном, неизменяемый, как остальное содержимое; NULL для уведомлений), `cancel_reason` (задан ровно когда статус `cancelled`, CHECK ограничивает его перечисленными причинами), столбцы lease `claim_owner` и `claimed_until` (оба или ни одного; lease держит только доставка, которую worker еще может отправить), `first_send_started_at` (когда начался первый запрос, по часам базы), `failure_count` (подряд идущие сбои worker на строке), `body_redacted_at` (тела письма с токеном очищены), статус `cancelled` с его CHECK и два частичных индекса: `deliveries_due_idx` по `(next_attempt_at, id)`, чей предикат называет служебные виды и статусы, которые берутся снова, поэтому строки уведомлений в него не попадают, а холостой опрос их не сканирует, и индекс по `email_token_id`. Trigger `deliveries_refuse_content_change` разрешает еще ровно одно изменение тел: у конечного письма с токеном оба тела один раз становятся пустыми вместе с `body_redacted_at`. В `email_tokens` добавляется назначение токена `password_reset`. Откат миграции превращает отмененные доставки в отклоненные и удаляет токены сброса. Запланировано: отмена доставки по отозванному разрешению. -Хранилище дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota`, `Cancel` и `Rebind`, а для worker отправки - `ClaimDue`, `ReleaseClaim` и `ServiceMailState`. +Хранилище дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota`, `Cancel` и `Rebind`, а для worker отправки - `ClaimDue`, `ReleaseClaim` и `ServiceMailState`. Миграция `00017_retry_unknown_mail.sql` добавляет маркеры ручного цикла, неизменяемый журнал решений и `unknown` в предикат индекса очереди. Она перестраивает частичный индекс очереди и берет блокировку таблицы на время перестройки. Откат удаляет журнал решений вместе с данными аудита; перед намеренным откатом сохраните экспорт. ### Квоты почты @@ -352,8 +352,8 @@ Offsets и партиции. Каждый обработчик - один уча Один проход `ServiceMailSender.ProcessNext` проводит одну доставку через три шага: -1. Транзакция захвата. `DeliveryRepository.ClaimDue` берет самую просроченную доставку с `FOR UPDATE SKIP LOCKED`: вид `verification` или `password_reset` (литералы совпадают с предикатом `deliveries_due_idx`, поэтому опрос читает только этот малый индекс), статус `pending` или `waiting_quota`, `next_attempt_at` наступил, доставка закреплена за настроенным аккаунтом провайдера и ее не держит живой lease. Он записывает `claim_owner` и `claimed_until` (lease), не меняя версию и время обновления, поэтому несколько процессов никогда не возьмут одну доставку. Lease измеряется часами базы данных (`clock_timestamp()` плюс длина lease, и он жив, пока `claimed_until` позже `clock_timestamp()`), а не часами экземпляра приложения, поэтому экземпляры с разными часами не могут перехватить живой lease или держать мертвый; сроки доставок остаются на часах приложения, которые их записали. У доставки в `unknown` или в `waiting_quota` без времени нет срока, и она ждет оператора. В той же транзакции отправитель переносит на настроенный аккаунт письма, сохраненные при `EMAIL_PROVIDER=disabled` (это разрешено только до первой попытки, пока ключ не видел ни один провайдер), выполняет проверку ниже, а затем `QuotaGate.PrepareSend`, который резервирует получателя или переводит доставку в `waiting_quota`. Транзакция фиксируется до вызова транспорта, поэтому медленный провайдер никогда не держит блокировку строки. Сбой внутри нее (детерминированный, например строка, которую нельзя восстановить) откатывает и lease, поэтому сбой записывается для строки отдельной транзакцией; см. "Сбойные строки". -2. Проверка прямо перед отправкой, одна короткая транзакция: она блокирует строку доставки (только для владельца lease), заново читает токен и аккаунт через `ServiceMailState`, поэтому отзыв после фиксации захвата учитывается, и в первый раз записывает `first_send_started_at`. Письмо, которое больше нельзя отправлять, отменяется, а резервирование возвращается. Затем один вызов `MailSender.Send` с сохраненным содержимым и стабильным ключом идемпотентности `delivery/`. Отправитель никогда не повторяет вызов. Вызов ограничен тем, что осталось от lease после захвата и бюджета расчета, и льготным периодом остановки. +1. Транзакция захвата. `DeliveryRepository.ClaimDue` берет самую просроченную доставку с `FOR UPDATE SKIP LOCKED`: вид `verification` или `password_reset` (литералы совпадают с предикатом `deliveries_due_idx`, поэтому опрос читает только этот малый индекс), статус `pending`, `waiting_quota` или запланированный `unknown`, наступивший `next_attempt_at`, доставка закреплена за настроенным аккаунтом провайдера и ее не держит живой lease. Неопределенный исход автоматически ставится на повтор только до cutoff; `unknown` без срока ждет оператора. Однократное разрешение оператора тоже ставит `unknown` в очередь. Захват записывает `claim_owner` и `claimed_until` (lease), не меняя версию и время обновления, поэтому несколько процессов не возьмут одну доставку. Lease измеряется часами базы данных (`clock_timestamp()` плюс длина lease, и он жив, пока `claimed_until` позже `clock_timestamp()`), а не часами экземпляра приложения; сроки доставок остаются на часах приложения, которые их записали. В той же транзакции отправитель переносит на настроенный аккаунт письма, сохраненные при `EMAIL_PROVIDER=disabled` (это разрешено только до первой попытки, пока ключ не видел ни один провайдер), выполняет проверку ниже, а затем `QuotaGate.PrepareSend`, который резервирует получателя или переводит доставку в `waiting_quota`. Транзакция фиксируется до вызова транспорта, поэтому медленный провайдер никогда не держит блокировку строки. Сбой внутри нее (детерминированный, например строка, которую нельзя восстановить) откатывает и lease, поэтому сбой записывается для строки отдельной транзакцией; см. "Сбойные строки". +2. Проверка прямо перед отправкой, одна короткая транзакция: она блокирует строку доставки (только для владельца lease), заново читает токен и аккаунт через `ServiceMailState`, поэтому отзыв после фиксации захвата учитывается, и записывает начало запроса по часам базы. Для неопределенного результата cutoff 23 часа повторно проверяется после квоты и захвата lease, прямо перед сетевым вызовом. Однократное разрешение оператора расходуется при записи send-start. Письмо, которое больше нельзя отправлять, отменяется, а резервирование возвращается. Затем один вызов `MailSender.Send` с сохраненным содержимым и стабильным ключом идемпотентности `delivery/`. Транспорт не повторяет вызов. Вызов ограничен тем, что осталось от lease после захвата и бюджета расчета, и льготным периодом остановки. 3. Транзакция расчета. Она сначала блокирует строку доставки (только пока этот worker держит lease), затем `QuotaGate.SettleSend` и `DeliveryRepository.RecordClaimedAttempt` фиксируются вместе, а lease заканчивается вместе с попыткой. `RecordClaimedAttempt` применяется только поверх версии доставки и только для владельца lease, поэтому worker, чей lease перехвачен, записать не может, а если два worker дошли до этого шага для одной доставки, сохраняется только первая; вторая откатывается вместе с расчетом квоты и сообщает `lease_lost`. Сбой базы при сохранении ответа повторяется до трех раз в пределах бюджета расчета, потому что ответ до сохранения существует только в памяти. Бюджет времени. Lease равен `EMAIL_TIMEOUT` плюс одна минута. Сначала идут захват и проверка; вызов получает остаток lease за вычетом бюджета расчета (20 секунд), поэтому захват, вызов и весь расчет умещаются в lease. Когда остановка началась, бюджет расчета - меньшее из 5 секунд и `SHUTDOWN_TIMEOUT` за вычетом 3 секунд льготного периода остановки (не меньше 1 секунды), поэтому процесс останавливается в пределах своего тайм-аута остановки, по умолчанию 10 секунд (период остановки в Compose - 30 секунд). Результат, который не удалось сохранить вовремя, покрывает перехват ниже. @@ -385,14 +385,14 @@ Offsets и партиции. Каждый обработчик - один уча | `rejected` `permanent` или `invalid_request` | `rejected` | нет | возвращается | | `rejected` `temporary` или `rate_limited` | `pending` | сейчас плюс `RetryPolicy`: 1 минута, удвоение до 30 минут, не меньше `Retry-After` провайдера | возвращается | | `rejected` `quota_exhausted` | `waiting_quota` | сброс, который вернул шлюз (ближайшие 00:00 UTC для суток, первое число следующего месяца для месяца); нет, если провайдер не назвал окно | окно отмечено заполненным | -| `unknown` | `unknown` | нет: автоматического повтора нет | считается | +| `unknown` | `unknown` | расписание повторов до cutoff 23 часа, затем без срока до решения оператора | считается | | Ошибка `Send`: нет транспорта (`ErrMailChannelUnavailable`) или context завершился | без изменений, lease освобожден | остается срок | возвращается | | Ошибка `Send`: неверное сообщение (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | нет | возвращается | | Ошибка `Send`: любая другая без ответа | не считается против строки; она отодвигается по `RetryPolicy`, а worker делает паузу | сейчас плюс `RetryPolicy` | возвращается | -В расписании повторов нет предела числа попыток намеренно: токен истекает, и тогда проверка отменяет доставку с `token_expired`. К каждой паузе добавляется ограниченный jitter, до пятой части сверх расписания, из подменяемого источника (в тестах nil, поэтому время точное), чтобы доставки, отклоненные вместе, не возвращались вместе. `unknown` никогда не читается как неотправленное и никогда не повторяется worker; решает оператор, и срабатывает alert `LincodexMailDeliveryUnknownOutcome`. +В расписании повторов нет предела числа попыток намеренно: токен истекает, и тогда проверка отменяет доставку с `token_expired`. К каждой паузе добавляется ограниченный jitter, до пятой части сверх расписания, из подменяемого источника (в тестах nil, поэтому время точное), чтобы доставки, отклоненные вместе, не возвращались вместе. `unknown` никогда не считается подтвержденным отказом. Подтвержденный отказ доказывает, что именно этот запрос провайдер не принял, но не снимает неопределенность от более ранней попытки `unknown`. Автоматические повторы с тем же закрепленным аккаунтом, ключом и телом заканчиваются через 23 часа от первого send-start; один час оставлен как запас до 24-часового срока Resend. Операторское решение требует handle, явного подтверждения риска дубля и записи в append-only audit. Worker выполняет его только при `EMAIL_PROVIDER=resend`. `make -C backend mail-retry ARGS='inspect --delivery '` показывает метаданные и предупреждение; `make -C backend mail-retry ARGS='retry --delivery --actor operator: --acknowledge-duplicate-risk'` сначала печатает предупреждение, затем атомарно записывает решение и ставит один ручной цикл в очередь, но сам не отправляет письмо. Для команды нет HTTP-интерфейса; доступ ограничен доступом к локальному процессу и учетным данным БД, а actor - только handle для аудита. Старый ключ может уже не дедуплицировать письмо, поэтому повтор способен создать дубль даже после подтверждения риска. После ручного `unknown` или потери lease после send-start автоматический повтора нет, нужна новая команда с подтверждением; подтвержденные временные и 429-отказы продолжают повторы под тем же решением. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока нужен разбор. -Worker потерян после вызова. Если worker остановился после вызова провайдера, но до сохранения ответа, его lease истекает, и другой worker берет доставку на той же попытке и повторяет запрос с тем же ключом идемпотентности. Resend отвечает на повторный ключ и тело исходным результатом, а шлюз квот повторно использует открытое резервирование, поэтому письмо существует одно и считается один раз. Провайдер хранит ключ 24 часа от первого запроса, поэтому возраст считается от `first_send_started_at` (его по часам базы записывает проверка прямо перед первым запросом), а не от последнего lease: сколько бы worker ни потерялось подряд и какой бы длины ни был lease, когда этот возраст достигает 23 часов (окно за вычетом часового запаса), прежний запрос может быть забыт, и повтор способен отправить письмо дважды, поэтому вместо этого доставка записывается как попытка `unknown` без следующей попытки. То же применяется сразу для транспорта без дедупликации на стороне провайдера (окно ноль, SMTP). Lease, не дошедший до первого запроса, ничего не оставляет под сомнением. +Потеря автоматического вызова. Если worker остановился после вызова провайдера, но до сохранения ответа, другой worker может взять ту же попытку и повторить запрос с тем же ключом, пока не наступил cutoff 23 часа. Потерянный результат после ручного send-start записывается как `unknown` и ждет нового решения; восстановление само не вызывает провайдера. Resend отвечает на повторный ключ и тело исходным результатом, а шлюз квот повторно использует открытое резервирование, поэтому письмо существует одно и считается один раз. Провайдер хранит ключ 24 часа от первого запроса, поэтому возраст считается от `first_send_started_at` (его по часам базы записывает проверка прямо перед первым запросом), а не от последнего lease: сколько бы worker ни потерялось подряд и какой бы длины ни был lease, когда этот возраст достигает 23 часов (окно за вычетом часового запаса), прежний запрос может быть забыт, и повтор способен отправить письмо дважды, поэтому вместо этого доставка записывается как попытка `unknown` без следующей попытки. То же применяется сразу для транспорта без дедупликации на стороне провайдера (окно ноль, SMTP). Lease, не дошедший до первого запроса, ничего не оставляет под сомнением. Сбойные строки. Сбой одной строки не должен занимать начало очереди. Когда транзакция захвата падает после того, как взяла строку, ее lease откатывается вместе с ней, и та же строка тут же была бы взята снова, а все доставки за ней ждали бы. Против строки считается только сбой, который вызывает сама строка: нарушаемое ею правило домена (`ErrInvalidDelivery`, `ErrDeliveryTransition`, неверное содержимое или адрес), строку нельзя восстановить по причине, отличной от несовпадения хеша, или отказ ограничения данных или целостности (классы SQLSTATE 22 и 23, `outbound.ErrRowFault`). Все остальное о строке ничего не говорит и никогда не считается: завершившийся context, тайм-аут, deadlock, потеря соединения (SQLSTATE 08, 40, 53, 57, XX), ошибка ввода-вывода, отсутствие настройки квоты. Такая ошибка возвращается worker, который делает паузу, как при любом глобальном сбое, а lease истекает или откатывается. Для считаемого сбоя отправитель записывает его короткой отдельной транзакцией (`RecordFailure`): `failure_count` растет, lease заканчивается, и строка снова должна быть отправлена по `RetryPolicy` (исход `row_failed`; следующий проход берет доставку за ней). Запрос не трогает строку, которую другой worker держит под живым lease, поэтому откатившийся захват не может помешать строке, которую кто-то только что взял. Счетчик означает сбои подряд: успешный захват и подготовка (проверка перед отправкой) его очищают, как и записанная попытка. Предохранитель в worker останавливает счет, когда сбои попадают на разные строки проход за проходом: три прохода подряд, упавших на трех разных строках, читаются как глобальный сбой, worker ждет с растущей паузой (проход `row_failed` никогда не крутится сразу), а сбои отодвигаются, но не считаются и ни одна строка не отменяется, пока проход не завершится успешно. После 3 считаемых сбоев подряд строка отменяется с причиной `processing_failed`: это существующий конечный статус, который подходит, оператор его видит, и срабатывает alert ниже, поэтому новый статус не понадобился. Если сбой базы мешает и этой записи, строка остается под своим lease, который истекает. @@ -400,7 +400,7 @@ Worker потерян после вызова. Если worker останови Цикл и остановка. `worker/mailsender` повторяет проходы: после прохода, обработавшего доставку, сразу идет следующий, после холостого прохода worker ждет 5 секунд, а после сбоя базы, отсутствия транспорта или прерванного вызова ждет с растущей паузой. Когда context завершается, worker больше ничего не захватывает, дает выполняющейся отправке продолжиться 5 секунд, сохраняет ее результат и возвращается; после этого gauge равен 0. Цикл - горутина процесса backend на собственном pool из двух соединений, как у других worker; больший объем дают дополнительные экземпляры, а каждый обрабатывает одну доставку за раз, что подходит для служебной почты при квоте Resend Free. -Токен в хранилище. Тело письма с токеном содержит одноразовый токен, а токен сброса - примитив захвата аккаунта для любого, кто может читать базу или резервную копию. Когда письмо с токеном достигает `accepted`, `rejected` или `cancelled` (любым путем: попыткой, отменой, отменой испорченной строки или `processing_failed`), тот же запрос делает `text_body` и `html_body` пустыми и ставит `body_redacted_at`; тема, хеш содержимого и версия шаблона остаются. Trigger разрешает ровно это изменение один раз для конечной строки и отклоняет любое другое изменение тел или метки; CHECK `deliveries_body_present` принимает пустое тело только с меткой; домен восстанавливает такую строку как очищенное содержимое (`RestoreRedactedMailContent`), которое отправить нельзя. `unknown` не конечный и сохраняет тело, потому что повтор отправляет его снова; оператор, который его разрешает, должен очистить его. Уведомления не очищаются. Откат миграции 00012 подставляет заглушку в очищенные тела. +Токен в хранилище. Тело письма с токеном содержит одноразовый токен, а токен сброса - примитив захвата аккаунта для любого, кто может читать базу или резервную копию. Когда письмо с токеном достигает `accepted`, `rejected` или `cancelled` (любым путем: попыткой, отменой, отменой испорченной строки или `processing_failed`), тот же запрос делает `text_body` и `html_body` пустыми и ставит `body_redacted_at`; тема, хеш содержимого и версия шаблона остаются. Trigger разрешает ровно это изменение один раз для конечной строки и отклоняет любое другое изменение тел или метки; CHECK `deliveries_body_present` принимает пустое тело только с меткой; домен восстанавливает такую строку как очищенное содержимое (`RestoreRedactedMailContent`), которое отправить нельзя. `unknown` сохраняет тело, пока ждет разбора или повтора, потому что worker может повторно отправить сохраненное содержимое. Локальная команда не показывает и не меняет тело. Уведомления не очищаются. Откат миграции 00012 подставляет заглушку в очищенные тела. Приватность. Журнал называет доставку только по `delivery_id`, ее виду и закрытым значениям (исход и причина отмены); адрес, токен, ссылка, тема и тело не попадают ни в строку журнала, ни в ошибку, ни в label метрики, а у метрики вообще нет labels. `ServiceMailSender` строит исходящее письмо из сохраненного содержимого и никогда его не логирует; `OutgoingMail` и `Delivery` скрывают себя сами. @@ -408,7 +408,7 @@ Worker потерян после вызова. Если worker останови Тесты. `integration_test/mail_sender_test.go` запускает локальную имитацию Resend (`resendfixture`, сервер `httptest`, который говорит на части API, используемой транспортом, и доступен через `resend.NewLoopbackSender`, принимающий только loopback endpoint) против PostgreSQL; см. [TESTING.md](TESTING.md). Это только тестовая подмена; production использует настоящий транспорт Resend с фиксированным endpoint. -Открытые вопросы. Автоматический повтор и эскалация для `unknown` пока не реализованы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема. +Открытые вопросы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема. ### Версии продуктовой политики @@ -536,7 +536,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, 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 сессии и проверку ограниченного набора операций сессии, 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/`. @@ -646,7 +646,7 @@ contact_grant относится к паре кандидат-компания ### Хранение identity -Хранение identity реализовано миграцией `backend/db/migrations/00002_create_identity_tables.sql`, запросами `backend/db/queries/identity.sql`, доменными типами, outbound-портами и адаптером Postgres. Backend API реализует регистрацию, повторную отправку подтверждения и `ConfirmEmail`. Экраны регистрации и подтверждения во frontend остаются заглушками; вход и сессии пока не реализованы; см. [контракт API](../../api/README.md#identity-сессии-cookie-и-csrf). +Хранение identity реализовано миграцией `backend/db/migrations/00002_create_identity_tables.sql`, запросами `backend/db/queries/identity.sql`, доменными типами, outbound-портами и адаптером Postgres. Backend API реализует регистрацию, повторную отправку подтверждения, `ConfirmEmail`, вход и базовые операции с текущей сессией. Экраны регистрации и подтверждения во frontend остаются заглушками; см. [контракт API](../../api/README.md#identity-сессии-cookie-и-csrf). - `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр. - `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. Миграция 00014 добавляет `pending_password_hash`, `pending_scenario` и `pending_onboarding_step`, чтобы каждый токен нес данные своей регистрации. CHECK допускает не больше одного из consumed и invalidated. @@ -659,14 +659,14 @@ contact_grant относится к паре кандидат-компания - База хранит хеши, а не пароли и исходные токены. Токен несет 256 бит из crypto/rand, поэтому SHA-256 без соли нельзя обратить перебором, а поиск остается одним обращением к индексу; для паролей нужен медленный KDF Argon2id. `bytea` вдвое компактнее hex-текста, допускает точную проверку длины и не имеет вариантов регистра. `domain.SecretToken`, `domain.PasswordHash` и `domain.EmailAddress` скрывают значение в выводе `fmt` (для любого verb) и `slog`, поэтому при печати `domain.User` не видны ни адрес, ни хеш; настоящие значения возвращают явные методы доступа. Неотображенные ошибки PostgreSQL из репозиториев identity сохраняют только SQLSTATE и имя ограничения, потому что текст и detail ошибки могут содержать значения строки. - Колонки с перечислимыми значениями - text с CHECK, а не enum-типы PostgreSQL. Новый сценарий, шаг или назначение заменяет одно ограничение в обратимой миграции; значение enum нельзя удалить и нельзя использовать в транзакции, которая его добавила. - Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, поэтому сроки и проверки по ним используют одни часы. Репозитории отклоняют нулевое время. -- Колонки для CSRF нет. `GetCurrentSession` должен вернуть CSRF-токен сессии после перезагрузки страницы, а сохраненный хеш не позволяет его восстановить. Аутентификация сессий может выводить токен из токена сессии с серверным ключом, что не требует хранения, или добавить колонку аддитивной миграцией. +- Колонки для CSRF нет. `GetCurrentSession` возвращает токен после перезагрузки страницы: сервер выводит его HMAC-SHA-256 с доменным разделением из cookie-токена и `IDENTITY_KEY_SECRET`, поэтому хранить или восстанавливать исходный токен в БД не нужно. Сравнение выполняется за постоянное время; сам session token в БД хранится только как SHA-256 хеш. Что гарантируют порты: - `UserRepository.Create` возвращает `ErrEmailTaken` для повторного ключа. `UpdateRegistration` сохраняет результат `domain.User.ReRegister`, только если сохраненная `version` совпадает и email не подтвержден; тот же запрос увеличивает `version` и `registration_version` на единицу, поэтому версию регистрации не выбирает вызывающий код, и удаляет регистрационное C1 прежнего регистранта (см. [Журнал согласий](#журнал-согласий)). `MarkEmailVerified` применяется только к неподтвержденному аккаунту с указанной версией регистрации. В остальных случаях оба возвращают `ErrUserVersionConflict`. - `EmailTokenRepository.Consume` - один `UPDATE ... RETURNING`, который требует непогашенный, неаннулированный и неистекший токен. Параллельные вызовы ждут в очереди на блокировку строки токена; при READ COMMITTED каждый ожидающий заново проверяет строку после завершения владельца блокировки, поэтому успешен ровно один, а если владелец откатился, ожидающий еще может погасить токен. Неудача сообщается как `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (заменен или выдан для более ранней версии регистрации) или `ErrEmailTokenExpired`. `InvalidateActive` помечает все прежние токены пользователя с этим назначением. - Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения переводит этот исход в `verification_token_invalid`. -- `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` записывает `last_seen_at`, только если сохраненное значение старше более чем на минуту, поэтому частые запросы не переписывают строку, а таймаут простоя может завершить сессию на минуту раньше; `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`. +- `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` объединяет записи с интервалом, равным меньшему из одной минуты и половины таймаута простоя: частые запросы не переписывают строку, а короткий допустимый idle timeout успевает продлеваться. `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`. - `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены, сессии, запросы писем, доставки писем и записи согласий через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена, сессии, запроса письма, доставки или согласия заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой, подтверждением, обработчиком доставки или worker доставки; пропущенные аккаунты остаются до следующего запуска. Запросы писем, доставки и попытки удаляются вместе с аккаунтом каскадно; записи согласий, которые запрещают удаление аккаунта, удаляются явно в том же запросе. - `postgres.IdentityStore` выполняет те же репозитории вне транзакции. При вызове с контекстом из callback `Transactor` он возвращает `ErrNestedTransaction`, а не фиксирует изменения через отдельное соединение. - Нарушения уникальности и внешних ключей переводятся в `ErrEmailTaken`, `ErrTokenHashConflict` и `ErrUserNotFound` по SQLSTATE и имени ограничения, а не по тексту ошибки. @@ -674,14 +674,14 @@ contact_grant относится к паре кандидат-компания ### Хеширование паролей -Реализовано и покрыто тестами: регистрация создает hasher из конфигурации и вызывает его; вход будет делать то же. +Реализовано и покрыто тестами: регистрация и вход используют hasher из конфигурации. - `domain.Password` хранит пароль, нормализованный в Unicode NFKC. `domain.NewPassword` применяет политику регистрации: от 15 до 128 кодовых точек после нормализации; `domain.ParseLoginPassword` принимает от 1 до 128. До нормализации оба отклоняют исходный ввод длиннее 512 байт (128 кодовых точек по 4 байта UTF-8 максимум, поэтому любое значение, принятое схемой контракта, помещается) и некорректный UTF-8. Эти проверки выполняются до любого хеширования и завершаются `domain.ErrInvalidPassword` с названием правила, но без значения. Blocklist распространенных и утекших паролей - отдельная запланированная проверка. - Порт `outbound.PasswordHasher` (`port/outbound/password.go`) содержит `Hash`, `Verify` и `VerifyDummy`; адаптер `adapter/secondary/argon2id` реализует его через `golang.org/x/crypto/argon2`. Новые хеши используют Argon2id v19 с m=65536 KiB, t=3, p=4 (второй рекомендованный вариант RFC 9106, выше базового уровня OWASP 19 MiB, t=2, p=1), соль 16 байт из crypto/rand и ключ 32 байта в формате `$argon2id$v=19$m=65536,t=3,p=4$$` в base64 без дополнения - этот формат принимают `domain.NewPasswordHash` и CHECK `users_password_hash_format`. Один хеш занял примерно 26-33 ms на машине разработчика Apple M5 (`BenchmarkHashRecommendedParameters`, в том числе на одном CPU); это не измерение задержки в production. -- Бюджет памяти: вычисления делят взвешенный семафор (`golang.org/x/sync/semaphore`) размером `PASSWORD_HASH_CONCURRENCY`, умноженное на 64 MiB, и каждое держит свой параметр памяти, пока выполняется. Настройка принимает от 1 до 4; если она не задана, берется меньшее из 2 и GOMAXPROCS, который Go выводит из лимита CPU контейнера. Compose передает `PASSWORD_HASH_CONCURRENCY=1` для backend-контейнера с 1 CPU, поэтому хеши вычисляются по одному и занимают 64 MiB живой памяти; максимум 4 требует 256 MiB. Память завершенного вычисления остается мусором до следующей сборки; `GOMEMLIMIT=600MiB` в Compose заставляет сборщик освободить ее раньше, чем куча дойдет примерно до 78% лимита контейнера 768 MiB, а остаток приходится на стеки и память вне кучи. Ожидающие вызовы стоят в очереди FIFO, ограниченной только контекстом запроса; ограничение частоты запросов появится вместе с HTTP-операциями. -- `Verify` строго разбирает сохраненную строку PHC, заново вычисляет ключ с сохраненными параметрами, солью и длиной ключа и сравнивает за постоянное время. Неверный пароль возвращает `outbound.ErrPasswordMismatch`. Некорректный хеш или хеш вне границ для сохраненных значений (память от 8 KiB на lane до 128 MiB и в пределах бюджета хеширования, от 1 до 16 проходов, от 1 до 16 lanes, соль 8-64 байта, digest 16-64 байта) возвращает `outbound.ErrPasswordHashCorrupt` без вычисления, поэтому подделанная строка не может потребовать неограниченную память или время. `ErrPasswordHashCorrupt` оборачивает `domain.ErrInvalidPasswordHash`, который репозиторий возвращает для сохраненного хеша, не прошедшего `domain.NewPasswordHash`. При совпадении `needsRehash` сообщает, что параметры, соль или длина ключа отличаются от текущих, и вход может сохранить новый хеш. -- `VerifyDummy` выполняет `Verify` для хеша с текущими параметрами, случайной солью и случайным digest и возвращает `ErrPasswordMismatch` (или ошибку контекста). Вход будет вызывать его для неизвестного email, поэтому обе ветки одинаково разбирают хеш, ждут память, вычисляют и сравнивают. -- Вход должен отвечать `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также должен записать ошибку в лог и вызвать `VerifyDummy`. Оставшиеся различия во времени: поврежденный хеш отклоняется без вычисления, что компенсирует `VerifyDummy`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует. +- Бюджет памяти: вычисления делят взвешенный семафор (`golang.org/x/sync/semaphore`) размером `PASSWORD_HASH_CONCURRENCY`, умноженное на 64 MiB, и каждое держит свой параметр памяти, пока выполняется. Настройка принимает от 1 до 4; если она не задана, берется меньшее из 2 и GOMAXPROCS, который Go выводит из лимита CPU контейнера. Compose передает `PASSWORD_HASH_CONCURRENCY=1` для backend-контейнера с 1 CPU, поэтому хеши вычисляются по одному и занимают 64 MiB живой памяти; максимум 4 требует 256 MiB. Память завершенного вычисления остается мусором до следующей сборки; `GOMEMLIMIT=600MiB` в Compose заставляет сборщик освободить ее раньше, чем куча дойдет примерно до 78% лимита контейнера 768 MiB, а остаток приходится на стеки и память вне кучи. Ожидающие вызовы стоят в очереди FIFO, ограниченной только контекстом запроса; HTTP-лимиты identity описаны в разделе серверных сессий. +- `Verify` строго разбирает сохраненную строку PHC, заново вычисляет ключ с сохраненными параметрами, солью и длиной ключа и сравнивает за постоянное время. Неверный пароль возвращает `outbound.ErrPasswordMismatch`. Некорректный хеш или хеш вне границ для сохраненных значений (память от 8 KiB на lane до 128 MiB и в пределах бюджета хеширования, от 1 до 16 проходов, от 1 до 16 lanes, соль 8-64 байта, digest 16-64 байта) возвращает `outbound.ErrPasswordHashCorrupt` без вычисления, поэтому подделанная строка не может потребовать неограниченную память или время. `ErrPasswordHashCorrupt` оборачивает `domain.ErrInvalidPasswordHash`, который репозиторий возвращает для сохраненного хеша, не прошедшего `domain.NewPasswordHash`. При совпадении `needsRehash` сообщает, что параметры, соль или длина ключа отличаются от текущих; вход пока не обновляет такие хеши автоматически. +- `VerifyDummy` выполняет `Verify` для хеша с текущими параметрами, случайной солью и случайным digest и возвращает `ErrPasswordMismatch` (или ошибку контекста). Вход вызывает его для неизвестного email и некорректного сохраненного хеша, чтобы эти ветки также выполняли полноценную проверку Argon2id. +- Вход отвечает `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также пишет ошибку в лог и вызывает `VerifyDummy`. Подтвержденный email с верным паролем, но без успешной верификации, получает `email_not_verified` и не создает сессию. Время проверки не полностью одинаково: для неизвестного email и поврежденного хеша выполняется `VerifyDummy`, а сохраненные хеши с разными Argon2id-параметрами требуют разное время. - `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация вызывает его во всех ветках до поиска email. - Ошибки и логи никогда не содержат пароль или хеш. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken` и `domain.EmailAddress` скрывают значение в выводе `fmt`, `slog` и JSON и хранят его за указателем, поэтому при печати внешней структуры, даже через неэкспортируемое поле, виден только адрес. @@ -734,21 +734,21 @@ contact_grant относится к паре кандидат-компания ### Регистрация, подтверждение и повторная отправка -Реализовано: `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/identity.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`. +Реализовано: `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/auth.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`. Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт. Отложенные учетные данные (защита от pre-hijack). Каждая регистрация, первая и каждая повторная, хранит хеш пароля, сценарий и первый шаг онбординга на своем токене подтверждения (столбцы `pending_*` таблицы `email_tokens`, миграция 00014). Повторная регистрация неподтвержденного адреса никогда не меняет учетные данные, сценарий и шаг онбординга строки `users`: `UserRepository.AdvanceRegistration` только увеличивает версию регистрации и время регистрации (и удаляет C1 прежней регистрации), а новый токен несет новые отложенные данные. Повторная отправка копирует отложенные данные новейшего токена регистрации. `password_hash`, `scenario` и `onboarding_step` строки неподтвержденного аккаунта не авторитетны, пока подтверждение не применит отложенные данные нажатого токена: в них значения первого регистранта лишь потому, что столбцы обязательны, и никакой код не вправе по ним аутентифицировать или им доверять (см. комментарий к `domain.User`). Аннулирование токена (`InvalidateActive`) очищает его столбцы `pending_*`, а CHECK не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает. -Подтверждение почты (`ConfirmEmail`) реализовано. Оно требует пароль, сохраненный для регистрации этого токена, и проверяет его по отложенному хешу. В одной транзакции backend проверяет текущую версию регистрации и запись C1, погашает токен, подтверждает адрес, переносит с токена на аккаунт хеш пароля, сценарий и шаг онбординга, очищает `pending_*` и записывает ровно одно событие `identity.email_verified` без секретов. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный, устаревший токен, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`; истекший токен дает `verification_token_expired`. Origin должен точно совпадать с `APP_PUBLIC_URL`. Подтверждение не создает сессию. Экран подтверждения во frontend пока остается заглушкой; вход и восстановление сессии еще не реализованы. +Подтверждение почты (`ConfirmEmail`) реализовано. Оно требует пароль, сохраненный для регистрации этого токена, и проверяет его по отложенному хешу. В одной транзакции backend проверяет текущую версию регистрации и запись C1, погашает токен, подтверждает адрес, переносит с токена на аккаунт хеш пароля, сценарий и шаг онбординга, очищает `pending_*` и записывает ровно одно событие `identity.email_verified` без секретов. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный, устаревший токен, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`; истекший токен дает `verification_token_expired`. Origin должен точно совпадать с `APP_PUBLIC_URL`. Подтверждение не создает сессию. Экран подтверждения во frontend пока остается заглушкой. -Планируемое поведение входа: неподтвержденный аккаунт не сможет войти. Вход будет отвечать как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не будет сравнивать пароль со строкой неподтвержденного аккаунта или с отложенными данными. +Вход принимает только подтвержденный email и проверяет сохраненный пароль аккаунта, а не отложенные данные регистрации. Неизвестный адрес, неверный пароль и некорректный сохраненный хеш получают одинаковый `invalid_credentials`; неизвестный адрес и некорректный хеш дополнительно проходят `VerifyDummy`, а ошибка сохраненного хеша записывается в лог без email или хеша. Верный пароль для неподтвержденного аккаунта отвечает `email_not_verified` и не создает сессию. Успешный вход создает новую сессию; если запрос принес действующую cookie сессии, сервер отзывает ее и создает новую в одной транзакции. Неуспешный вход не отзывает старую сессию, а некорректная cookie не становится principal. Порядок проверок регистрации: валидация всего тела и версии текста C1, проверка воспроизведения, лимит, хеш пароля (в каждой ветке, до чтения аккаунта), транзакция. Ошибка валидации (400) не зависит от хранимых аккаунтов и не расходует лимит. Идемпотентность. Ключ ограничен `HMAC(secret, операция | ключ | нормализованный email)`, отпечаток запроса - `HMAC(secret, канонное тело)` (`identity.Keyring`, секрет `IDENTITY_KEY_SECRET`; обязателен; стенд разработки может задать `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, чтобы взять случайный на процесс, и тогда записи и счетчики теряются при перезапуске). Запись хранится в `idempotency_records` (миграция 00014) 24 часа и пишется в транзакции регистрации, поэтому видимая запись всегда относится к зафиксированной регистрации. Повтор с тем же ключом и телом воспроизводит нейтральный 202 и не расходует лимит; тот же ключ с другим телом дает 422 `idempotency_key_reused`. Параллельный одинаковый запрос ждет строку первого и затем воспроизводится, поэтому эта реализация никогда не отвечает 409 `idempotency_in_progress`. Каждая регистрация удаляет до 10 просроченных записей, поэтому таблица остается ограниченной без отдельного задания. -Лимиты (Redis, фиксированные окна, `outbound.RateLimiter`, `redis.Cache.Take`, один атомарный Lua-скрипт на вызов). Счетчики ключуются HMAC нормализованного адреса и считают каждый запрос независимо от того, есть ли аккаунт, поэтому 429 ничего не раскрывает об аккаунте. Регистрация и каждая повторная отправка делят счетчики адреса: не меньше `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между двумя письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за окно 24 часа, которое начинается с первого. Подтверждение ограничивает каждый токен пятью попытками в час. Счетчик клиента `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час) ключуется `middleware.LimiterKey` от `ClientAddr`, хешируется секретом и пропускается, когда адрес неизвестен (общий бакет позволил бы одному клиенту заблокировать всех). Отклоненный вызов `Take` не увеличивает свой счетчик; если предыдущая проверка лимита прошла, ее счетчик уже учел попытку, даже когда следующая проверка отказала. Отказ отвечает 429 `rate_limited` с `Retry-After` в целых секундах с округлением вверх и не выпускает токен. Счетчики эфемерны: перезапуск Redis их сбрасывает, а квота почтового провайдера остается последней границей. Сбой Redis дает 500 и никогда не пропускает запрос. Ни адрес, ни токен не логируются. +Лимиты (Redis, фиксированные окна, `outbound.RateLimiter`, `redis.Cache.Take`, один атомарный Lua-скрипт на вызов). Счетчики ключуются HMAC нормализованного адреса и считают каждый запрос независимо от того, есть ли аккаунт, поэтому 429 ничего не раскрывает об аккаунте. Регистрация и каждая повторная отправка делят счетчики адреса: не меньше `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между двумя письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за окно 24 часа, которое начинается с первого. Подтверждение ограничивает каждый токен пятью попытками в час. Счетчик клиента `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час) применяется к регистрации, подтверждению, повторной отправке и входу; он ключуется `middleware.LimiterKey` от `ClientAddr`, хешируется секретом и пропускается, когда адрес неизвестен (общий бакет позволил бы одному клиенту заблокировать всех). Вход также ограничен `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (по умолчанию 10 в час) для нормализованного email, независимо от наличия аккаунта. Оба настраиваемых лимита принимают значения от 1 до 10000. Отклоненный вызов `Take` не увеличивает свой счетчик; если предыдущая проверка лимита прошла, ее счетчик уже учел попытку, даже когда следующая проверка отказала. Отказ отвечает 429 `rate_limited` с `Retry-After` в целых секундах с округлением вверх. Счетчики эфемерны: перезапуск Redis их сбрасывает, а квота почтового провайдера остается последней границей. Сбой Redis дает 500 и никогда не пропускает запрос. Ни адрес, ни токен не логируются. Политика замены токена. Каждый выпуск токена подтверждения (регистрация, повторная регистрация, повторная отправка) сначала аннулирует все неиспользованные токены подтверждения аккаунта и затем сохраняет новый, поэтому одновременно работает не больше одной ссылки. Повторная отправка не меняет пароль, сценарий, запись согласия и версию регистрации, меняется только токен. Письмо аннулированного токена воркер отправки отменяет, поэтому доставляется только текущая ссылка. Срок жизни токена берется из продуктовой политики (`identity.verification_token_lifetime_hours`, 24 в демонстрационной версии), а не из конфигурации. @@ -756,6 +756,14 @@ contact_grant относится к паре кандидат-компания Без определенного адреса клиента (middleware `ClientIP` не выполнился) лимит клиента пропускается и действуют только лимиты адреса: общий бакет "unknown" позволил бы одному клиенту заблокировать всех, что хуже. `IDENTITY_KEY_SECRET` обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` позволяет стенду разработки взять случайный. Ключи лимитера содержат hash tag Redis (`{key}`), поэтому скрипт с несколькими ключами безопасен для кластера. +### Серверные сессии + +Вход, чтение текущей сессии и выход реализованы на 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. + +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`. Таймаут простоя не может превышать абсолютный срок; неверные значения останавливают запуск. Активный запрос продлевает срок простоя, но не абсолютный срок. + +`IDENTITY_KEY_SECRET` должен иметь не менее 32 байт и оставаться одинаковым между перезапусками и экземплярами backend. Он также выводит ключ CSRF с разделением назначения `lincodex/identity/session-csrf/v1`; смена общего секрета делает прежние значения CSRF недействительными, но не отзывает сессии в PostgreSQL - клиент получает новый токен через GetCurrentSession. После успешной проверки пароля создание новой сессии и отзыв принесенной действующей сессии коммитятся одной транзакцией. Ошибка входа старую сессию не отзывает. Logout с просроченной или отозванной cookie очищает ее в браузере; ошибка Origin или CSRF не отзывает и не очищает действующую сессию. + Известные ограничения. Повторная отправка для неизвестного или подтвержденного адреса пропускает работу с токеном и письмом, поэтому ее время отличается от неподтвержденного аккаунта на несколько запросов к базе; регистрация скрывает разницу за хешем пароля. Blocklist паролей из контракта еще не реализован; действуют только правила длины `domain.NewPassword`. ### Организации и членства diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 31889a1..ab8e7bc 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -72,9 +72,9 @@ Compose healthcheck запускает `kafka-broker-api-versions.sh` проти Backend получает `KAFKA_BROKERS` - список адресов bootstrap в формате `host:port` через запятую. Compose задает `kafka:9092`; прямой запуск Go по умолчанию использует `localhost:9092`. Явно пустое значение, пустой элемент списка, отсутствующий или нулевой порт либо схема URL приводят к ошибке конфигурации. Relay outbox подключается к этим брокерам в фоне: backend не ждет Kafka при старте, а `/readyz` ее не проверяет. Объявленный адрес `kafka:9092` разрешается только внутри Compose сети, поэтому для прямого запуска нужен отдельно доступный брокер. Redis остается кешем и не используется как очередь. -`PASSWORD_HASH_CONCURRENCY` задает бюджет памяти Argon2id в вычислениях по 64 MiB и четыре lanes каждое (от 1 до 4). Compose передает значение из `.env`, по умолчанию 1, потому что у backend-контейнера 1 CPU и 768 MB: второе вычисление только добавило бы 64 MiB, деля тот же CPU. Backend, запущенный напрямую без переменной, берет меньшее из 2 и GOMAXPROCS. Следующие регистрации и входы ждут память, пока не завершится контекст запроса. Compose также задает `GOMEMLIMIT=600MiB`, примерно 78% лимита контейнера, чтобы сборщик Go освобождал память завершенных вычислений раньше, чем контейнеру ее не хватит; меняйте его вместе с лимитом памяти. Значение читается и проверяется при старте; регистрация и вход начнут его использовать, когда будут реализованы. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей). +`PASSWORD_HASH_CONCURRENCY` задает бюджет памяти Argon2id в вычислениях по 64 MiB и четыре lanes каждое (от 1 до 4). Compose передает значение из `.env`, по умолчанию 1, потому что у backend-контейнера 1 CPU и 768 MB: второе вычисление только добавило бы 64 MiB, деля тот же CPU. Backend, запущенный напрямую без переменной, берет меньшее из 2 и GOMAXPROCS. Следующие регистрации и входы ждут память, пока не завершится контекст запроса. Compose также задает `GOMEMLIMIT=600MiB`, примерно 78% лимита контейнера, чтобы сборщик Go освобождал память завершенных вычислений раньше, чем контейнеру ее не хватит; меняйте его вместе с лимитом памяти. Значение читается и проверяется при старте; регистрация и вход используют его. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей). -`IDENTITY_KEY_SECRET` обязателен в production `.env` (не меньше 32 байт; сгенерируйте `openssl rand -base64 48` и храните неизменным между перезапусками и на всех экземплярах). Он ключует записи идемпотентности регистрации и счетчики лимитов; Compose не стартует без него, а backend не стартует без него, если не задан `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, который нужен только стендам разработки. Смена секрета забывает записи идемпотентности и счетчики за последние 24 часа. `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию `1m`), `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию `5`) и `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию `30`) ограничивают письма подтверждения на адрес и запросы на клиента; пустое значение означает значение по умолчанию. Подтверждение также ограничено 5 попытками на токен в час. Метрика `lincodex_identity_rate_limit_refusals_total{scope}` считает отказы; большая доля `scope="client"` намекает на сломанную цепочку прокси (см. `TRUSTED_PROXY_CIDRS`). См. [ARCHITECTURE.md](ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка). +`IDENTITY_KEY_SECRET` обязателен в production `.env` (не меньше 32 байт; сгенерируйте `openssl rand -base64 48` и храните неизменным между перезапусками и на всех экземплярах). Он ключует записи идемпотентности и лимиты, а также выводит ключ для session CSRF; Compose не стартует без него, а backend не стартует без него, если не задан `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, который нужен только стендам разработки. Смена секрета меняет ключи счетчиков и поиска записей идемпотентности за последние 24 часа и делает прежние CSRF-токены недействительными, но не отзывает сессии, сохраненные в PostgreSQL. `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию `1m`) и `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию `5`) ограничивают письма подтверждения на адрес; пустое значение означает значение по умолчанию. `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию `30` и принимает значения от `1` до `10000`; он ограничивает регистрацию, подтверждение, повторную отправку и вход по адресу клиента, если тот разрешен доверенной цепочкой. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` по умолчанию `10` и принимает значения от `1` до `10000`; он ограничивает вход по нормализованному email независимо от наличия аккаунта. Подтверждение также ограничено 5 попытками на токен в час. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h` (от `1m` до `30d`), `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h` (от `1m` до `365d`); idle timeout не может превышать absolute lifetime, а некорректная конфигурация останавливает backend при запуске. Метрика `lincodex_identity_rate_limit_refusals_total{scope}` считает отказы; большая доля `scope="client"` намекает на сломанную цепочку прокси (см. `TRUSTED_PROXY_CIDRS`). См. [ARCHITECTURE.md](ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка) и раздел о серверных сессиях в [ARCHITECTURE.md](ARCHITECTURE.md#серверные-сессии). down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова. @@ -239,7 +239,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL Совместимость выпуска: `ConfirmEmail` требует `token` и пароль, выбранный при соответствующей регистрации. Клиенты, которые отправляли только токен, нужно обновить. Миграция `00016_bind_registration_consent.sql` добавляет версию регистрации к C1 и заполняет ее для прежних записей по текущей версии аккаунта, без требования живого токена. Она проверяет, что регистрационная C1 не старше последней регистрации и что у аккаунта нет нескольких активных регистрационных C1; при несоответствии миграция останавливается без частичных изменений. Триггер заполняет версию, если старый backend не передал ее, и отклоняет несовпадающую версию от нового backend. Частичный уникальный индекс допускает не больше одной неотозванной регистрационной C1 на аккаунт и версию регистрации. Миграцию можно применить до обновления backend. При откате сначала верните старый backend, затем отмените миграцию. Новые переменные окружения не нужны. `APP_PUBLIC_URL` также задает Origin, который должен передавать запрос подтверждения. -`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов относятся к запланированному слою доставки, а ожидание сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). +`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов выполняет worker отправки, а ожидание известного сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). `disabled` ничего не отправляет. Каждая отправка возвращает `ErrMailChannelUnavailable` без идентификатора сообщения провайдера и никогда не считается принятой или доставленной. Этот режим не подтверждает email, не отмечает аккаунт подтвержденным и не пропускает проверки аккаунта. В логе запуска есть `mail transport selected` с полем `email_provider`, а для `disabled` еще и предупреждение `mail delivery is disabled`. @@ -282,21 +282,21 @@ Compose передает эти переменные из корневого `.e - Внутренний endpoint /metrics показывает текущие окна настроенного аккаунта, которые читаются каждые 30 секунд: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` (1 после отказа провайдера по квоте), каждая с labels `provider` и `window` (`day` или `month`). `EMAIL_ACCOUNT` не становится label, потому что его текст выбирает оператор; при `EMAIL_PROVIDER=disabled` серий квот нет. Alert `LincodexMailQuotaUsedUp` (severity info) срабатывает, пока окно исчерпано. - Варианты, пока письма ждут: дождаться сброса, для этого ничего делать не нужно; или после осознанной смены тарифа у провайдера поднять лимиты и перезапустить backend, тогда новые отправки снова допускаются, а отложенные доставки сохраняют свой `next_attempt_at`; или осознанно сменить транспорт или аккаунт (что остается закрепленным, описано в [Доставки писем](#доставки-писем)). Не уменьшайте `used_recipients` и не правьте журнал вручную, чтобы освободить отправки: у провайдера свой счет, и такие отправки он только отклонит. - `provider_exhausted_at` в строке значит, что провайдер ответил отказом по квоте, хотя по локальному счету место было. Возможные причины: аккаунт отправляет письма еще откуда-то; Resend учитывает в той же квоте полученные (входящие) письма; или настроенный лимит выше тарифа. Приведите лимиты в соответствие с тарифом. -- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов. +- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Локальная команда оператора предназначена для терминального `unknown`, а не для доставок, ожидающих сброса квоты. - Сниженный лимит действует со следующего резервирования. Во время поэтапного обновления экземпляры со старым и новым лимитом работают одновременно, и каждый проверяет лимит, с которым запущен, поэтому сниженный лимит соблюдается только после того, как все экземпляры работают с новой конфигурацией. Переключение `EMAIL_PROVIDER` на `smtp` начинает для relay отдельные счетчики с его явно заданными лимитами; доставки, закрепленные за прежним аккаунтом, шлюз отклоняет, а не отправляет без лимита. ### Отправка служебной почты -Процесс backend запускает один цикл отправки служебной почты identity (подтверждение почты и сброс пароля). Он стартует вместе с backend, когда `EMAIL_PROVIDER` равен `resend` и задан `DATABASE_URL`, использует ту же базу, что и другие worker, через pool из двух соединений и не требует собственных настроек: интервал опроса (5 секунд), lease на захваченную доставку (`EMAIL_TIMEOUT` плюс одна минута), льготный период остановки (5 секунд), расписание повторов (1 минута с удвоением до 30 минут) и пауза после сбоя (5 секунд с удвоением до 2 минут) - константы в `backend/internal/bootstrap/mail_sender.go`. Миграция 00012 добавляет его столбцы; модель, проверки и исходы описаны в [ARCHITECTURE.md](ARCHITECTURE.md#отправка-служебной-почты). +Процесс backend запускает один цикл отправки служебной почты identity (подтверждение почты и сброс пароля). Он стартует вместе с backend, когда `EMAIL_PROVIDER` равен `resend` и задан `DATABASE_URL`, использует ту же базу, что и другие worker, через pool из двух соединений и не требует собственных настроек: интервал опроса (5 секунд), lease на захваченную доставку (`EMAIL_TIMEOUT` плюс одна минута), льготный период остановки (5 секунд), расписание повторов (1 минута с удвоением до 30 минут) и пауза после сбоя (5 секунд с удвоением до 2 минут) - константы в `backend/internal/bootstrap/mail_sender.go`. Миграция 00012 добавляет его столбцы, а 00017 - журнал решений для неопределенного исхода и пересоздает частичный индекс доставок под блокировкой таблицы. Откат 00017 удаляет журнал и всю историю аудита, поэтому перед ним экспортируйте решения. Модель, проверки и исходы описаны в [ARCHITECTURE.md](ARCHITECTURE.md#отправка-служебной-почты). - Одновременно может работать несколько экземпляров backend. Каждый захватывает доставку через `FOR UPDATE SKIP LOCKED` и lease, поэтому одну доставку отправляет один экземпляр, а вызов провайдера несет стабильный ключ идемпотентности `delivery/`. При поэтапном обновлении останавливающийся экземпляр завершает отправку в течение 5 секунд, сохраняет результат и выходит. - При `EMAIL_PROVIDER=disabled` цикл не запускается, а в журнале пишется `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` равен 0, ничего не отправляется, а сохраненная служебная почта ждет следующего запуска с транспортом. Worker никогда не крутится вхолостую: после прохода, который ничего не смог отправить, он делает паузу. - Перед отправкой worker проверяет токен и аккаунт. Доставка, которую нельзя отправлять, завершается как `cancelled` с `cancel_reason`, без попытки и без расхода квоты: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Причины, вызванные пользователем, нормальны: пользователь запросил новую ссылку, подтвердил адрес, зарегистрировался заново или слишком долго ждал. Причины можно посмотреть так: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. Пользователь видит отмененное письмо как "не отправлено, запросите новое". -- Ответы провайдера: `accepted` означает принято провайдером, а не доставлено человеку; подтверждения доставки у backend нет. Отказ "пока" (`temporary`, `rate_limited`) оставляет доставку в `pending` с более поздним `next_attempt_at`, а повтор использует тот же ключ и тело; он повторяется, пока не удастся, пока не будет отказа навсегда или пока токен не истечет и доставка не будет отменена. Постоянный отказ или отказ из-за запроса завершает ее как `rejected`: прочитайте код провайдера в `delivery_attempts.provider_code` (например `validation_error` для неподтвержденного домена отправителя или `invalid_api_key`) и устраните причину. Ответ о квоте переводит ее в `waiting_quota`; см. [Квоты почты](#квоты-почты). -- `unknown` worker никогда не повторяет. Это значит, что провайдер мог принять письмо (потерянный ответ, ответ 5xx) или что worker, отправивший его, был потерян дольше 24-часового окна идемпотентности провайдера. Найдите сообщение в журнале самого провайдера; пока срабатывает alert `LincodexMailDeliveryUnknownOutcome`. Ручной повтор с записью аудита запланирован вместе с политикой повторов. +- Ответы провайдера: `accepted` означает принято провайдером, а не доставлено человеку; подтверждения доставки у backend нет. Подтвержденный временный отказ или 429 означает, что провайдер не принял письмо: доставка остается в `pending` с более поздним `next_attempt_at`, повтор использует закрепленные аккаунт, ключ и тело. `Retry-After` от Resend - нижняя граница ожидания. Такой отказ не снимает неопределенность от более ранней попытки `unknown`. После cutoff продолжать повторы подтвержденных отказов можно только в рамках ожидающего ручного решения; без него worker остановится и оставит более ранний `unknown` на проверку оператора. Постоянный отказ или отказ из-за запроса завершает ее как `rejected`: прочитайте код провайдера в `delivery_attempts.provider_code` (например `validation_error` для неподтвержденного домена отправителя или `invalid_api_key`) и устраните причину. Ответ о квоте переводит ее в `waiting_quota`; см. [Квоты почты](#квоты-почты). +- Неопределенный исход Resend автоматически повторяется с теми же закрепленными аккаунтом, ключом и сохраненным телом только до 23 часов после первого начала отправки, записанного часами базы. Это на час раньше документированного 24-часового срока хранения ключа. Worker повторяет проверку cutoff прямо перед сетевым вызовом. После cutoff или после ручного send-start с потерянным результатом автоматические повторы останавливаются, а alert `LincodexMailDeliveryUnknownOutcome` требует проверки. Сначала проверьте журнал провайдера. Для терминальной строки `unknown` выполните `make -C backend mail-retry ARGS='inspect --delivery '`, чтобы увидеть метаданные и предупреждение о возможном дубле, затем `make -C backend mail-retry ARGS='retry --delivery --actor operator: --acknowledge-duplicate-risk'`, чтобы запланировать одно аудируемое решение. Команда требует локальный доступ к базе, доступна только при `EMAIL_PROVIDER=resend`, показывает предупреждение до изменения состояния и сама письмо не отправляет. Actor является меткой для аудита, а не аутентификацией; HTTP endpoint оператора нет. Ручное решение не запускает заново срок ключа провайдера: после нового `unknown` или потери результата ручной отправки worker остановится и потребует еще одно решение. Истекший ключ идемпотентности может привести к дублю и после подтверждения риска. - Захваченная доставка держит lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. Строка с давно прошедшим `claimed_until` значит, что ее worker умер; другой экземпляр подхватит ее сам. Не сбрасывайте lease вручную. - `content_invalid` и `processing_failed` - не действия пользователя: первое значит, что сохраненная строка не совпадает со своим хешем содержимого (ручная правка) или содержит сообщение, которое не принимает ни один транспорт, второе - что worker трижды подряд потерпел сбой на строке (повторы разнесены расписанием). Alert `LincodexMailCancelledBroken` срабатывает при росте; прочитайте журнал worker по `delivery_id` и осмотрите метаданные строки. Строка, которая сбоит постоянно, не блокирует остальные: она повторяется позже (`failure_count`, `next_attempt_at`), а затем отменяется. -- Тела письма с токеном очищаются, когда оно принято, отклонено или отменено (ставится `body_redacted_at`), поэтому дампы и резервные копии завершенной почты с токеном токенов не содержат. Письмо в `unknown` сохраняет тело, пока оператор его не разрешит. Не копируйте тела ожидающих писем никуда. +- Тела письма с токеном очищаются, когда оно принято, отклонено или отменено (ставится `body_redacted_at`), поэтому дампы и резервные копии завершенной почты с токеном токенов не содержат. Письмо в `unknown` сохраняет тело, пока оператор его не разрешит. Команда повтора не показывает адрес, тело, ключ или токен. Не копируйте тела ожидающих писем никуда. - Lease измеряется часами базы, поэтому различие часов экземпляров не важно, важны только часы базы. Вызов провайдера ограничен остатком lease; при `SHUTDOWN_TIMEOUT` по умолчанию 10 секунд останавливающийся экземпляр укладывается в 3 секунды льготного периода плюс 5 секунд на сохранение ответа. Снижение `SHUTDOWN_TIMEOUT` укорачивает вторую часть (не меньше 1 секунды); результат, не сохраненный вовремя, покрывает перехват. - Журнал называет доставку только по `delivery_id`, ее виду и исходу или причине отмены, например `service mail was not sent because it is no longer valid`; никогда не по адресу, токену, ссылке или телу. Если токен или ссылка появились в журнале, считайте это дефектом. - Внутренний endpoint /metrics показывает `lincodex_mail_sender_running` (1, пока цикл этого экземпляра работает, иначе 0; без labels) и `lincodex_mail_sender_cancelled_total{reason}` (счетчик по причине отмены, включая нулевые) рядом с gauges доставок, у которых теперь есть и статус `cancelled`. @@ -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. Планируемая cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict`. Браузер принимает ее только со страницы HTTPS, с `Path=/` и без `Domain`; один HTTPS origin это обеспечивает. Edge сохраняет `Host` как публичное имя и ставит `X-Forwarded-Proto: https`; Nginx frontend контейнера сохраняет это значение для backend (`$forwarded_proto` в `deploy/nginx/conf.d/app.conf`), а иначе сообщает собственную схему. `APP_PUBLIC_URL` в `.env` app-хоста должен быть `https://`: это единственное значение origin, которое читает backend. +Браузер видит только `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 для этой проверки. -Регистрация, повторная отправка подтверждения и подтверждение email доступны через API, но вход не реализован. Экраны регистрации и подтверждения во frontend остаются заглушками, а backend не читает `X-Forwarded-Proto`. Поэтому браузерный путь подтверждения и вход через edge не проверены end to end; проверен транспорт cookie (HTTPS, один origin, переданные исходные хост и схема). +Регистрация, повторная отправка подтверждения, подтверждение email, вход, чтение текущей сессии и выход доступны через backend API. Экраны регистрации и подтверждения во frontend остаются заглушками, а backend не читает `X-Forwarded-Proto` для проверки origin. Браузерный путь входа через edge не проверен end to end. ### Обработка запросов на edge @@ -490,7 +490,7 @@ Docker обходит ufw для опубликованных портов: он systemctl list-timers certbot.timer sudo certbot certificates -Reload запускает новые workers с новым сертификатом и конфигурацией и дает старым workers дойти до конца открытых соединений, поэтому запросы в полете и keep-alive соединения не обрываются. Сессии nginx вообще не хранит: планируемая схема держит их в PostgreSQL за непрозрачной cookie, поэтому reload или перезапуск nginx или туннеля никого не разлогинивает. Пока вход не реализован, доступное доказательство - запрос в полете и удерживаемое соединение через `systemctl reload nginx`: оба завершаются без 5xx, а следующий запрос по тому же соединению проходит. +Reload запускает новые workers с новым сертификатом и конфигурацией и дает старым workers дойти до конца открытых соединений, поэтому запросы в полете и keep-alive соединения не обрываются. Состояние сессии хранит backend в PostgreSQL, а не nginx: reload или перезапуск nginx либо туннеля не отзывает сессию, пока работают backend и база. Проверка ниже подтверждает только завершение запроса в полете и работу keep-alive через `systemctl reload nginx`; сохранение входа через браузер после reload не проверено end to end. ### Проверка