diff --git a/.env.example b/.env.example index d6c2878..35e5ae2 100644 --- a/.env.example +++ b/.env.example @@ -68,6 +68,19 @@ PASSWORD_HASH_CONCURRENCY=1 # two together if the range collides with another network or route. APP_SUBNET=172.29.79.0/24 APP_FRONTEND_IP=172.29.79.10 +# Registration. IDENTITY_KEY_SECRET is required: it keys the idempotency +# records and the rate limit counters, so a restart or another instance keeps +# them. 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 +# A value that starts with replace-this is refused. Without it the backend refuses to start, unless a development stand sets +# IDENTITY_ALLOW_EPHEMERAL_KEY=true (a random secret per process). +IDENTITY_KEY_SECRET= +# The limits count the registration and every verification resend per address. +VERIFICATION_MAIL_MIN_INTERVAL=1m +VERIFICATION_MAIL_DAILY_LIMIT=5 +IDENTITY_CLIENT_HOURLY_LIMIT=30 + # Reverse proxies the backend trusts to report the client address in # X-Forwarded-For. Leave it unset: the default is the frontend container's # APP_FRONTEND_IP as a single address. A wider list lets other containers (or a diff --git a/api/README.en.md b/api/README.en.md index 8863dab..ebeed5b 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. The operations are in the contract; their business logic is not implemented yet. Until it is, public operations answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from configuration in TASK-053 to TASK-056. +The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount` and `ResendEmailVerification` are implemented (TASK-053); the other public operations still answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from configuration in TASK-054 to TASK-056. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -121,8 +121,9 @@ Registration and verification: - Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email, and login answers 401 `invalid_credentials` for both an unknown email and a wrong password. - 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 replaces the password hash, the scenario, the onboarding step, and the C1 record, advances the registration version, invalidates every earlier verification token, and sends a new one. A pre-registration with someone else's password therefore does not survive the owner's own registration. For a verified email nothing changes; the server may send a rate-limited "you already have an account" notice. -- 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, 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). +- Registering an unverified email again never changes the password hash, the scenario, or the onboarding step of the account row. Every registration, the first and each repeat, stores its own pending credentials (password hash and scenario) on its own verification token, replaces the C1 record, advances the registration version, and invalidates every earlier verification token. Confirming a token (`ConfirmEmail`, TASK-054) must apply the pending credentials of that token only, and must require the password of that registration to confirm a token that carries pending credentials; the current `EmailVerificationRequest` has no password field, so TASK-054 changes the contract. This stops a pre-registration with someone else's password from being adopted by the address owner who clicks the attacker's link, and the reverse. The account row of an unverified account cannot be used to sign in: login (TASK-055) refuses every unverified account and never compares a password with the row or the pending credentials of an unverified account. For a verified email nothing changes; the server sends nothing. +- Implementation of registration and resend (TASK-053). 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). 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-and-verification-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. - The verification link is `/verify-email#token=`. The page removes the fragment with `history.replaceState` and posts the token only after an explicit user action, so the token stays out of server logs and Referer headers and a link scanner does not consume it. Verification does not start a session. - An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token answers `verification_token_invalid`. The client offers a new link and sign-in for both. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token. diff --git a/api/README.md b/api/README.md index c331e2f..5e1aca5 100644 --- a/api/README.md +++ b/api/README.md @@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Identity: сессии, cookie и CSRF -Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Операции есть в контракте, бизнес-логика еще не реализована. До ее появления публичные операции после валидации запроса отвечают 501 `not_implemented`, а `v1.DenyAllSecurity` в backend отклоняет любую сессию, поэтому операции, которым она нужна, отвечают 401 `unauthenticated`. Значения, отмеченные как запланированные, задаются конфигурацией в TASK-053 - TASK-056. +Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount` и `ResendEmailVerification` реализованы (TASK-053); остальные публичные операции после валидации запроса по-прежнему отвечают 501 `not_implemented`, а `v1.DenyAllSecurity` в backend отклоняет любую сессию, поэтому операции, которым она нужна, отвечают 401 `unauthenticated`. Значения, отмеченные как запланированные, задаются конфигурацией в TASK-054 - TASK-056. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -121,8 +121,9 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Аккаунты не перечисляются. Регистрация и повторная отправка отвечают одинаковым нейтральным 202 для нового, неподтвержденного, подтвержденного и неизвестного email, а вход отвечает 401 `invalid_credentials` и для неизвестного email, и для неверного пароля. - До поиска email сервер проверяет все тело регистрации (длину пароля после нормализации NFKC, blocklist паролей, версию C1) и в каждой ветке вычисляет хеш Argon2id, поэтому ни 400, ни время ответа не зависят от существования аккаунта. -- Повторная регистрация неподтвержденного email заменяет хеш пароля, сценарий, шаг онбординга и запись C1, увеличивает версию регистрации, аннулирует все прежние токены подтверждения и отправляет новый. Поэтому предрегистрация с чужим паролем не переживает собственную регистрацию владельца адреса. Для подтвержденного email ничего не меняется; сервер может отправить ограниченное по частоте уведомление "у вас уже есть аккаунт". -- Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики). +- Повторная регистрация неподтвержденного email никогда не меняет хеш пароля, сценарий и шаг онбординга строки аккаунта. Каждая регистрация, первая и каждая повторная, хранит свои отложенные учетные данные (хеш пароля и сценарий) на своем токене подтверждения, заменяет запись C1, увеличивает версию регистрации и аннулирует все прежние токены подтверждения. Подтверждение токена (`ConfirmEmail`, TASK-054) обязано применять отложенные данные только этого токена и требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными; в текущем `EmailVerificationRequest` поля пароля нет, поэтому TASK-054 меняет контракт. Это не дает владельцу адреса, перешедшему по ссылке злоумышленника, принять предрегистрацию с чужим паролем, и наоборот. Строкой неподтвержденного аккаунта нельзя войти: вход (TASK-055) отклоняет любой неподтвержденный аккаунт и никогда не сравнивает пароль со строкой или с отложенными данными неподтвержденного аккаунта. Для подтвержденного email ничего не меняется; сервер ничего не отправляет. +- Реализация регистрации и повторной отправки (TASK-053). Подтвержденный адрес: ничего не меняется и ничего не отправляется (уведомление "у вас уже есть аккаунт" не реализовано). Лимиты на адрес (общие для регистрации и повторной отправки, ключ - HMAC нормализованного адреса, считаются независимо от наличия аккаунта): не реже `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за 24 часа; на клиента: `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час). Отклоненный запрос дает 429 `rate_limited` с `Retry-After` в целых секундах и не выпускает токен. Политика замены токена: каждый выпуск сначала аннулирует все неиспользованные токены подтверждения аккаунта, поэтому работает одна ссылка; повторная отправка меняет только токен. `IDENTITY_KEY_SECRET` (не меньше 32 байт, обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` разрешает случайный на стенде разработки) ключует область идемпотентности, отпечаток и ключи лимитера. Параллельный запрос с тем же ключом ждет первый и воспроизводится, поэтому `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 тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля. - Ссылка подтверждения имеет вид `/verify-email#token=`. Страница удаляет фрагмент через `history.replaceState` и отправляет токен только после явного действия пользователя, поэтому токен не попадает в логи сервера и заголовок Referer, а сканер ссылок его не расходует. Подтверждение не создает сессию. - Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии - `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку и вход. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос. diff --git a/backend/config/config.go b/backend/config/config.go index d412178..69d3e79 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -120,6 +120,23 @@ 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 string + // IdentityAllowEphemeralKey lets a development stand run without + // IDENTITY_KEY_SECRET, with a random secret per process. + IdentityAllowEphemeralKey bool + // VerificationMailMinInterval and VerificationMailDailyLimit bound the + // verification messages to one address: the registration and every + // resend count against both. + VerificationMailMinInterval time.Duration + VerificationMailDailyLimit int + // IdentityClientHourlyLimit bounds the registrations and resends of one + // client network address per hour. + IdentityClientHourlyLimit int + // TrustedProxyCIDRs are the reverse proxies in front of the API. The // client address is taken from X-Forwarded-For only through them (see // middleware.ClientIP). Empty trusts no proxy. @@ -173,6 +190,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) { if err := config.loadPasswordHash(lookup); err != nil { return Config{}, err } + if err := config.loadIdentity(lookup); err != nil { + return Config{}, err + } if err := config.loadTrustedProxies(lookup); err != nil { return Config{}, err } @@ -223,6 +243,9 @@ func (config Config) Validate() error { if err := config.ValidatePasswordHash(); err != nil { return err } + if err := config.ValidateIdentity(); err != nil { + return err + } if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil { return err } @@ -267,8 +290,6 @@ func DatabaseURLFromEnv(lookup LookupEnv) string { // boolOrDefault accepts only "true" or "false", ignoring case and surrounding // spaces. strconv.ParseBool would also accept 1, t, and similar shorthands, // which are easy to mistype in deployment files. -// -//nolint:unparam // Every setting names its own default; that all current defaults are true is a coincidence. func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) { value, ok := lookup(key) if !ok { diff --git a/backend/config/config_test.go b/backend/config/config_test.go index 45a973c..5a0ef45 100644 --- a/backend/config/config_test.go +++ b/backend/config/config_test.go @@ -112,6 +112,9 @@ func testEnvironment(values map[string]string) LookupEnv { if value, ok := values[key]; ok { return value, true } + if key == "IDENTITY_KEY_SECRET" { + return "config-test-identity-key-secret-0123456789", true + } if key == "SEAWEEDFS_ACCESS_KEY" { return "test-access", true } diff --git a/backend/config/identity.go b/backend/config/identity.go new file mode 100644 index 0000000..7f20d64 --- /dev/null +++ b/backend/config/identity.go @@ -0,0 +1,98 @@ +package config + +import ( + "errors" + "fmt" + "strings" + "time" +) + +const ( + // defaultVerificationMailMinInterval is the shortest time between two + // verification messages to one address, counting the registration and + // every resend. + defaultVerificationMailMinInterval = time.Minute + // minVerificationMailMinInterval and maxVerificationMailMinInterval bound + // the setting: a shorter interval is no brake, a longer one is a + // lock-out that a person who mistyped cannot wait out. + minVerificationMailMinInterval = time.Second + maxVerificationMailMinInterval = time.Hour + // defaultVerificationMailDailyLimit is the number of verification + // 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 = 30 + maxIdentityClientHourlyLimit = 10000 + // MinIdentityKeySecretBytes is the shortest accepted IDENTITY_KEY_SECRET. + MinIdentityKeySecretBytes = 32 + // examplePlaceholderPrefix starts the placeholder values of the example + // environment file; a secret that keeps it is public. + examplePlaceholderPrefix = "replace-this" +) + +// loadIdentity reads the registration 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. +// +// The three limits 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 + config.IdentityAllowEphemeralKey, err = boolOrDefault(lookup, "IDENTITY_ALLOW_EPHEMERAL_KEY", false) + if err != nil { + return err + } + setOnly := func(key string) (string, bool) { + value, ok := lookup(key) + if strings.TrimSpace(value) == "" { + return "", false + } + return value, ok + } + config.VerificationMailMinInterval, err = durationOrDefault(setOnly, "VERIFICATION_MAIL_MIN_INTERVAL", defaultVerificationMailMinInterval) + if err != nil { + return err + } + config.VerificationMailDailyLimit, err = intOrDefault(setOnly, "VERIFICATION_MAIL_DAILY_LIMIT", defaultVerificationMailDailyLimit) + if err != nil { + return err + } + config.IdentityClientHourlyLimit, err = intOrDefault(setOnly, "IDENTITY_CLIENT_HOURLY_LIMIT", defaultIdentityClientHourlyLimit) + return err +} + +// ValidateIdentity checks the registration settings. Errors never include +// the secret. +func (config Config) ValidateIdentity() 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") + } + if strings.HasPrefix(config.IdentityKeySecret, examplePlaceholderPrefix) { + return errors.New("Config.ValidateIdentity - IDENTITY_KEY_SECRET is an example placeholder; generate a real one with: openssl rand -base64 48") + } + if config.IdentityKeySecret != "" && len(config.IdentityKeySecret) < MinIdentityKeySecretBytes { + return fmt.Errorf("Config.ValidateIdentity - IDENTITY_KEY_SECRET must have at least %d bytes", MinIdentityKeySecretBytes) + } + if config.VerificationMailMinInterval < minVerificationMailMinInterval || config.VerificationMailMinInterval > maxVerificationMailMinInterval { + return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be between %s and %s", + minVerificationMailMinInterval, maxVerificationMailMinInterval) + } + 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 +} diff --git a/backend/config/identity_test.go b/backend/config/identity_test.go new file mode 100644 index 0000000..ff3267f --- /dev/null +++ b/backend/config/identity_test.go @@ -0,0 +1,113 @@ +package config + +import ( + "strings" + "testing" + "time" +) + +func TestLoadFromEnvIdentityDefaults(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_ALLOW_EPHEMERAL_KEY": "true", "IDENTITY_KEY_SECRET": ""})) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + 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) + } +} + +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", + })) + if err != nil { + t.Fatalf("LoadFromEnv() error = %v", err) + } + if settings.IdentityKeySecret != secret || settings.VerificationMailMinInterval != 90*time.Second || + settings.VerificationMailDailyLimit != 3 || settings.IdentityClientHourlyLimit != 100 { + t.Fatalf("identity settings were not read: %+v", settings) + } +} + +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"}, + } + for name, test := range tests { + _, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value})) + if err == nil || !strings.HasPrefix(err.Error(), test.want) { + t.Fatalf("LoadFromEnv(%s) error = %v, want an error starting with %q", name, err, test.want) + } + } +} + +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") { + t.Fatalf("LoadFromEnv() error = %v, want an error without the secret", err) + } +} + +func TestLoadFromEnvIdentityEmptyLimitsMeanUnset(t *testing.T) { + settings, err := LoadFromEnv(testEnvironment(map[string]string{ + "VERIFICATION_MAIL_MIN_INTERVAL": "", + "VERIFICATION_MAIL_DAILY_LIMIT": " ", + "IDENTITY_CLIENT_HOURLY_LIMIT": "", + })) + 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) + } +} + +func TestLoadFromEnvRequiresTheIdentityKeySecret(t *testing.T) { + // Not through testEnvironment, which supplies a secret. + lookup := func(key string) (string, bool) { + if key == "IDENTITY_KEY_SECRET" || key == "IDENTITY_ALLOW_EPHEMERAL_KEY" { + return "", false + } + return testEnvironment(nil)(key) + } + _, err := LoadFromEnv(lookup) + if err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET is required") || !strings.Contains(err.Error(), "openssl rand") { + t.Fatalf("LoadFromEnv() error = %v, want the missing secret named with how to generate one", err) + } + ephemeral := func(key string) (string, bool) { + if key == "IDENTITY_ALLOW_EPHEMERAL_KEY" { + return "true", true + } + return lookup(key) + } + settings, err := LoadFromEnv(ephemeral) + if err != nil || !settings.IdentityAllowEphemeralKey { + t.Fatalf("LoadFromEnv(ephemeral) = %v, %v, want an accepted development configuration", settings.IdentityAllowEphemeralKey, err) + } +} + +func TestLoadFromEnvRejectsThePlaceholderSecret(t *testing.T) { + const placeholder = "replace-this-identity-key-secret-0123456789abcdef" + _, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_KEY_SECRET": placeholder})) + if err == nil || !strings.Contains(err.Error(), "example placeholder") || strings.Contains(err.Error(), placeholder) { + t.Fatalf("LoadFromEnv() error = %v, want a refusal that does not quote the value", err) + } +} diff --git a/backend/db/migrations/00014_create_idempotency_records.sql b/backend/db/migrations/00014_create_idempotency_records.sql new file mode 100644 index 0000000..c648c98 --- /dev/null +++ b/backend/db/migrations/00014_create_idempotency_records.sql @@ -0,0 +1,84 @@ +-- +goose Up +-- Replay records of anonymous commands that carry an Idempotency-Key, first +-- of all the registration. A record is written in the same transaction as +-- the effect it guards, so a record that is visible always belongs to a +-- committed command: a running command is represented by the uncommitted row +-- itself, on which a concurrent request with the same scope waits. +-- +-- Nothing here identifies a person or reveals a credential. scope_hash is an +-- HMAC-SHA-256 with a server secret over the operation, the key, and the +-- normalized email, and fingerprint is an HMAC-SHA-256 with a server secret +-- over the canonical request body; without the secret neither can be used to +-- confirm an email address or to test a password offline. +CREATE TABLE idempotency_records ( + scope_hash bytea NOT NULL, + fingerprint bytea NOT NULL, + created_at timestamptz NOT NULL, + -- The key may be accepted as new once this time has passed. + expires_at timestamptz NOT NULL, + CONSTRAINT idempotency_records_pkey PRIMARY KEY (scope_hash), + CONSTRAINT idempotency_records_scope_hash_sha256 CHECK ( + octet_length(scope_hash) = 32 + ), + CONSTRAINT idempotency_records_fingerprint_sha256 CHECK ( + octet_length(fingerprint) = 32 + ), + CONSTRAINT idempotency_records_expiry_after_creation CHECK ( + expires_at > created_at + ) +); + +-- Serves the bounded purge of expired records. +CREATE INDEX idempotency_records_expires_at_idx +ON idempotency_records (expires_at); + +-- Pending credentials of a registration, bound to the verification token +-- issued for it. A registration of an unverified address never changes the +-- credentials of the account row: it issues a token that carries its own +-- password hash and scenario. Confirming a token applies the credentials of +-- that token, so whoever registered an address first or last cannot make the +-- owner of the address adopt a password the owner did not choose. NULL for +-- tokens that carry none (a resend copies them from the registration's +-- latest token; password reset tokens carry none). +ALTER TABLE email_tokens +ADD COLUMN pending_password_hash text, +ADD COLUMN pending_scenario text, +ADD COLUMN pending_onboarding_step text, +ADD CONSTRAINT email_tokens_pending_all_or_none CHECK ( + (pending_password_hash IS NULL) = (pending_scenario IS NULL) + AND (pending_scenario IS NULL) = (pending_onboarding_step IS NULL) +), +ADD CONSTRAINT email_tokens_invalidated_keeps_no_pending CHECK ( + invalidated_at IS NULL OR pending_password_hash IS NULL +), +ADD CONSTRAINT email_tokens_pending_password_hash_format CHECK ( + pending_password_hash IS NULL + OR ( + char_length(pending_password_hash) <= 512 + AND pending_password_hash + ~ '^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$' + ) +), +ADD CONSTRAINT email_tokens_pending_scenario_step CHECK ( + pending_scenario IS NULL + OR ( + pending_scenario = 'candidate' + AND pending_onboarding_step = 'candidate_consents' + ) + OR ( + pending_scenario = 'employer' + AND pending_onboarding_step = 'employer_company' + ) +); + +-- +goose Down +ALTER TABLE email_tokens +DROP CONSTRAINT email_tokens_pending_scenario_step, +DROP CONSTRAINT email_tokens_invalidated_keeps_no_pending, +DROP CONSTRAINT email_tokens_pending_password_hash_format, +DROP CONSTRAINT email_tokens_pending_all_or_none, +DROP COLUMN pending_onboarding_step, +DROP COLUMN pending_scenario, +DROP COLUMN pending_password_hash; + +DROP TABLE idempotency_records; diff --git a/backend/db/queries/identity.sql b/backend/db/queries/identity.sql index 496a134..533e32c 100644 --- a/backend/db/queries/identity.sql +++ b/backend/db/queries/identity.sql @@ -273,7 +273,10 @@ INSERT INTO email_tokens ( token_hash, registration_version, created_at, - expires_at + expires_at, + pending_password_hash, + pending_scenario, + pending_onboarding_step ) VALUES ( sqlc.arg(id), sqlc.arg(user_id), @@ -281,12 +284,92 @@ INSERT INTO email_tokens ( sqlc.arg(token_hash), sqlc.arg(registration_version), sqlc.arg(created_at), - sqlc.arg(expires_at) + sqlc.arg(expires_at), + sqlc.narg(pending_password_hash), + sqlc.narg(pending_scenario), + sqlc.narg(pending_onboarding_step) ); +-- The pending credentials of the newest token of a registration, for a +-- resend, which issues its token with the same credentials. +-- name: GetLatestPendingRegistration :one +SELECT + pending_password_hash, + pending_scenario, + pending_onboarding_step +FROM email_tokens +WHERE + user_id = sqlc.arg(user_id) + AND purpose = sqlc.arg(purpose) + AND registration_version = sqlc.arg(registration_version) + AND pending_password_hash IS NOT NULL +ORDER BY created_at DESC, id DESC +LIMIT 1; + +-- Starts a new registration of an unverified account without touching its +-- credentials, scenario, or onboarding step: the new registration carries +-- them on its verification token. Advances the registration version, which +-- ends every earlier token, and deletes the registration C1 of the earlier +-- registrant like UpdateUserRegistration does. +-- name: AdvanceUserRegistration :one +WITH updated AS ( + UPDATE users + SET + registration_version = registration_version + 1, + last_registered_at = sqlc.arg(registered_at), + updated_at = sqlc.arg(registered_at), + version = version + 1 + WHERE + users.id = sqlc.arg(id) + AND users.version = sqlc.arg(expected_version) + AND users.email_verified_at IS NULL + RETURNING + users.id, + users.email, + users.email_normalized, + users.password_hash, + users.scenario, + users.onboarding_step, + users.email_verified_at, + users.registration_version, + users.last_registered_at, + users.version, + users.created_at, + users.updated_at +), + +discarded_consent AS ( + DELETE FROM consent_records + USING updated + WHERE + consent_records.subject_id = updated.id + AND consent_records.purpose = 'c1' + AND consent_records.source = 'registration' +) + +SELECT + updated.id, + updated.email, + updated.email_normalized, + updated.password_hash, + updated.scenario, + updated.onboarding_step, + updated.email_verified_at, + updated.registration_version, + updated.last_registered_at, + updated.version, + updated.created_at, + updated.updated_at +FROM updated; + -- name: InvalidateActiveEmailTokens :execrows UPDATE email_tokens -SET invalidated_at = sqlc.arg(invalidated_at) +SET + invalidated_at = sqlc.arg(invalidated_at), + -- An invalidated token keeps no password hash: it can never be confirmed. + pending_password_hash = NULL, + pending_scenario = NULL, + pending_onboarding_step = NULL WHERE user_id = sqlc.arg(user_id) AND purpose = sqlc.arg(purpose) @@ -323,7 +406,10 @@ RETURNING token.created_at, token.expires_at, token.consumed_at, - token.invalidated_at; + token.invalidated_at, + token.pending_password_hash, + token.pending_scenario, + token.pending_onboarding_step; -- Explains why ConsumeEmailToken matched no row. -- name: GetEmailTokenState :one @@ -416,3 +502,52 @@ SET revoked_at = sqlc.arg(revoked_at) WHERE user_id = sqlc.arg(user_id) AND revoked_at IS NULL; + +-- Stores the replay record of a command. A record whose retention has passed +-- is replaced, so the key is accepted as new after the retention. A live +-- record is left as it is and nothing is returned; the caller then reads it +-- with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait +-- on the row of the first one until its transaction ends. +-- name: ReserveIdempotencyRecord :one +INSERT INTO idempotency_records ( + scope_hash, + fingerprint, + created_at, + expires_at +) VALUES ( + sqlc.arg(scope_hash), + sqlc.arg(fingerprint), + sqlc.arg(created_at), + sqlc.arg(expires_at) +) +ON CONFLICT (scope_hash) DO UPDATE +SET + fingerprint = excluded.fingerprint, + created_at = excluded.created_at, + expires_at = excluded.expires_at +WHERE idempotency_records.expires_at <= excluded.created_at +RETURNING scope_hash, fingerprint, created_at, expires_at; + +-- name: GetLiveIdempotencyRecord :one +SELECT + scope_hash, + fingerprint, + created_at, + expires_at +FROM idempotency_records +WHERE + scope_hash = sqlc.arg(scope_hash) + AND expires_at > sqlc.arg(at); + +-- Deletes at most batch_limit expired records. Locked rows are skipped, so +-- the statement never waits for a concurrent reservation. +-- name: PurgeExpiredIdempotencyRecords :execrows +DELETE FROM idempotency_records +WHERE scope_hash IN ( + SELECT stale.scope_hash + FROM idempotency_records AS stale + WHERE stale.expires_at <= sqlc.arg(at) + ORDER BY stale.expires_at + LIMIT sqlc.arg(batch_limit) + FOR UPDATE SKIP LOCKED +); diff --git a/backend/integration_test/bootstrap_test.go b/backend/integration_test/bootstrap_test.go index 5c51e73..9ef7fa2 100644 --- a/backend/integration_test/bootstrap_test.go +++ b/backend/integration_test/bootstrap_test.go @@ -131,6 +131,7 @@ func bootstrap(t *testing.T, services ...service) *testEnvironment { "REDIS_PASSWORD": redisPassword, "REDIS_TIMEOUT": redisTimeout.String(), "SEAWEEDFS_ACCESS_KEY": seaweedfsAccessKey, + "IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab", "SEAWEEDFS_SECRET_KEY": seaweedfsSecretKey, "SEAWEEDFS_BUCKET": seaweedfsBucket, "SEAWEEDFS_TIMEOUT": storageTimeout.String(), diff --git a/backend/integration_test/mail_quota_test.go b/backend/integration_test/mail_quota_test.go index a5e7d70..5760495 100644 --- a/backend/integration_test/mail_quota_test.go +++ b/backend/integration_test/mail_quota_test.go @@ -629,6 +629,7 @@ func (harness *quotaHarness) gateFromConfig(t *testing.T, mail map[string]string func loadQuotaConfig(mail map[string]string) (config.Config, error) { values := map[string]string{ "SEAWEEDFS_ACCESS_KEY": "test-access", + "IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab", "SEAWEEDFS_SECRET_KEY": "test-secret", "EMAIL_FROM": "no-reply@example.com", "EMAIL_ACCOUNT": quotaAccount, diff --git a/backend/integration_test/redis_ratelimit_test.go b/backend/integration_test/redis_ratelimit_test.go new file mode 100644 index 0000000..d3292c6 --- /dev/null +++ b/backend/integration_test/redis_ratelimit_test.go @@ -0,0 +1,87 @@ +//go:build integration + +package integration_test + +import ( + "errors" + "testing" + "time" + + "lincodex/backend/internal/port/outbound" +) + +func TestRedisRateLimiter(t *testing.T) { + env := bootstrap(t, redisService) + ctx := t.Context() + limiter := env.Redis + + t.Run("admits up to the limit and then reports the wait", func(t *testing.T) { + rule := outbound.RateLimitRule{Window: 10 * time.Second, Limit: 2} + for attempt := 1; attempt <= 2; attempt++ { + decision, err := limiter.Take(ctx, "limit-basic", rule) + if err != nil || !decision.Allowed || decision.RetryAfter != 0 { + t.Fatalf("take %d = %+v, %v, want allowed", attempt, decision, err) + } + } + decision, err := limiter.Take(ctx, "limit-basic", rule) + if err != nil || decision.Allowed || decision.RetryAfter <= 0 || decision.RetryAfter > rule.Window { + t.Fatalf("third take = %+v, %v, want refused with a wait inside the window", decision, err) + } + }) + + t.Run("a refused take counts nothing in any rule", func(t *testing.T) { + interval := outbound.RateLimitRule{Window: 300 * time.Millisecond, Limit: 1} + daily := outbound.RateLimitRule{Window: time.Hour, Limit: 3} + if decision, err := limiter.Take(ctx, "limit-atomic", interval, daily); err != nil || !decision.Allowed { + t.Fatalf("first take = %+v, %v", decision, err) + } + // Refused by the interval: the daily counter must stay at 1. + for range 5 { + if decision, err := limiter.Take(ctx, "limit-atomic", interval, daily); err != nil || decision.Allowed { + t.Fatalf("take inside the interval = %+v, %v, want refused", decision, err) + } + } + time.Sleep(350 * time.Millisecond) + for attempt := 2; attempt <= 3; attempt++ { + decision, err := limiter.Take(ctx, "limit-atomic", interval, daily) + if err != nil || !decision.Allowed { + t.Fatalf("take %d after the interval = %+v, %v, want allowed", attempt, decision, err) + } + time.Sleep(350 * time.Millisecond) + } + decision, err := limiter.Take(ctx, "limit-atomic", interval, daily) + if err != nil || decision.Allowed || decision.RetryAfter < 50*time.Minute { + t.Fatalf("take over the daily limit = %+v, %v, want refused until the daily window ends", decision, err) + } + }) + + t.Run("keys are independent and windows reset", func(t *testing.T) { + rule := outbound.RateLimitRule{Window: 200 * time.Millisecond, Limit: 1} + for _, key := range []string{"limit-a", "limit-b"} { + if decision, err := limiter.Take(ctx, key, rule); err != nil || !decision.Allowed { + t.Fatalf("first take of %s = %+v, %v", key, decision, err) + } + } + time.Sleep(250 * time.Millisecond) + if decision, err := limiter.Take(ctx, "limit-a", rule); err != nil || !decision.Allowed { + t.Fatalf("take after the window = %+v, %v, want allowed", decision, err) + } + }) + + t.Run("rejects an invalid rule", func(t *testing.T) { + for name, rules := range map[string][]outbound.RateLimitRule{ + "no rule": nil, + "zero limit": {{Window: time.Second, Limit: 0}}, + "zero window": {{Window: 0, Limit: 1}}, + "tiny window": {{Window: time.Microsecond, Limit: 1}}, + "second fails": {{Window: time.Second, Limit: 1}, {Window: time.Second, Limit: -1}}, + } { + if _, err := limiter.Take(ctx, "limit-invalid", rules...); !errors.Is(err, outbound.ErrInvalidRateLimitRule) { + t.Fatalf("Take(%s) error = %v, want ErrInvalidRateLimitRule", name, err) + } + } + if _, err := limiter.Take(ctx, "", outbound.RateLimitRule{Window: time.Second, Limit: 1}); !errors.Is(err, outbound.ErrInvalidRateLimitRule) { + t.Fatalf("Take with an empty key error = %v", err) + } + }) +} diff --git a/backend/integration_test/registration_test.go b/backend/integration_test/registration_test.go new file mode 100644 index 0000000..9bb5e5e --- /dev/null +++ b/backend/integration_test/registration_test.go @@ -0,0 +1,642 @@ +//go:build integration + +package integration_test + +import ( + "bytes" + "context" + "crypto/sha256" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "regexp" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/jackc/pgx/v5" + "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" + "lincodex/backend/internal/adapter/secondary/mail/resend" + "lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture" + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/health" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" + "lincodex/backend/internal/usecase/policy" +) + +const ( + registrationTestTimeout = 5 * time.Minute + registrationPath = "/api/v1/identity/registrations" + resendPath = "/api/v1/identity/email-verification-requests" + registrationPassword = "correct horse battery staple" + registrationC1 = `{"text_version":"c1-2026-10-01","accepted":true}` + // registrationMinInterval is long enough that one request, including the + // password hash, finishes well inside it, and short enough to wait out. + // The production default is a minute. + registrationMinInterval = 3 * time.Second + registrationDailyLimit = 3 + registrationSecret = "integration-test-identity-key-secret-0123456789" +) + +var ( + registrationTables = slices.Concat(mailSenderTables, usersDependentTables, []pgx.Identifier{{"idempotency_records"}}) + // verificationLinkToken finds the token in the fragment of the link of + // the sent message. + verificationLinkToken = regexp.MustCompile(`#token=([A-Za-z0-9_-]{32,128})`) +) + +type registrationHarness struct { + pool *pgxpool.Pool + router http.Handler + sender *notification.ServiceMailSender + fixture *resendfixture.Server + clock *testClock + logs *syncBuffer + identity *postgresadapter.IdentityStore + // registration is the usecase behind the router. + registration *identity.Registration + // nextKey makes every request carry a new Idempotency-Key. + nextKey int + // start is the application time at the beginning of every subtest. + start time.Time +} + +func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironment, clientHourlyLimit int64) *registrationHarness { + t.Helper() + pool := env.newPoolWithMaxConns(ctx, t, 16) + // The demo policy is effective from its publication by the database clock, + // so the application clock must not be earlier than now. + clock := &testClock{now: time.Now().UTC().Add(time.Minute).Truncate(time.Microsecond)} + start := clock.Now() + logs := &syncBuffer{} + logger := slog.New(slog.NewJSONHandler(logs, nil)) + + templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL) + if err != nil { + t.Fatalf("NewRenderer() error = %v", err) + } + fixture := resendfixture.New() + t.Cleanup(fixture.Close) + transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, fixture.URL(), clock.Now) + if err != nil { + t.Fatalf("NewLoopbackSender() error = %v", err) + } + account, err := domain.NewMailProviderAccount("resend", mailSenderAccount) + if err != nil { + t.Fatalf("NewMailProviderAccount() error = %v", err) + } + // The product policy carries the verification token lifetime. + if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), clock.Now).EnsureDemoProductPolicy(ctx); err != nil { + t.Fatalf("EnsureDemoProductPolicy() error = %v", err) + } + + hasher, err := argon2id.NewHasher(2) + if err != nil { + t.Fatalf("NewHasher() error = %v", err) + } + keyring, err := identity.NewKeyring([]byte(registrationSecret)) + if err != nil { + t.Fatalf("NewKeyring() error = %v", err) + } + transactor := postgresadapter.NewTransactor(pool) + identityStore := postgresadapter.NewIdentityStore(pool) + registration, err := identity.NewRegistration(identity.RegistrationDependencies{ + Transactor: transactor, + ConsentTexts: postgresadapter.NewConsentStore(pool), + Idempotency: identityStore.IdempotencyRecords(), + Consents: consent.NewService(transactor, clock.Now), + Credentials: identity.NewCredentials(hasher), + Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(templates), account, clock.Now), + Limiter: env.Redis, + Keyring: keyring, + Clock: clock.Now, + }, identity.RegistrationSettings{ + MailMinInterval: registrationMinInterval, + MailDailyLimit: registrationDailyLimit, + ClientHourlyLimit: clientHourlyLimit, + }) + if err != nil { + t.Fatalf("NewRegistration() error = %v", err) + } + + responder := problem.NewResponder(logger) + healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second) + handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler(registration))) + router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, prometheus.New(), logger, nil) + if err != nil { + t.Fatalf("NewRouter() error = %v", err) + } + + limits, err := domain.NewMailQuotaLimits(1000, 10000) + if err != nil { + t.Fatalf("NewMailQuotaLimits() error = %v", err) + } + gate := notification.NewQuotaGate(account, limits, resend.IdempotencyWindow, clock.Now, logger) + sender, err := notification.NewServiceMailSender(transactor, transport, gate, notification.ServiceMailSenderSettings{ + Account: account, + Lease: time.Minute, + StoreTimeout: 30 * time.Second, + SettleBudget: mailSenderSettleBudget, + ShutdownSettleBudget: time.Second, + MaxFailures: 3, + Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute}, + }, clock.Now, logger) + if err != nil { + t.Fatalf("NewServiceMailSender() error = %v", err) + } + return ®istrationHarness{ + start: start, pool: pool, router: router, sender: sender, fixture: fixture, clock: clock, logs: logs, identity: identityStore, + registration: registration, + } +} + +type registrationResponse struct { + status int + body string + retryAfter string + // contentType is part of the shape that must not depend on the branch. + contentType string +} + +func (harness *registrationHarness) post(t *testing.T, path, body string, headers map[string]string) registrationResponse { + t.Helper() + request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + for name, value := range headers { + request.Header.Set(name, value) + } + recorder := httptest.NewRecorder() + harness.router.ServeHTTP(recorder, request) + return registrationResponse{ + status: recorder.Code, + body: recorder.Body.String(), + retryAfter: recorder.Header().Get("Retry-After"), + contentType: recorder.Header().Get("Content-Type"), + } +} + +func registrationBody(email, scenario, password, consent string) string { + return `{"email":"` + email + `","password":"` + password + `","scenario":"` + scenario + `","consent_c1":` + consent + `}` +} + +// register posts a registration under a fresh Idempotency-Key unless key is +// given. +func (harness *registrationHarness) register(t *testing.T, email, scenario, key string) registrationResponse { + t.Helper() + return harness.registerBody(t, registrationBody(email, scenario, registrationPassword, registrationC1), key) +} + +func (harness *registrationHarness) registerBody(t *testing.T, body, key string) registrationResponse { + t.Helper() + if key == "" { + harness.nextKey++ + key = "integration-key-" + strconv.Itoa(harness.nextKey) + } + return harness.post(t, registrationPath, body, map[string]string{"Idempotency-Key": key}) +} + +func (harness *registrationHarness) resend(t *testing.T, email string) registrationResponse { + t.Helper() + return harness.post(t, resendPath, `{"email":"`+email+`"}`, nil) +} + +func (harness *registrationHarness) count(ctx context.Context, t *testing.T, query string, args ...any) int { + t.Helper() + var count int + if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { + t.Fatalf("count %q: %v", query, err) + } + return count +} + +// drain runs the sending worker until it finds nothing due and returns how +// many deliveries it settled. +func (harness *registrationHarness) drain(ctx context.Context, t *testing.T) int { + t.Helper() + settled := 0 + for range 20 { + result, err := harness.sender.ProcessNext(ctx, ctx) + if err != nil { + t.Fatalf("ProcessNext() error = %v", err) + } + if result.Outcome == inbound.MailPassIdle { + return settled + } + settled++ + } + t.Fatal("the sending worker did not go idle") + return settled +} + +// truncate empties the tables of the flow. CASCADE also empties tables that +// later migrations add with a reference to users, so this suite does not +// depend on usersDependentTables being kept up to date by other tasks. +func (harness *registrationHarness) truncate(ctx context.Context, t *testing.T) { + t.Helper() + names := make([]string, 0, len(registrationTables)) + for _, table := range registrationTables { + names = append(names, table.Sanitize()) + } + harness.exec(ctx, t, "TRUNCATE "+strings.Join(names, ", ")+" CASCADE") +} + +func (harness *registrationHarness) exec(ctx context.Context, t *testing.T, statement string, args ...any) { + t.Helper() + if _, err := harness.pool.Exec(ctx, statement, args...); err != nil { + t.Fatalf("exec %q: %v", statement, err) + } +} + +func (harness *registrationHarness) assertLogsHoldNoSecrets(t *testing.T, forbidden ...string) { + t.Helper() + logs := harness.logs.String() + for _, marker := range forbidden { + if marker != "" && strings.Contains(logs, marker) { + t.Fatalf("a secret or an address reached the logs:\n%s", logs) + } + } +} + +// requireProblemStatus checks the status and the problem code of a response +// and returns its body. +func requireProblemStatus(t *testing.T, response registrationResponse, status int, code string) string { + t.Helper() + if response.status != status || !strings.Contains(response.body, `"code":"`+code+`"`) { + t.Fatalf("response = %d %s, want %d with code %s", response.status, response.body, status, code) + } + return response.body +} + +// requireRetryWithinInterval checks the wait of a refusal by the minimum +// interval: at least one second and at most the interval. +func requireRetryWithinInterval(t *testing.T, response registrationResponse) { + t.Helper() + wait, err := strconv.Atoi(response.retryAfter) + if err != nil || wait < 1 || wait > int(registrationMinInterval/time.Second) { + t.Fatalf("Retry-After = %q, want 1 to %d seconds", response.retryAfter, int(registrationMinInterval/time.Second)) + } +} + +func requireAccepted(t *testing.T, response registrationResponse) { + t.Helper() + if response.status != http.StatusAccepted || response.body != `{"status":"accepted"}` { + t.Fatalf("response = %d %s, want the neutral 202", response.status, response.body) + } +} + +func TestRegistrationOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 1000) + reset := func(t *testing.T) { + t.Helper() + harness.truncate(ctx, t) + harness.clock.Set(harness.start) + } + + t.Run("a candidate registers in one transaction with C1 and a queued message", func(t *testing.T) { + reset(t) + requests := len(harness.fixture.Requests()) + response := harness.register(t, "Candidate.One@Example.com", "candidate", "") + requireAccepted(t, response) + + var scenario, step string + var verified *time.Time + var version int64 + err := harness.pool.QueryRow(ctx, + `SELECT scenario, onboarding_step, email_verified_at, registration_version FROM users WHERE email_normalized = 'candidate.one@example.com'`, + ).Scan(&scenario, &step, &verified, &version) + if err != nil { + t.Fatalf("read the account: %v", err) + } + if scenario != "candidate" || step != "candidate_consents" || verified != nil || version != 1 { + t.Fatalf("account = %s %s verified=%v version=%d", scenario, step, verified, version) + } + assertRowCount(ctx, t, harness.pool, usersTable, 1) + + // C1 with the current text version and its hash; nothing else, in + // particular no C4. + c1Text, err := postgresadapter.NewConsentStore(harness.pool).ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, harness.clock.Now()) + if err != nil { + t.Fatalf("read the current C1 text: %v", err) + } + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 1) + var purpose, textVersion, source string + var textHash []byte + var revoked *time.Time + err = harness.pool.QueryRow(ctx, `SELECT purpose, text_version, text_hash, source, revoked_at FROM consent_records`). + Scan(&purpose, &textVersion, &textHash, &source, &revoked) + wantHash := c1Text.Hash() + if err != nil || purpose != "c1" || textVersion != string(c1Text.Version()) || !bytes.Equal(textHash, wantHash[:]) || + source != "registration" || revoked != nil { + t.Fatalf("consent record = %s %s %x %s revoked=%v, err=%v", purpose, textVersion, textHash, source, revoked, err) + } + if harness.count(ctx, t, `SELECT count(*) FROM consent_records WHERE purpose = 'c4'`) != 0 { + t.Fatal("C4 was recorded by the registration") + } + + // One token hash (never the raw token) and one queued delivery bound + // to it, in the same commit. + assertRowCount(ctx, t, harness.pool, emailTokensTable, 1) + var tokenHash []byte + var tokenID, deliveryTokenID string + var tokenVersion int64 + if err := harness.pool.QueryRow(ctx, `SELECT id::text, token_hash, registration_version FROM email_tokens`).Scan(&tokenID, &tokenHash, &tokenVersion); err != nil { + t.Fatalf("read the token: %v", err) + } + if len(tokenHash) != sha256.Size || tokenVersion != 1 { + t.Fatalf("token hash length = %d, version = %d", len(tokenHash), tokenVersion) + } + var status string + if err := harness.pool.QueryRow(ctx, `SELECT status, email_token_id::text FROM deliveries`).Scan(&status, &deliveryTokenID); err != nil { + t.Fatalf("read the delivery: %v", err) + } + if status != string(domain.DeliveryStatusPending) || deliveryTokenID != tokenID { + t.Fatalf("delivery = %s bound to %s, want pending bound to token %s", status, deliveryTokenID, tokenID) + } + + // The sending worker sends it through the local Resend fixture. + if settled := harness.drain(ctx, t); settled != 1 { + t.Fatalf("settled %d deliveries, want 1", settled) + } + sent := harness.fixture.Requests()[requests:] + if len(sent) != 1 || !slices.Equal(sent[0].To, []string{"Candidate.One@Example.com"}) { + t.Fatalf("fixture received %d messages to %v", len(sent), sent) + } + link := verificationLinkToken.FindStringSubmatch(sent[0].Text) + if link == nil { + t.Fatal("the message holds no verification link with the token in the fragment") + } + sum := sha256.Sum256([]byte(link[1])) + if !bytes.Equal(sum[:], tokenHash) { + t.Fatal("the token of the link does not match the stored hash") + } + harness.assertLogsHoldNoSecrets(t, "Candidate.One", registrationPassword, link[1]) + }) + + t.Run("an employer registers once and a repeat creates no second account and reveals nothing", func(t *testing.T) { + reset(t) + first := harness.register(t, "employer@example.com", "employer", "employer-key-1") + requireAccepted(t, first) + var step string + if err := harness.pool.QueryRow(ctx, `SELECT onboarding_step FROM users`).Scan(&step); err != nil || step != "employer_company" { + t.Fatalf("onboarding step = %q, err = %v, want employer_company", step, err) + } + + // The same request replays: one account, one token, one message. + replay := harness.register(t, "employer@example.com", "employer", "employer-key-1") + if replay != first { + t.Fatalf("replay = %+v, want exactly %+v", replay, first) + } + assertRowCount(ctx, t, harness.pool, usersTable, 1) + assertRowCount(ctx, t, harness.pool, emailTokensTable, 1) + assertRowCount(ctx, t, harness.pool, pgx.Identifier{"deliveries"}, 1) + + // The same key with another body is a reused key. + reused := harness.registerBody(t, registrationBody("employer@example.com", "employer", "another correct horse battery", registrationC1), "employer-key-1") + requireProblemStatus(t, reused, http.StatusUnprocessableEntity, "idempotency_key_reused") + + // A new registration of the pending address, with another password and + // scenario, never changes the credentials of the account row. + var firstHash string + if err := harness.pool.QueryRow(ctx, `SELECT password_hash FROM users`).Scan(&firstHash); err != nil { + t.Fatalf("read the password hash: %v", err) + } + time.Sleep(registrationMinInterval + 100*time.Millisecond) + again := harness.registerBody(t, registrationBody("employer@example.com", "candidate", "an attacker chosen long password", registrationC1), "") + if again != first { + t.Fatalf("repeat = %+v, want the same answer as the first registration %+v", again, first) + } + assertRowCount(ctx, t, harness.pool, usersTable, 1) + var scenario string + var version int64 + if err := harness.pool.QueryRow(ctx, `SELECT scenario, registration_version FROM users`).Scan(&scenario, &version); err != nil { + t.Fatalf("read the account: %v", err) + } + var hashAfter, stepAfter string + if err := harness.pool.QueryRow(ctx, `SELECT password_hash, onboarding_step FROM users`).Scan(&hashAfter, &stepAfter); err != nil { + t.Fatalf("read the account: %v", err) + } + if scenario != "employer" || stepAfter != "employer_company" || hashAfter != firstHash || version != 2 { + t.Fatalf("after the repeat: scenario = %s, step = %s, registration version = %d, hash unchanged = %t; want the first registration's credentials and version 2", + scenario, stepAfter, version, hashAfter == firstHash) + } + // Each token carries the pending credentials of its own registration; + // the invalidated first token keeps none. + rows, err := harness.pool.Query(ctx, `SELECT pending_password_hash, pending_scenario, pending_onboarding_step, registration_version, invalidated_at IS NOT NULL + FROM email_tokens ORDER BY created_at, id`) + if err != nil { + t.Fatalf("read the tokens: %v", err) + } + type pendingRow struct { + hash, scenario, step *string + version int64 + invalidated bool + } + var pendings []pendingRow + for rows.Next() { + var row pendingRow + if err := rows.Scan(&row.hash, &row.scenario, &row.step, &row.version, &row.invalidated); err != nil { + t.Fatalf("scan a token: %v", err) + } + pendings = append(pendings, row) + } + rows.Close() + if len(pendings) != 2 || + !pendings[0].invalidated || pendings[0].hash != nil || pendings[0].scenario != nil || pendings[0].step != nil || pendings[0].version != 1 || + pendings[1].invalidated || pendings[1].hash == nil || *pendings[1].hash == firstHash || + pendings[1].scenario == nil || *pendings[1].scenario != "candidate" || + pendings[1].step == nil || *pendings[1].step != "candidate_consents" || pendings[1].version != 2 { + t.Fatalf("tokens do not carry their own pending credentials: %+v", pendings) + } + assertRowCount(ctx, t, harness.pool, consentRecordsTable, 1) + if active := harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NULL AND consumed_at IS NULL`); active != 1 { + t.Fatalf("%d unused tokens, want exactly the new one", active) + } + if all := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`); all != 2 { + t.Fatalf("%d tokens, want the replaced one and the new one", all) + } + + // A verified address is left alone and answers the same way. + var userID string + if err := harness.pool.QueryRow(ctx, `SELECT id::text FROM users`).Scan(&userID); err != nil { + t.Fatalf("read the account ID: %v", err) + } + harness.exec(ctx, t, `UPDATE users SET email_verified_at = $1 WHERE id = $2`, harness.clock.Now(), userID) + tokens := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) + deliveries := harness.count(ctx, t, `SELECT count(*) FROM deliveries`) + time.Sleep(registrationMinInterval + 100*time.Millisecond) + verified := harness.register(t, "employer@example.com", "employer", "") + if verified != first { + t.Fatalf("verified address answered %+v, want %+v", verified, first) + } + if harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) != tokens || + harness.count(ctx, t, `SELECT count(*) FROM deliveries`) != deliveries || + harness.count(ctx, t, `SELECT count(*) FROM users WHERE scenario = 'employer' AND registration_version = 2`) != 1 { + t.Fatal("a registration of a verified address changed the account or queued a message") + } + // The replaced token never reaches the user: the sending worker + // cancels its message because the token is no longer current. + harness.drain(ctx, t) + harness.assertLogsHoldNoSecrets(t, "employer@example.com", registrationPassword) + }) + + t.Run("a stale consent text version is refused the same way and consumes nothing", func(t *testing.T) { + reset(t) + stale := `{"text_version":"c1-2000-01-01","accepted":true}` + for _, email := range []string{"new.address@example.com", "known.address@example.com"} { + if email == "known.address@example.com" { + requireAccepted(t, harness.register(t, email, "candidate", "")) + time.Sleep(registrationMinInterval + 100*time.Millisecond) + } + response := harness.registerBody(t, registrationBody(email, "candidate", registrationPassword, stale), "") + body := requireProblemStatus(t, response, http.StatusBadRequest, "validation_failed") + if !strings.Contains(body, `"/consent_c1/text_version"`) { + t.Fatalf("problem %s does not point at /consent_c1/text_version", body) + } + } + assertRowCount(ctx, t, harness.pool, usersTable, 1) + }) + + t.Run("resend replaces the unused token and is rate limited without a new token", func(t *testing.T) { + reset(t) + requests := len(harness.fixture.Requests()) + const email = "resend.candidate@example.com" + requireAccepted(t, harness.register(t, email, "candidate", "")) + assertRowCount(ctx, t, harness.pool, emailTokensTable, 1) + + // Inside the minimum interval: 429 with the wait, and no new token. + limited := harness.resend(t, email) + requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited") + requireRetryWithinInterval(t, limited) + assertRowCount(ctx, t, harness.pool, emailTokensTable, 1) + + // Within the daily limit: every resend replaces the previous token. + for sent := 2; sent <= registrationDailyLimit; sent++ { + time.Sleep(registrationMinInterval + 100*time.Millisecond) + requireAccepted(t, harness.resend(t, email)) + assertRowCount(ctx, t, harness.pool, emailTokensTable, sent) + if active := harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NULL AND consumed_at IS NULL`); active != 1 { + t.Fatalf("after resend %d: %d unused tokens, want 1", sent, active) + } + } + + // A resend keeps the credentials of the registration it resends for on + // its new token; every invalidated token keeps none. + if harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE pending_password_hash IS NOT NULL`) != 1 || + harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NOT NULL AND pending_password_hash IS NOT NULL`) != 0 || + harness.count(ctx, t, `SELECT count(*) FROM email_tokens AS token JOIN users ON users.id = token.user_id + WHERE token.invalidated_at IS NULL AND token.pending_password_hash = users.password_hash`) != 1 { + t.Fatal("resent tokens do not carry the pending credentials of the registration") + } + + // Over the daily limit: 429 with a long wait and no new token. + time.Sleep(registrationMinInterval + 100*time.Millisecond) + capped := harness.resend(t, email) + requireProblemStatus(t, capped, http.StatusTooManyRequests, "rate_limited") + if wait, err := strconv.Atoi(capped.retryAfter); err != nil || wait <= int(registrationMinInterval/time.Second) { + t.Fatalf("Retry-After over the daily limit = %q, want the wait until the window ends", capped.retryAfter) + } + assertRowCount(ctx, t, harness.pool, emailTokensTable, registrationDailyLimit) + + // Only the message of the last token is current; the others are + // cancelled by the worker, and the message goes through the fixture. + harness.drain(ctx, t) + sent := harness.fixture.Requests()[requests:] + if len(sent) != 1 || !slices.Equal(sent[0].To, []string{email}) { + t.Fatalf("fixture received %d messages, want exactly the one of the current token: %v", len(sent), sent) + } + var lastHash []byte + if err := harness.pool.QueryRow(ctx, `SELECT token_hash FROM email_tokens WHERE invalidated_at IS NULL`).Scan(&lastHash); err != nil { + t.Fatalf("read the current token: %v", err) + } + link := verificationLinkToken.FindStringSubmatch(sent[0].Text) + sum := sha256.Sum256([]byte(link[1])) + if link == nil || !bytes.Equal(sum[:], lastHash) { + t.Fatal("the delivered link is not the one of the current token") + } + if cancelled := harness.count(ctx, t, `SELECT count(*) FROM deliveries WHERE status = 'cancelled'`); cancelled != registrationDailyLimit-1 { + t.Fatalf("%d cancelled deliveries, want %d", cancelled, registrationDailyLimit-1) + } + harness.assertLogsHoldNoSecrets(t, "resend.candidate", link[1]) + }) + + t.Run("resend answers an unknown and a verified address like an unverified one", func(t *testing.T) { + reset(t) + requireAccepted(t, harness.register(t, "pending@example.com", "candidate", "")) + requireAccepted(t, harness.register(t, "done@example.com", "candidate", "")) + harness.exec(ctx, t, `UPDATE users SET email_verified_at = $1 WHERE email_normalized = 'done@example.com'`, harness.clock.Now()) + time.Sleep(registrationMinInterval + 100*time.Millisecond) + tokens := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) + + pending := harness.resend(t, "pending@example.com") + unknown := harness.resend(t, "nobody@example.com") + verified := harness.resend(t, "done@example.com") + requireAccepted(t, pending) + if unknown != pending || verified != pending { + t.Fatalf("answers differ: pending %+v, unknown %+v, verified %+v", pending, unknown, verified) + } + if got := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`); got != tokens+1 { + t.Fatalf("%d tokens, want %d: only the unverified account gets one", got, tokens+1) + } + assertRowCount(ctx, t, harness.pool, usersTable, 2) + + // The limit does not depend on the account either: a never + // registered address is refused on the same schedule. + for _, email := range []string{"pending@example.com", "nobody@example.com", "done@example.com"} { + response := harness.resend(t, email) + requireProblemStatus(t, response, http.StatusTooManyRequests, "rate_limited") + requireRetryWithinInterval(t, response) + } + }) + + t.Run("a validation error does not consume the limit", func(t *testing.T) { + reset(t) + bad := harness.registerBody(t, registrationBody("not-an-email", "candidate", registrationPassword, registrationC1), "") + requireProblemStatus(t, bad, http.StatusBadRequest, "validation_failed") + short := harness.registerBody(t, registrationBody("short.password@example.com", "candidate", "too short", registrationC1), "") + requireProblemStatus(t, short, http.StatusBadRequest, "validation_failed") + requireAccepted(t, harness.register(t, "short.password@example.com", "candidate", "")) + }) +} + +func TestRegistrationClientLimit(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 2) + harness.truncate(ctx, t) + + // The usecase counts a request with a client key against the per-client + // rule; the handler supplies the key from the resolved network address. + registration := harness.registration + for index, email := range []string{"client.one@example.com", "client.two@example.com", "client.three@example.com"} { + err := registration.Register(ctx, identity.RegisterCommand{ + IdempotencyKey: "client-key-" + email, Email: email, Password: registrationPassword, + Scenario: "candidate", ConsentTextVersion: "c1-2026-10-01", ClientKey: "203.0.113.9", + }) + var limited *identity.RateLimitedError + switch { + case index < 2 && err != nil: + t.Fatalf("registration %d error = %v, want accepted", index+1, err) + case index == 2 && !errors.As(err, &limited): + t.Fatalf("registration 3 error = %v, want *RateLimitedError", err) + } + } + assertRowCount(ctx, t, harness.pool, usersTable, 2) +} diff --git a/backend/internal/adapter/primary/http/candidate_profile_contract_test.go b/backend/internal/adapter/primary/http/candidate_profile_contract_test.go index f91a2af..ef7651c 100644 --- a/backend/internal/adapter/primary/http/candidate_profile_contract_test.go +++ b/backend/internal/adapter/primary/http/candidate_profile_contract_test.go @@ -411,7 +411,7 @@ func TestProfileSchemaValidationPrecedesImplementation(t *testing.T) { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/internal/adapter/primary/http/identity_registration_test.go b/backend/internal/adapter/primary/http/identity_registration_test.go new file mode 100644 index 0000000..ba274cd --- /dev/null +++ b/backend/internal/adapter/primary/http/identity_registration_test.go @@ -0,0 +1,120 @@ +package httpadapter + +import ( + "context" + "errors" + "log/slog" + "net/http" + "testing" + "time" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/usecase/identity" +) + +const resendPath = "/api/v1/identity/email-verification-requests" + +// scriptedRegistration answers every call with its fixed error and records +// the last commands. +type scriptedRegistration struct { + err error + register identity.RegisterCommand + resend identity.ResendCommand +} + +func (registration *scriptedRegistration) Register(_ context.Context, command identity.RegisterCommand) error { + registration.register = command + return registration.err +} + +func (registration *scriptedRegistration) ResendVerification(_ context.Context, command identity.ResendCommand) error { + registration.resend = command + return registration.err +} + +func newIdentityRouter(t *testing.T, registration v1.AccountRegistration) http.Handler { + t.Helper() + logger := slog.New(slog.DiscardHandler) + healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) + handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(v1.NewIdentityHandler(registration))) + return newTestRouterWithAPI(t, healthHandler, handler, logger) +} + +func TestRegistrationOperationsMapUsecaseOutcomes(t *testing.T) { + registerRequest := identityRequest{ + method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent), + headers: map[string]string{"Idempotency-Key": testIdempotencyKey}, + } + resendRequest := identityRequest{method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`} + staleConsent := &identity.InvalidFieldError{Pointer: "/consent_c1/text_version", Err: errors.New("stale")} + for _, test := range []struct { + name string + request identityRequest + err error + statusCode int + code api.ProblemCode + pointer string + retryAfter string + }{ + {name: "register accepted", request: registerRequest, statusCode: http.StatusAccepted}, + {name: "resend accepted", request: resendRequest, statusCode: http.StatusAccepted}, + { + name: "register stale consent version", request: registerRequest, err: staleConsent, + statusCode: http.StatusBadRequest, code: api.ProblemCodeValidationFailed, pointer: "/consent_c1/text_version", + }, + { + name: "register reused key", request: registerRequest, err: identity.ErrIdempotencyKeyReused, + statusCode: http.StatusUnprocessableEntity, code: api.ProblemCodeIdempotencyKeyReused, + }, + { + name: "register limited", request: registerRequest, err: &identity.RateLimitedError{RetryAfter: 1500 * time.Millisecond}, + statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "2", + }, + { + name: "resend limited", request: resendRequest, err: &identity.RateLimitedError{RetryAfter: 59 * time.Second}, + statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "59", + }, + { + name: "resend internal failure", request: resendRequest, err: errors.New("database unavailable"), + statusCode: http.StatusInternalServerError, code: api.ProblemCodeInternal, + }, + } { + t.Run(test.name, func(t *testing.T) { + response := serveIdentityRequest(t, newIdentityRouter(t, &scriptedRegistration{err: test.err}), test.request) + if test.statusCode == http.StatusAccepted { + if response.Code != http.StatusAccepted || response.Body.String() != `{"status":"accepted"}` { + t.Fatalf("response = %d %s, want the neutral 202", response.Code, response.Body.String()) + } + return + } + body := requireProblem(t, response, test.statusCode, test.code) + if test.pointer != "" && (len(body.Errors) != 1 || body.Errors[0].Pointer != test.pointer) { + t.Fatalf("errors = %v, want one error at %s", body.Errors, test.pointer) + } + if got := response.Header().Get("Retry-After"); got != test.retryAfter { + t.Fatalf("Retry-After = %q, want %q", got, test.retryAfter) + } + }) + } +} + +func TestRegistrationPassesTheRequestToTheUsecase(t *testing.T) { + registration := &scriptedRegistration{} + router := newIdentityRouter(t, registration) + response := serveIdentityRequest(t, router, identityRequest{ + method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent), + headers: map[string]string{"Idempotency-Key": testIdempotencyKey}, + }) + if response.Code != http.StatusAccepted { + t.Fatalf("status = %d: %s", response.Code, response.Body.String()) + } + want := identity.RegisterCommand{ + IdempotencyKey: testIdempotencyKey, Email: "candidate@example.com", Password: validPassword, + Scenario: "candidate", ConsentTextVersion: "c1-2026-10-01", ClientKey: "192.0.2.1", + } + if registration.register != want { + t.Fatalf("command = %+v, want %+v", registration.register, want) + } +} diff --git a/backend/internal/adapter/primary/http/metrics_test.go b/backend/internal/adapter/primary/http/metrics_test.go index 9e9035a..4e99340 100644 --- a/backend/internal/adapter/primary/http/metrics_test.go +++ b/backend/internal/adapter/primary/http/metrics_test.go @@ -27,7 +27,7 @@ func newMetricsTestRouter(t *testing.T, apiHandler func(*v1.HealthHandler, *prob healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) responder := problem.NewResponder(logger) collector := metrics.New() - router, err := NewRouter(healthHandler, apiHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, collector, logger) + router, err := NewRouter(healthHandler, apiHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, collector, logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/internal/adapter/primary/http/middleware/clientip.go b/backend/internal/adapter/primary/http/middleware/clientip.go index 1c159b6..cc9ba00 100644 --- a/backend/internal/adapter/primary/http/middleware/clientip.go +++ b/backend/internal/adapter/primary/http/middleware/clientip.go @@ -73,8 +73,10 @@ func ClientIP(trusted []netip.Prefix) func(http.Handler) http.Handler { // ClientAddr returns the client address that the ClientIP middleware stored. // The second result is false when the middleware did not run or the peer -// address was not an IP address; a caller must then fail closed, for example -// by sharing one limiter bucket, instead of skipping its limit. +// address was not an IP address. A caller then skips its per-client limit +// and keeps its other limits: a shared "unknown" bucket would let one client +// lock out everyone, which is the worse failure than a missing per-client +// brake. The registration handler does this and counts nothing for it. func ClientAddr(ctx context.Context) (netip.Addr, bool) { addr, ok := ctx.Value(clientAddrKey{}).(netip.Addr) return addr, ok && addr.IsValid() diff --git a/backend/internal/adapter/primary/http/organization_test.go b/backend/internal/adapter/primary/http/organization_test.go index 2e0b00e..9547ccc 100644 --- a/backend/internal/adapter/primary/http/organization_test.go +++ b/backend/internal/adapter/primary/http/organization_test.go @@ -275,7 +275,7 @@ func TestOrganizationSchemaValidationPrecedesImplementation(t *testing.T) { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/internal/adapter/primary/http/problem/field.go b/backend/internal/adapter/primary/http/problem/field.go new file mode 100644 index 0000000..eae13dd --- /dev/null +++ b/backend/internal/adapter/primary/http/problem/field.go @@ -0,0 +1,22 @@ +package problem + +import ( + "context" + + "lincodex/backend/internal/adapter/primary/http/api" +) + +// InvalidField is the validation_failed problem for one invalid value that +// only the application can detect, such as a stale consent text version. The +// pointer is a JSON Pointer into the location of the value; the body of the +// problem never echoes the value. +func InvalidField(ctx context.Context, location api.ProblemFieldLocation, pointer string) *api.ProblemStatusCode { + return validationProblem(ctx, []api.ProblemFieldError{fieldError(location, pointer, fieldCodeInvalid)}) +} + +// RateLimited is the 429 problem with the wait before a retry. The wait is +// rounded up to whole seconds, at least one. +func RateLimited(ctx context.Context, waitSeconds int32) *api.TooManyRequestsHeaders { + problem := New(ctx, api.ProblemCodeRateLimited) + return &api.TooManyRequestsHeaders{RetryAfter: api.NewOptInt32(max(waitSeconds, 1)), Response: problem.Response} +} diff --git a/backend/internal/adapter/primary/http/request_log_test.go b/backend/internal/adapter/primary/http/request_log_test.go index 107bb47..56e121a 100644 --- a/backend/internal/adapter/primary/http/request_log_test.go +++ b/backend/internal/adapter/primary/http/request_log_test.go @@ -27,7 +27,7 @@ func TestRequestLogNamesTheRouteTemplateAndNoRequestData(t *testing.T) { logger := slog.New(slog.NewJSONHandler(&logs, nil)) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) responder := problem.NewResponder(logger) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/internal/adapter/primary/http/router.go b/backend/internal/adapter/primary/http/router.go index dff5994..88ce0a9 100644 --- a/backend/internal/adapter/primary/http/router.go +++ b/backend/internal/adapter/primary/http/router.go @@ -4,6 +4,7 @@ import ( "fmt" "log/slog" "net/http" + "net/netip" "github.com/go-chi/chi/v5" kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware" @@ -27,7 +28,8 @@ const ( // unknown routes under /api to 404, unsupported methods to 405, and any other // server error or panic to 500 without exposing its text. Operation errors go // through apiHandler.NewError. security decides every operation that requires -// a session; the generated server answers its rejection, and a request +// a session; trustedProxies are the reverse proxies whose X-Forwarded-For +// is believed; the generated server answers its rejection, and a request // without the session cookie, with 401 unauthenticated through NewError. func NewRouter( health *v1.HealthHandler, @@ -36,6 +38,7 @@ func NewRouter( problems *problem.Responder, collector httpmiddleware.RequestMetrics, logger *slog.Logger, + trustedProxies []netip.Prefix, ) (http.Handler, error) { apiServer, err := apiadapter.NewServer( apiHandler, @@ -55,6 +58,9 @@ func NewRouter( // same route template as the metrics, never the raw path or query. resolveRoute := operationRoute(apiServer) router.Use(kitmiddleware.RequestID()) + // 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)) router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath)) router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute)) router.Group(func(operational chi.Router) { diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index f1ce04f..0ad31cd 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -393,7 +393,7 @@ func TestGeneratedServerSecurityOrder(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) security := &recordingSecurity{} - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -503,7 +503,7 @@ func TestQuestionnaireSchemaValidationPrecedesImplementation(t *testing.T) { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -715,7 +715,7 @@ func TestAssessmentSchemaValidationPrecedesImplementation(t *testing.T) { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -1010,7 +1010,7 @@ func TestNeedSchemaValidationPrecedesImplementation(t *testing.T) { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -1337,7 +1337,7 @@ func TestSupportCaseSchemaValidationPrecedesImplementation(t *testing.T) { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -1803,7 +1803,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -1910,7 +1910,7 @@ func TestConsentSchemaValidationPrecedesImplementation(t *testing.T) { t.Run(test.name, func(t *testing.T) { logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) - router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -2021,7 +2021,7 @@ func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) { getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) }, } recorder := &requestRecorder{} - router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger) + router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -2198,7 +2198,7 @@ func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler { func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler { t.Helper() - router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger) + router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } @@ -2210,7 +2210,7 @@ func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getH logger := slog.New(slog.DiscardHandler) healthHandler := newTestHealthHandler(func(context.Context) error { return nil }) handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz} - router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger) + router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger, nil) if err != nil { t.Fatalf("NewRouter() error = %v", err) } diff --git a/backend/internal/adapter/primary/http/v1/handler.go b/backend/internal/adapter/primary/http/v1/handler.go index ef70749..a481fc0 100644 --- a/backend/internal/adapter/primary/http/v1/handler.go +++ b/backend/internal/adapter/primary/http/v1/handler.go @@ -32,19 +32,55 @@ type Handler struct { api.UnimplementedHandler health *HealthHandler + identity *IdentityHandler problems *problem.Responder } var _ api.Handler = (*Handler)(nil) -func NewHandler(health *HealthHandler, problems *problem.Responder) *Handler { - return &Handler{health: health, problems: problems} +// 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) +} + // 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/identity.go b/backend/internal/adapter/primary/http/v1/identity.go new file mode 100644 index 0000000..019479f --- /dev/null +++ b/backend/internal/adapter/primary/http/v1/identity.go @@ -0,0 +1,119 @@ +package v1 + +import ( + "context" + "errors" + "math" + "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" +) + +// AccountRegistration is what IdentityHandler needs from the registration +// usecase. +type AccountRegistration interface { + Register(ctx context.Context, command identity.RegisterCommand) error + ResendVerification(ctx context.Context, command identity.ResendCommand) error +} + +// IdentityHandler serves the anonymous registration operations. Both answer +// the same neutral 202 whatever the state of the address; see the contract. +type IdentityHandler struct { + registration AccountRegistration +} + +func NewIdentityHandler(registration AccountRegistration) *IdentityHandler { + return &IdentityHandler{registration: registration} +} + +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) { + 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 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/secondary/postgres/idempotency.go b/backend/internal/adapter/secondary/postgres/idempotency.go new file mode 100644 index 0000000..0ec07b9 --- /dev/null +++ b/backend/internal/adapter/secondary/postgres/idempotency.go @@ -0,0 +1,107 @@ +package postgres + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/jackc/pgx/v5" + + "lincodex/backend/internal/adapter/secondary/postgres/sqlc" + "lincodex/backend/internal/port/outbound" +) + +type idempotencyRepository struct { + queries *sqlc.Queries +} + +func (repository idempotencyRepository) Reserve( + ctx context.Context, + record outbound.IdempotencyRecord, +) (outbound.IdempotencyRecord, bool, error) { + const location = "idempotencyRepository.Reserve" + if err := requireTime(location, record.CreatedAt, outbound.ErrIdempotencyRecordNotFound); err != nil { + return outbound.IdempotencyRecord{}, false, err + } + if !record.ExpiresAt.After(record.CreatedAt) { + return outbound.IdempotencyRecord{}, false, errors.New(location + " - expiry must be after creation") + } + row, err := repository.queries.ReserveIdempotencyRecord(ctx, sqlc.ReserveIdempotencyRecordParams{ + ScopeHash: record.Scope[:], + Fingerprint: record.Fingerprint[:], + CreatedAt: pgTime(record.CreatedAt), + ExpiresAt: pgTime(record.ExpiresAt), + }) + if err == nil { + return idempotencyFromRow(location, row.ScopeHash, row.Fingerprint, row.CreatedAt.Time, row.ExpiresAt.Time, true) + } + if !isNoRows(err) { + return outbound.IdempotencyRecord{}, false, fmt.Errorf("%s - store record: %w", location, mapIdentityError(err)) + } + // A live record with the scope exists and was left as it is. It is + // visible now: a concurrent writer committed before this statement + // returned. + existing, err := repository.Find(ctx, record.Scope, record.CreatedAt) + if err != nil { + return outbound.IdempotencyRecord{}, false, fmt.Errorf("%s - read live record: %w", location, err) + } + return existing, false, nil +} + +func (repository idempotencyRepository) Find( + ctx context.Context, + scope [outbound.IdempotencyDigestSize]byte, + at time.Time, +) (outbound.IdempotencyRecord, error) { + const location = "idempotencyRepository.Find" + if err := requireTime(location, at, outbound.ErrIdempotencyRecordNotFound); err != nil { + return outbound.IdempotencyRecord{}, err + } + row, err := repository.queries.GetLiveIdempotencyRecord(ctx, sqlc.GetLiveIdempotencyRecordParams{ + ScopeHash: scope[:], + At: pgTime(at), + }) + if err != nil { + return outbound.IdempotencyRecord{}, fmt.Errorf("%s - select record: %w", location, mapNoRows(err, outbound.ErrIdempotencyRecordNotFound)) + } + record, _, err := idempotencyFromRow(location, row.ScopeHash, row.Fingerprint, row.CreatedAt.Time, row.ExpiresAt.Time, false) + return record, err +} + +func (repository idempotencyRepository) PurgeExpired(ctx context.Context, at time.Time, limit int32) (int64, error) { + const location = "idempotencyRepository.PurgeExpired" + if err := requireTime(location, at, outbound.ErrIdempotencyRecordNotFound); err != nil { + return 0, err + } + if limit <= 0 { + return 0, errors.New(location + " - limit must be positive") + } + deleted, err := repository.queries.PurgeExpiredIdempotencyRecords(ctx, sqlc.PurgeExpiredIdempotencyRecordsParams{ + At: pgTime(at), + BatchLimit: limit, + }) + if err != nil { + return 0, fmt.Errorf("%s - delete records: %w", location, mapIdentityError(err)) + } + return deleted, nil +} + +func idempotencyFromRow( + location string, + scope, fingerprint []byte, + createdAt, expiresAt time.Time, + created bool, +) (outbound.IdempotencyRecord, bool, error) { + record := outbound.IdempotencyRecord{CreatedAt: createdAt, ExpiresAt: expiresAt} + if len(scope) != outbound.IdempotencyDigestSize || len(fingerprint) != outbound.IdempotencyDigestSize { + return outbound.IdempotencyRecord{}, false, errors.New(location + " - stored digest has an unexpected size") + } + copy(record.Scope[:], scope) + copy(record.Fingerprint[:], fingerprint) + return record, created, nil +} + +func isNoRows(err error) bool { + return errors.Is(err, pgx.ErrNoRows) +} diff --git a/backend/internal/adapter/secondary/postgres/identity.go b/backend/internal/adapter/secondary/postgres/identity.go index 2f461e7..88ff7cd 100644 --- a/backend/internal/adapter/secondary/postgres/identity.go +++ b/backend/internal/adapter/secondary/postgres/identity.go @@ -97,6 +97,14 @@ func (store *IdentityStore) Sessions() outbound.SessionRepository { return sessionRepository{queries: store.queries} } +func (store *IdentityStore) IdempotencyRecords() outbound.IdempotencyRepository { + return idempotencyRepository{queries: store.queries} +} + +func (unit *UnitOfWork) IdempotencyRecords() outbound.IdempotencyRepository { + return idempotencyRepository{queries: unit.queries} +} + func (unit *UnitOfWork) Users() outbound.UserRepository { return userRepository{queries: unit.queries} } @@ -226,6 +234,26 @@ func (repository userRepository) UpdateRegistration(ctx context.Context, user do return userFromRow(sqlc.User(row)) } +func (repository userRepository) AdvanceRegistration( + ctx context.Context, + id uuid.UUID, + expectedVersion int64, + at time.Time, +) (domain.User, error) { + if err := requireTime("userRepository.AdvanceRegistration", at, domain.ErrInvalidUser); err != nil { + return domain.User{}, err + } + row, err := repository.queries.AdvanceUserRegistration(ctx, sqlc.AdvanceUserRegistrationParams{ + ID: pgUUID(id), + ExpectedVersion: expectedVersion, + RegisteredAt: pgTime(at), + }) + if err != nil { + return domain.User{}, fmt.Errorf("userRepository.AdvanceRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict)) + } + return userFromRow(sqlc.User(row)) +} + func (repository userRepository) MarkEmailVerified( ctx context.Context, id uuid.UUID, @@ -318,7 +346,7 @@ func (repository emailTokenRepository) Insert(ctx context.Context, token domain. if token.ID == uuid.Nil || token.TokenHash.IsZero() { return fmt.Errorf("emailTokenRepository.Insert - token was not built by domain.NewEmailToken: %w", domain.ErrInvalidEmailToken) } - err := repository.queries.InsertEmailToken(ctx, sqlc.InsertEmailTokenParams{ + params := sqlc.InsertEmailTokenParams{ ID: pgUUID(token.ID), UserID: pgUUID(token.UserID), Purpose: string(token.Purpose), @@ -326,13 +354,62 @@ func (repository emailTokenRepository) Insert(ctx context.Context, token domain. RegistrationVersion: token.RegistrationVersion, CreatedAt: pgTime(token.CreatedAt), ExpiresAt: pgTime(token.ExpiresAt), - }) - if err != nil { + } + if pending := token.Pending; pending != nil { + params.PendingPasswordHash = pgtype.Text{String: pending.PasswordHash.PHC(), Valid: true} + params.PendingScenario = pgtype.Text{String: string(pending.Scenario), Valid: true} + params.PendingOnboardingStep = pgtype.Text{String: string(pending.OnboardingStep), Valid: true} + } + if err := repository.queries.InsertEmailToken(ctx, params); err != nil { return fmt.Errorf("emailTokenRepository.Insert - insert email token: %w", mapIdentityError(err)) } return nil } +func (repository emailTokenRepository) LatestPending( + ctx context.Context, + userID uuid.UUID, + registrationVersion int64, +) (domain.PendingRegistration, bool, error) { + row, err := repository.queries.GetLatestPendingRegistration(ctx, sqlc.GetLatestPendingRegistrationParams{ + UserID: pgUUID(userID), + Purpose: string(domain.EmailTokenPurposeEmailVerification), + RegistrationVersion: registrationVersion, + }) + if errors.Is(err, pgx.ErrNoRows) { + return domain.PendingRegistration{}, false, nil + } + if err != nil { + return domain.PendingRegistration{}, false, fmt.Errorf("emailTokenRepository.LatestPending - select pending registration: %w", mapIdentityError(err)) + } + pending, err := pendingFromColumns(row.PendingPasswordHash, row.PendingScenario, row.PendingOnboardingStep) + if err != nil { + return domain.PendingRegistration{}, false, err + } + return *pending, true, nil +} + +// pendingFromColumns decodes the pending credentials of a token row; nil when +// the token carries none. +func pendingFromColumns(hash, scenario, step pgtype.Text) (*domain.PendingRegistration, error) { + if !hash.Valid { + return nil, nil + } + passwordHash, err := domain.NewPasswordHash(hash.String) + if err != nil { + return nil, fmt.Errorf("postgres.pendingFromColumns - decode password hash: %w", err) + } + parsedScenario, err := domain.ParseScenario(scenario.String) + if err != nil { + return nil, fmt.Errorf("postgres.pendingFromColumns - decode scenario: %w", err) + } + parsedStep, err := domain.ParseOnboardingStep(step.String) + if err != nil { + return nil, fmt.Errorf("postgres.pendingFromColumns - decode onboarding step: %w", err) + } + return &domain.PendingRegistration{PasswordHash: passwordHash, Scenario: parsedScenario, OnboardingStep: parsedStep}, nil +} + func (repository emailTokenRepository) InvalidateActive( ctx context.Context, userID uuid.UUID, @@ -416,7 +493,12 @@ func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) { if err != nil { return domain.EmailToken{}, err } + pending, err := pendingFromColumns(row.PendingPasswordHash, row.PendingScenario, row.PendingOnboardingStep) + if err != nil { + return domain.EmailToken{}, err + } return domain.EmailToken{ + Pending: pending, ID: uuid.UUID(row.ID.Bytes), UserID: uuid.UUID(row.UserID.Bytes), Purpose: purpose, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go index 03d2005..750b072 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go @@ -11,6 +11,104 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const advanceUserRegistration = `-- name: AdvanceUserRegistration :one +WITH updated AS ( + UPDATE users + SET + registration_version = registration_version + 1, + last_registered_at = $1, + updated_at = $1, + version = version + 1 + WHERE + users.id = $2 + AND users.version = $3 + AND users.email_verified_at IS NULL + RETURNING + users.id, + users.email, + users.email_normalized, + users.password_hash, + users.scenario, + users.onboarding_step, + users.email_verified_at, + users.registration_version, + users.last_registered_at, + users.version, + users.created_at, + users.updated_at +), + +discarded_consent AS ( + DELETE FROM consent_records + USING updated + WHERE + consent_records.subject_id = updated.id + AND consent_records.purpose = 'c1' + AND consent_records.source = 'registration' +) + +SELECT + updated.id, + updated.email, + updated.email_normalized, + updated.password_hash, + updated.scenario, + updated.onboarding_step, + updated.email_verified_at, + updated.registration_version, + updated.last_registered_at, + updated.version, + updated.created_at, + updated.updated_at +FROM updated +` + +type AdvanceUserRegistrationParams struct { + RegisteredAt pgtype.Timestamptz + ID pgtype.UUID + ExpectedVersion int64 +} + +type AdvanceUserRegistrationRow struct { + ID pgtype.UUID + Email string + EmailNormalized string + PasswordHash string + Scenario string + OnboardingStep string + EmailVerifiedAt pgtype.Timestamptz + RegistrationVersion int64 + LastRegisteredAt pgtype.Timestamptz + Version int64 + CreatedAt pgtype.Timestamptz + UpdatedAt pgtype.Timestamptz +} + +// Starts a new registration of an unverified account without touching its +// credentials, scenario, or onboarding step: the new registration carries +// them on its verification token. Advances the registration version, which +// ends every earlier token, and deletes the registration C1 of the earlier +// registrant like UpdateUserRegistration does. +func (q *Queries) AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error) { + row := q.db.QueryRow(ctx, advanceUserRegistration, arg.RegisteredAt, arg.ID, arg.ExpectedVersion) + var i AdvanceUserRegistrationRow + err := row.Scan( + &i.ID, + &i.Email, + &i.EmailNormalized, + &i.PasswordHash, + &i.Scenario, + &i.OnboardingStep, + &i.EmailVerifiedAt, + &i.RegistrationVersion, + &i.LastRegisteredAt, + &i.Version, + &i.CreatedAt, + &i.UpdatedAt, + ) + return i, err +} + const consumeEmailToken = `-- name: ConsumeEmailToken :one UPDATE email_tokens AS token SET consumed_at = $1 @@ -32,7 +130,10 @@ RETURNING token.created_at, token.expires_at, token.consumed_at, - token.invalidated_at + token.invalidated_at, + token.pending_password_hash, + token.pending_scenario, + token.pending_onboarding_step ` type ConsumeEmailTokenParams struct { @@ -63,6 +164,9 @@ func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenPa &i.ExpiresAt, &i.ConsumedAt, &i.InvalidatedAt, + &i.PendingPasswordHash, + &i.PendingScenario, + &i.PendingOnboardingStep, ) return i, err } @@ -273,6 +377,71 @@ func (q *Queries) GetEmailTokenState(ctx context.Context, arg GetEmailTokenState return i, err } +const getLatestPendingRegistration = `-- name: GetLatestPendingRegistration :one +SELECT + pending_password_hash, + pending_scenario, + pending_onboarding_step +FROM email_tokens +WHERE + user_id = $1 + AND purpose = $2 + AND registration_version = $3 + AND pending_password_hash IS NOT NULL +ORDER BY created_at DESC, id DESC +LIMIT 1 +` + +type GetLatestPendingRegistrationParams struct { + UserID pgtype.UUID + Purpose string + RegistrationVersion int64 +} + +type GetLatestPendingRegistrationRow struct { + PendingPasswordHash pgtype.Text + PendingScenario pgtype.Text + PendingOnboardingStep pgtype.Text +} + +// The pending credentials of the newest token of a registration, for a +// resend, which issues its token with the same credentials. +func (q *Queries) GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error) { + row := q.db.QueryRow(ctx, getLatestPendingRegistration, arg.UserID, arg.Purpose, arg.RegistrationVersion) + var i GetLatestPendingRegistrationRow + err := row.Scan(&i.PendingPasswordHash, &i.PendingScenario, &i.PendingOnboardingStep) + return i, err +} + +const getLiveIdempotencyRecord = `-- name: GetLiveIdempotencyRecord :one +SELECT + scope_hash, + fingerprint, + created_at, + expires_at +FROM idempotency_records +WHERE + scope_hash = $1 + AND expires_at > $2 +` + +type GetLiveIdempotencyRecordParams struct { + ScopeHash []byte + At pgtype.Timestamptz +} + +func (q *Queries) GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error) { + row := q.db.QueryRow(ctx, getLiveIdempotencyRecord, arg.ScopeHash, arg.At) + var i IdempotencyRecord + err := row.Scan( + &i.ScopeHash, + &i.Fingerprint, + &i.CreatedAt, + &i.ExpiresAt, + ) + return i, err +} + const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one SELECT id, @@ -357,7 +526,10 @@ INSERT INTO email_tokens ( token_hash, registration_version, created_at, - expires_at + expires_at, + pending_password_hash, + pending_scenario, + pending_onboarding_step ) VALUES ( $1, $2, @@ -365,18 +537,24 @@ INSERT INTO email_tokens ( $4, $5, $6, - $7 + $7, + $8, + $9, + $10 ) ` type InsertEmailTokenParams struct { - ID pgtype.UUID - UserID pgtype.UUID - Purpose string - TokenHash []byte - RegistrationVersion int64 - CreatedAt pgtype.Timestamptz - ExpiresAt pgtype.Timestamptz + ID pgtype.UUID + UserID pgtype.UUID + Purpose string + TokenHash []byte + RegistrationVersion int64 + CreatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz + PendingPasswordHash pgtype.Text + PendingScenario pgtype.Text + PendingOnboardingStep pgtype.Text } func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error { @@ -388,6 +566,9 @@ func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenPara arg.RegistrationVersion, arg.CreatedAt, arg.ExpiresAt, + arg.PendingPasswordHash, + arg.PendingScenario, + arg.PendingOnboardingStep, ) return err } @@ -496,7 +677,12 @@ func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) error { const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execrows UPDATE email_tokens -SET invalidated_at = $1 +SET + invalidated_at = $1, + -- An invalidated token keeps no password hash: it can never be confirmed. + pending_password_hash = NULL, + pending_scenario = NULL, + pending_onboarding_step = NULL WHERE user_id = $2 AND purpose = $3 @@ -571,6 +757,83 @@ func (q *Queries) MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVe return i, err } +const purgeExpiredIdempotencyRecords = `-- name: PurgeExpiredIdempotencyRecords :execrows +DELETE FROM idempotency_records +WHERE scope_hash IN ( + SELECT stale.scope_hash + FROM idempotency_records AS stale + WHERE stale.expires_at <= $1 + ORDER BY stale.expires_at + LIMIT $2 + FOR UPDATE SKIP LOCKED +) +` + +type PurgeExpiredIdempotencyRecordsParams struct { + At pgtype.Timestamptz + BatchLimit int32 +} + +// Deletes at most batch_limit expired records. Locked rows are skipped, so +// the statement never waits for a concurrent reservation. +func (q *Queries) PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error) { + result, err := q.db.Exec(ctx, purgeExpiredIdempotencyRecords, arg.At, arg.BatchLimit) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const reserveIdempotencyRecord = `-- name: ReserveIdempotencyRecord :one +INSERT INTO idempotency_records ( + scope_hash, + fingerprint, + created_at, + expires_at +) VALUES ( + $1, + $2, + $3, + $4 +) +ON CONFLICT (scope_hash) DO UPDATE +SET + fingerprint = excluded.fingerprint, + created_at = excluded.created_at, + expires_at = excluded.expires_at +WHERE idempotency_records.expires_at <= excluded.created_at +RETURNING scope_hash, fingerprint, created_at, expires_at +` + +type ReserveIdempotencyRecordParams struct { + ScopeHash []byte + Fingerprint []byte + CreatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz +} + +// Stores the replay record of a command. A record whose retention has passed +// is replaced, so the key is accepted as new after the retention. A live +// record is left as it is and nothing is returned; the caller then reads it +// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait +// on the row of the first one until its transaction ends. +func (q *Queries) ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error) { + row := q.db.QueryRow(ctx, reserveIdempotencyRecord, + arg.ScopeHash, + arg.Fingerprint, + arg.CreatedAt, + arg.ExpiresAt, + ) + var i IdempotencyRecord + err := row.Scan( + &i.ScopeHash, + &i.Fingerprint, + &i.CreatedAt, + &i.ExpiresAt, + ) + return i, err +} + const revokeSession = `-- name: RevokeSession :execrows UPDATE sessions SET revoked_at = $1 diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index c88e8bf..8e6f625 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -163,15 +163,25 @@ type DeliveryAttempt struct { } type EmailToken struct { - ID pgtype.UUID - UserID pgtype.UUID - Purpose string - TokenHash []byte - RegistrationVersion int64 - CreatedAt pgtype.Timestamptz - ExpiresAt pgtype.Timestamptz - ConsumedAt pgtype.Timestamptz - InvalidatedAt pgtype.Timestamptz + ID pgtype.UUID + UserID pgtype.UUID + Purpose string + TokenHash []byte + RegistrationVersion int64 + CreatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz + ConsumedAt pgtype.Timestamptz + InvalidatedAt pgtype.Timestamptz + PendingPasswordHash pgtype.Text + PendingScenario pgtype.Text + PendingOnboardingStep pgtype.Text +} + +type IdempotencyRecord struct { + ScopeHash []byte + Fingerprint []byte + CreatedAt pgtype.Timestamptz + ExpiresAt pgtype.Timestamptz } type MailQuotaReservation struct { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 4a128e2..b65af98 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -22,6 +22,12 @@ type Querier interface { // returns for a stale version or for an account without a profile, which the // caller answers as a version conflict. AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error) + // Starts a new registration of an unverified account without touching its + // credentials, scenario, or onboarding step: the new registration carries + // them on its verification token. Advances the registration version, which + // ends every earlier token, and deletes the registration C1 of the earlier + // registrant like UpdateUserRegistration does. + AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, 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 @@ -163,7 +169,11 @@ type Querier interface { // for the account's own view of its mail. It selects no address and no // content. The recipient index narrows the scan to the account's rows. GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeliveryStatusParams) (GetLatestDeliveryStatusRow, error) + // The pending credentials of the newest token of a registration, for a + // resend, which issues its token with the same credentials. + GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error) GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error) + GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error) // Reads the usage of the day and the month window without locking. GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error) // Reads the membership of one account in one organization, in any state. @@ -366,6 +376,9 @@ type Querier interface { // the publication time set by the guard trigger. No row means the version // was not a draft any more. PublishAssessmentFamily(ctx context.Context, arg PublishAssessmentFamilyParams) (AssessmentFamily, error) + // Deletes at most batch_limit expired records. Locked rows are skipped, so + // the statement never waits for a concurrent reservation. + PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error) // Reads the profile row of an account together with every claim in one // statement, so the version and the claims come from one snapshot: a save that // commits between two separate reads could pair version N with the claims of @@ -419,6 +432,12 @@ type Querier interface { // the job did not cause the failure. The same guard as the completion // applies, one (id, attempt) pair per job. It returns the IDs it released. ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error) + // Stores the replay record of a command. A record whose retention has passed + // is replaced, so the key is accepted as new after the retention. A live + // record is left as it is and nothing is returned; the caller then reads it + // with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait + // on the row of the first one until its transaction ends. + ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error) RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error) // Revokes every unrevoked record of a purpose other than C4, superseded ones // included, and returns them. A revocation time before the grant time, from diff --git a/backend/internal/adapter/secondary/prometheus/mail.go b/backend/internal/adapter/secondary/prometheus/mail.go index 257b47e..24129de 100644 --- a/backend/internal/adapter/secondary/prometheus/mail.go +++ b/backend/internal/adapter/secondary/prometheus/mail.go @@ -39,6 +39,10 @@ type mailMetrics struct { // senderCancelled counts deliveries that the sending worker ended without // sending, by cancel reason, a closed set from the domain. senderCancelled *client.CounterVec + // identityRateLimited counts registration and resend requests that the + // identity limiter refused, by scope: address or client. No address, + // email, or key is ever a label. + identityRateLimited *client.CounterVec } // deliveryKinds and deliveryStatuses list the series that always exist, so a @@ -89,6 +93,10 @@ func newMailMetrics() mailMetrics { Name: "lincodex_mail_sender_cancelled_total", Help: "Deliveries that the mail sending worker of this process ended without sending, by cancel reason. content_invalid and processing_failed mean a broken row or a defect.", }, []string{"reason"}), + identityRateLimited: client.NewCounterVec(client.CounterOpts{ + Name: "lincodex_identity_rate_limit_refusals_total", + Help: "Registration and verification resend requests refused with 429 by the identity limiter, by scope: address (per email address) or client (per network address). A large share of client refusals hints at a broken proxy chain, where many clients share one address; a rise of address refusals can mean a targeted lockout of one address.", + }, []string{"scope"}), senderRunning: client.NewGauge(client.GaugeOpts{ Name: "lincodex_mail_sender_running", Help: "1 while the mail sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.", @@ -99,14 +107,32 @@ func newMailMetrics() mailMetrics { for _, reason := range domain.DeliveryCancelReasons() { metrics.senderCancelled.WithLabelValues(string(reason)) } + for _, scope := range []string{IdentityScopeAddress, IdentityScopeClient} { + metrics.identityRateLimited.WithLabelValues(scope) + } return metrics } +// The scopes of the identity rate limit refusal counter. +const ( + IdentityScopeAddress = "address" + IdentityScopeClient = "client" +) + +// ObserveIdentityRateLimited counts one refused identity request. A scope +// outside the two known ones counts as address, so the label stays bounded. +func (metrics *Metrics) ObserveIdentityRateLimited(scope string) { + if scope != IdentityScopeClient { + scope = IdentityScopeAddress + } + metrics.mail.identityRateLimited.WithLabelValues(scope).Inc() +} + func (mail mailMetrics) collectors() []client.Collector { return []client.Collector{ mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess, mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted, - mail.senderRunning, mail.senderCancelled, + mail.senderRunning, mail.senderCancelled, mail.identityRateLimited, } } diff --git a/backend/internal/adapter/secondary/prometheus/mail_test.go b/backend/internal/adapter/secondary/prometheus/mail_test.go index 646ab5a..26ce11c 100644 --- a/backend/internal/adapter/secondary/prometheus/mail_test.go +++ b/backend/internal/adapter/secondary/prometheus/mail_test.go @@ -39,3 +39,16 @@ func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) { t.Fatal("an arbitrary reason became a label") } } + +func TestIdentityRateLimitRefusalsAreCountedByBoundedScope(t *testing.T) { + metrics := New() + metrics.ObserveIdentityRateLimited(IdentityScopeClient) + metrics.ObserveIdentityRateLimited(IdentityScopeAddress) + metrics.ObserveIdentityRateLimited("203.0.113.9") + body := scrape(t, metrics) + requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="client"} 1`) + requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="address"} 2`) + if strings.Contains(body, "203.0.113.9") { + t.Fatal("an unknown scope became a label value") + } +} diff --git a/backend/internal/adapter/secondary/redis/ratelimit.go b/backend/internal/adapter/secondary/redis/ratelimit.go new file mode 100644 index 0000000..b41932c --- /dev/null +++ b/backend/internal/adapter/secondary/redis/ratelimit.go @@ -0,0 +1,86 @@ +package redis + +import ( + "context" + "fmt" + "strconv" + "time" + + "github.com/redis/go-redis/v9" + + "lincodex/backend/internal/port/outbound" +) + +// takeScript counts one request against every rule atomically. KEYS holds one +// counter per rule and ARGV holds the limit and the window in milliseconds of +// each rule, in the same order. It returns 0 when the request was counted and +// otherwise the milliseconds until every refusing rule admits it again; a +// refused request changes nothing, so it does not extend a window. A counter +// without an expiry, which a crash outside this script could never leave, +// still gets one, and a counter with 0 ms left counts as 1 ms, so a refusal +// never reports a zero wait. +var takeScript = redis.NewScript(` +local retry = 0 +for index, key in ipairs(KEYS) do + local limit = tonumber(ARGV[2 * index - 1]) + local window = tonumber(ARGV[2 * index]) + local used = tonumber(redis.call('GET', key) or '0') + if used >= limit then + local remaining = redis.call('PTTL', key) + if remaining < 0 then + redis.call('PEXPIRE', key, window) + remaining = window + elseif remaining == 0 then + remaining = 1 + end + if remaining > retry then + retry = remaining + end + end +end +if retry > 0 then + return retry +end +for index, key in ipairs(KEYS) do + local count = redis.call('INCR', key) + if count == 1 or redis.call('PTTL', key) < 0 then + redis.call('PEXPIRE', key, ARGV[2 * index]) + end +end +return 0 +`) + +const rateLimitKeyPrefix = "ratelimit:" + +var _ outbound.RateLimiter = (*Cache)(nil) + +// Take implements outbound.RateLimiter with one fixed-window counter per +// rule, named by the key and the window length, so two rules of one key never +// share a counter. +func (cache *Cache) Take(ctx context.Context, key string, rules ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) { + if key == "" || len(rules) == 0 { + return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - key and at least one rule are required: %w", outbound.ErrInvalidRateLimitRule) + } + keys := make([]string, 0, len(rules)) + arguments := make([]any, 0, 2*len(rules)) + for _, rule := range rules { + if rule.Limit <= 0 || rule.Window < time.Millisecond { + return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - limit must be positive and window at least 1ms: %w", outbound.ErrInvalidRateLimitRule) + } + windowMillis := rule.Window.Milliseconds() + // The key is a hash tag, so every counter of one caller maps to one + // cluster slot, as a multi-key script needs. + keys = append(keys, rateLimitKeyPrefix+"{"+key+"}:"+strconv.FormatInt(windowMillis, 10)) + arguments = append(arguments, rule.Limit, windowMillis) + } + ctx, cancel := context.WithTimeout(ctx, cache.timeout) + defer cancel() + retryMillis, err := takeScript.Run(ctx, cache.client, keys, arguments...).Int64() + if err != nil { + return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - run script: %w", err) + } + if retryMillis == 0 { + return outbound.RateLimitDecision{Allowed: true}, nil + } + return outbound.RateLimitDecision{RetryAfter: time.Duration(retryMillis) * time.Millisecond}, nil +} diff --git a/backend/internal/bootstrap/consumers_test.go b/backend/internal/bootstrap/consumers_test.go index 78ff065..c8720a9 100644 --- a/backend/internal/bootstrap/consumers_test.go +++ b/backend/internal/bootstrap/consumers_test.go @@ -33,6 +33,7 @@ func consumerTestConfig(t *testing.T) config.Config { settings, err := config.LoadFromEnv(func(key string) (string, bool) { value, ok := map[string]string{ "SEAWEEDFS_ACCESS_KEY": "test-access", + "IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab", "SEAWEEDFS_SECRET_KEY": "test-secret", "EMAIL_PROVIDER": "disabled", "EMAIL_FROM": "no-reply@example.com", diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go new file mode 100644 index 0000000..67e7393 --- /dev/null +++ b/backend/internal/bootstrap/identity.go @@ -0,0 +1,119 @@ +package bootstrap + +import ( + "context" + "crypto/rand" + "fmt" + "log/slog" + "net/netip" + "time" + + "lincodex/backend/config" + "lincodex/backend/internal/adapter/primary/http/problem" + v1 "lincodex/backend/internal/adapter/primary/http/v1" + "lincodex/backend/internal/adapter/secondary/argon2id" + "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + redisadapter "lincodex/backend/internal/adapter/secondary/redis" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/identity" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/usecase/notification/mailtemplate" +) + +// identityPoolMaxConns bounds the connections of the registration requests: +// each holds one for a short transaction, after the password hash is done. +const identityPoolMaxConns = 8 + +// newTrustedProxies hands the configured reverse proxies to the router. +func newTrustedProxies(settings config.Config) []netip.Prefix { return settings.TrustedProxyCIDRs } + +// newAPIHandler composes the handler of the public API from the business +// areas that are built. An area without a handler answers 501. +func newAPIHandler(health *v1.HealthHandler, problems *problem.Responder, identityHandler *v1.IdentityHandler) *v1.Handler { + 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. +func newIdentityHandler( + ctx context.Context, + settings config.Config, + logger *slog.Logger, + cache *redisadapter.Cache, + metrics *prometheus.Metrics, +) (*v1.IdentityHandler, func(), error) { + if settings.DatabaseURL == "" { + logger.Warn("registration is not served because DATABASE_URL is not set") + return nil, func() {}, nil + } + keyring, err := newIdentityKeyring(settings, logger) + if err != nil { + return nil, nil, err + } + renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create mail renderer: %w", err) + } + // New deliveries are pinned to the transport and account configured now. + account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - mail provider account: %w", err) + } + hasher, err := argon2id.NewHasher(settings.PasswordHashConcurrency) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create password hasher: %w", err) + } + pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, identityPoolMaxConns) + if err != nil { + return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create pool: %w", err) + } + transactor := postgres.NewTransactor(pool) + registration, err := identity.NewRegistration(identity.RegistrationDependencies{ + Transactor: transactor, + ConsentTexts: postgres.NewConsentStore(pool), + Idempotency: postgres.NewIdentityStore(pool).IdempotencyRecords(), + Consents: consent.NewService(transactor, time.Now), + Credentials: identity.NewCredentials(hasher), + Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, time.Now), + Limiter: cache, + Keyring: keyring, + Clock: time.Now, + Metrics: metrics, + }, identity.RegistrationSettings{ + MailMinInterval: settings.VerificationMailMinInterval, + MailDailyLimit: int64(settings.VerificationMailDailyLimit), + ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit), + }) + if err != nil { + pool.Close() + return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create registration: %w", err) + } + // The HTTP server stops before this cleanup runs, so no request uses the + // pool while it closes. + return v1.NewIdentityHandler(registration), 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. +func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) { + secret := []byte(settings.IdentityKeySecret) + if len(secret) == 0 { + secret = make([]byte, identity.MinKeySecretBytes) + 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") + } + keyring, err := identity.NewKeyring(secret) + if err != nil { + return nil, fmt.Errorf("bootstrap.newIdentityKeyring - create keyring: %w", err) + } + return keyring, nil +} diff --git a/backend/internal/bootstrap/mail_test.go b/backend/internal/bootstrap/mail_test.go index c81849c..76264be 100644 --- a/backend/internal/bootstrap/mail_test.go +++ b/backend/internal/bootstrap/mail_test.go @@ -30,6 +30,7 @@ func loadMailConfig(t *testing.T, mail map[string]string) config.Config { t.Helper() values := map[string]string{ "SEAWEEDFS_ACCESS_KEY": "test-access", + "IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab", "SEAWEEDFS_SECRET_KEY": "test-secret", "EMAIL_FROM": "Lincodex <" + testSenderAddress + ">", "APP_PUBLIC_URL": "http://localhost:8080", diff --git a/backend/internal/bootstrap/wire.go b/backend/internal/bootstrap/wire.go index a76c097..5307ef8 100644 --- a/backend/internal/bootstrap/wire.go +++ b/backend/internal/bootstrap/wire.go @@ -44,7 +44,9 @@ func initialize( metrics.New, newHealthHandler, problem.NewResponder, - v1.NewHandler, + newAPIHandler, + newTrustedProxies, + newIdentityHandler, v1.NewDenyAllSecurity, httpadapter.NewRouter, newOutboxRelay, diff --git a/backend/internal/bootstrap/wire_gen.go b/backend/internal/bootstrap/wire_gen.go index c708676..b73f935 100644 --- a/backend/internal/bootstrap/wire_gen.go +++ b/backend/internal/bootstrap/wire_gen.go @@ -45,24 +45,18 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, readiness := newReadiness(healthChecker, cache, storage) healthHandler := newHealthHandler(readiness, config2) responder := problem.NewResponder(logger) - handler := v1.NewHandler(healthHandler, responder) - denyAllSecurity := v1.NewDenyAllSecurity() metrics := prometheus.New() - httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger) + identityHandler, cleanup4, err := newIdentityHandler(ctx, config2, logger, cache, metrics) if err != nil { cleanup3() cleanup2() cleanup() return nil, nil, err } - relay, cleanup4, err := newOutboxRelay(ctx, config2, logger, metrics) - if err != nil { - cleanup3() - cleanup2() - cleanup() - return nil, nil, err - } - bootstrapEventConsumers, cleanup5, err := newEventConsumers(ctx, config2, logger, metrics) + handler := newAPIHandler(healthHandler, responder, identityHandler) + denyAllSecurity := v1.NewDenyAllSecurity() + v := newTrustedProxies(config2) + httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger, v) if err != nil { cleanup4() cleanup3() @@ -70,7 +64,15 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - worker, cleanup6, err := newJobWorker(ctx, config2, logger, metrics) + relay, cleanup5, err := newOutboxRelay(ctx, config2, logger, metrics) + if err != nil { + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } + bootstrapEventConsumers, cleanup6, err := newEventConsumers(ctx, config2, logger, metrics) if err != nil { cleanup5() cleanup4() @@ -79,7 +81,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - mailsenderWorker, cleanup7, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) + worker, cleanup7, err := newJobWorker(ctx, config2, logger, metrics) if err != nil { cleanup6() cleanup5() @@ -89,7 +91,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } - sampler, cleanup8, err := newDeliveryMetrics(ctx, config2, logger, metrics) + mailsenderWorker, cleanup8, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender) if err != nil { cleanup7() cleanup6() @@ -100,8 +102,21 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger, cleanup() return nil, nil, err } + sampler, cleanup9, err := newDeliveryMetrics(ctx, config2, logger, metrics) + if err != nil { + cleanup8() + cleanup7() + cleanup6() + cleanup5() + cleanup4() + cleanup3() + cleanup2() + cleanup() + return nil, nil, err + } application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler) return application, func() { + cleanup9() cleanup8() cleanup7() cleanup6() diff --git a/backend/internal/domain/email_token.go b/backend/internal/domain/email_token.go index 7d169d1..d93918e 100644 --- a/backend/internal/domain/email_token.go +++ b/backend/internal/domain/email_token.go @@ -32,6 +32,29 @@ func ParseEmailTokenPurpose(value string) (EmailTokenPurpose, error) { } } +// PendingRegistration holds the credentials of one registration, which wait +// on the verification token issued for it. A registration of an unverified +// address never changes the account row; confirming a token applies its own +// pending credentials, and only to a caller who proves the password of that +// registration. Nothing here is valid for login before the confirmation. +type PendingRegistration struct { + PasswordHash PasswordHash + Scenario Scenario + OnboardingStep OnboardingStep +} + +// NewPendingRegistration builds the pending credentials of a registration +// with the first onboarding step of its scenario. +func NewPendingRegistration(hash PasswordHash, scenario Scenario) (PendingRegistration, error) { + if hash.IsZero() { + return PendingRegistration{}, invalidEmailToken("pending password hash must be built by NewPasswordHash") + } + if _, err := ParseScenario(string(scenario)); err != nil { + return PendingRegistration{}, fmt.Errorf("domain.NewPendingRegistration - validate scenario: %w", err) + } + return PendingRegistration{PasswordHash: hash, Scenario: scenario, OnboardingStep: scenario.InitialOnboardingStep()}, nil +} + // EmailToken is the stored record of a one-time token sent by email. It holds // only the hash of the raw token. A token ends at most once: it is either // consumed or invalidated, and it stops working at ExpiresAt. @@ -45,6 +68,9 @@ type EmailToken struct { ExpiresAt time.Time ConsumedAt *time.Time InvalidatedAt *time.Time + // Pending is set on the verification token of a registration and nil on + // a token that carries no credentials. + Pending *PendingRegistration } // NewEmailTokenInput describes a token to issue. RegistrationVersion is the @@ -56,6 +82,8 @@ type NewEmailTokenInput struct { RegistrationVersion int64 IssuedAt time.Time Lifetime time.Duration + // Pending is optional; see PendingRegistration. + Pending *PendingRegistration } // NewEmailToken validates input and assigns a UUIDv7 identifier. @@ -87,6 +115,7 @@ func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) { RegistrationVersion: input.RegistrationVersion, CreatedAt: input.IssuedAt, ExpiresAt: input.IssuedAt.Add(input.Lifetime), + Pending: input.Pending, }, nil } diff --git a/backend/internal/domain/user.go b/backend/internal/domain/user.go index 7cc3f43..868042a 100644 --- a/backend/internal/domain/user.go +++ b/backend/internal/domain/user.go @@ -184,7 +184,15 @@ func (registration Registration) validate(location string) error { return nil } -// User is an account. Storage reconstructs it from trusted rows; new accounts +// User is an account. The PasswordHash, Scenario, and OnboardingStep of an +// unverified account are not authoritative: they hold what the first +// registration of the address stored only because the columns are mandatory. +// A repeat registration never changes them; the credentials that count are the +// pending ones on the verification token, and confirming that token applies +// them. No code may authenticate with, or trust the scenario of, an +// unverified account row. +// +// Storage reconstructs it from trusted rows; new accounts // come from NewUser and changes from its methods. type User struct { ID uuid.UUID diff --git a/backend/internal/port/outbound/identity.go b/backend/internal/port/outbound/identity.go index 6dde4e3..f625923 100644 --- a/backend/internal/port/outbound/identity.go +++ b/backend/internal/port/outbound/identity.go @@ -67,6 +67,7 @@ type IdentityRepositories interface { Users() UserRepository EmailTokens() EmailTokenRepository Sessions() SessionRepository + IdempotencyRecords() IdempotencyRepository } // UserRepository stores accounts. Lookups by email use the normalized form. @@ -97,6 +98,18 @@ type UserRepository interface { // deletes nothing. UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error) + // AdvanceRegistration starts a new registration of an unverified account + // without changing its password hash, scenario, or onboarding step: the + // new registration carries them on its token (see + // domain.PendingRegistration). It applies only when the stored version + // still equals expectedVersion and the email is unverified, advances + // Version and RegistrationVersion by one in the same statement, sets the + // registration time, and deletes the C1 records with the source + // registration of the earlier registration like UpdateRegistration does; + // the caller grants the new C1 strictly after it. Otherwise it returns + // ErrUserVersionConflict. + AdvanceRegistration(ctx context.Context, id uuid.UUID, expectedVersion int64, at time.Time) (domain.User, error) + // MarkEmailVerified sets the verification time when the account is still // unverified and still has registrationVersion, and returns the stored // account. Otherwise it returns ErrUserVersionConflict. A confirmation @@ -124,6 +137,11 @@ type EmailTokenRepository interface { // ErrTokenHashConflict for a duplicate hash. Insert(ctx context.Context, token domain.EmailToken) error + // LatestPending returns the pending credentials of the newest token that + // the registration version of the user has, or false when none carries + // any. A resend copies them to its new token. + LatestPending(ctx context.Context, userID uuid.UUID, registrationVersion int64) (domain.PendingRegistration, bool, error) + // InvalidateActive marks every unconsumed, not yet invalidated token of // the user and purpose as invalidated at the given time, and returns how // many it marked. @@ -174,3 +192,51 @@ type SessionRepository interface { // how many it revoked. RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error) } + +// IdempotencyRetention is how long the replay record of a command with an +// Idempotency-Key lives, as the public contract states. After it the key may +// be accepted as new. +const IdempotencyRetention = 24 * time.Hour + +// IdempotencyDigestSize is the size of the HMAC-SHA-256 values that identify +// and fingerprint a command. +const IdempotencyDigestSize = 32 + +// IdempotencyRecord is the replay record of a committed command. Both digests +// are HMAC-SHA-256 values computed with a server secret; the record holds +// neither the key, the email, nor the request body. +type IdempotencyRecord struct { + // Scope identifies the operation, the key, and the principal; for an + // anonymous operation the principal is the normalized email. + Scope [IdempotencyDigestSize]byte + // Fingerprint identifies the request that the key was first used with. + Fingerprint [IdempotencyDigestSize]byte + CreatedAt time.Time + ExpiresAt time.Time +} + +// IdempotencyRepository stores the replay records of commands. Reserve runs +// in the transaction of the command it guards, so a stored record always +// belongs to a committed command. +type IdempotencyRepository interface { + // Reserve stores record unless a live record with the same scope exists. + // For a stored record it returns it with created true. For a live record + // it returns that record with created false and stores nothing; the + // caller compares the fingerprints to decide between a replay and a + // reused key. A concurrent Reserve with the same scope waits until the + // transaction of the first ends. A record past ExpiresAt is replaced. + // Every method that takes a time rejects the zero time. + Reserve(ctx context.Context, record IdempotencyRecord) (stored IdempotencyRecord, created bool, err error) + + // Find returns the live record with the scope at the given time, or + // ErrIdempotencyRecordNotFound. + Find(ctx context.Context, scope [IdempotencyDigestSize]byte, at time.Time) (IdempotencyRecord, error) + + // PurgeExpired deletes at most limit records that expired at or before + // the given time and returns how many it deleted. It never waits for a + // locked record. + PurgeExpired(ctx context.Context, at time.Time, limit int32) (int64, error) +} + +// ErrIdempotencyRecordNotFound reports that no live record has the scope. +var ErrIdempotencyRecordNotFound = errors.New("idempotency record not found") diff --git a/backend/internal/port/outbound/rate_limit.go b/backend/internal/port/outbound/rate_limit.go new file mode 100644 index 0000000..246a620 --- /dev/null +++ b/backend/internal/port/outbound/rate_limit.go @@ -0,0 +1,39 @@ +package outbound + +import ( + "context" + "errors" + "time" +) + +// ErrInvalidRateLimitRule reports a rule without a positive window or limit, +// or a take without a key or a rule. +var ErrInvalidRateLimitRule = errors.New("invalid rate limit rule") + +// RateLimitRule allows at most Limit takes per fixed Window. The window of a +// key starts with its first take and ends Window later. +type RateLimitRule struct { + Window time.Duration + Limit int64 +} + +// RateLimitDecision is the outcome of Take. +type RateLimitDecision struct { + // Allowed reports that the take was counted against every rule. + Allowed bool + // RetryAfter is, for a refused take, how long until every rule that + // refused it admits another one. It is zero for an allowed take. + RetryAfter time.Duration +} + +// RateLimiter counts requests of one caller key against fixed windows. The +// counters are ephemeral: a restart or a flush of the store resets them, so +// a limiter is an abuse brake, never a record of what happened. +type RateLimiter interface { + // Take counts one request of key against every rule at once. It counts + // nothing when any rule refuses, so refused requests do not extend a + // window. The key is an opaque string that must not hold personal data + // in clear form; callers pass a keyed digest. A store failure returns + // an error and the caller decides how to fail. + Take(ctx context.Context, key string, rules ...RateLimitRule) (RateLimitDecision, error) +} diff --git a/backend/internal/usecase/identity/errors.go b/backend/internal/usecase/identity/errors.go new file mode 100644 index 0000000..57c90cc --- /dev/null +++ b/backend/internal/usecase/identity/errors.go @@ -0,0 +1,51 @@ +package identity + +import ( + "errors" + "fmt" + "time" +) + +var ( + // ErrRateLimited reports a request refused by the per-address limit. + // errors.As with *RateLimitedError yields the wait. + ErrRateLimited = errors.New("rate limit exceeded") + + // ErrIdempotencyKeyReused reports a key that was first used with another + // request body for the same address. + ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request") + + // ErrInvalidField reports a request value outside its rules. + // errors.As with *InvalidFieldError yields the JSON Pointer of the field. + ErrInvalidField = errors.New("invalid request field") +) + +// RateLimitedError carries how long the caller waits before a repeat can be +// accepted. It matches ErrRateLimited. +type RateLimitedError struct { + RetryAfter time.Duration +} + +func (err *RateLimitedError) Error() string { + return fmt.Sprintf("rate limit exceeded, retry after %s", err.RetryAfter) +} + +func (err *RateLimitedError) Unwrap() error { return ErrRateLimited } + +// InvalidFieldError names the body field that failed and why, without the +// value. Pointer is the JSON Pointer of the field in the request body. It +// matches ErrInvalidField and also the domain error it wraps. +type InvalidFieldError struct { + Pointer string + Err error +} + +func (err *InvalidFieldError) Error() string { + return fmt.Sprintf("invalid request field %s: %v", err.Pointer, err.Err) +} + +func (err *InvalidFieldError) Unwrap() []error { return []error{ErrInvalidField, err.Err} } + +func invalidField(pointer string, cause error) error { + return &InvalidFieldError{Pointer: pointer, Err: cause} +} diff --git a/backend/internal/usecase/identity/keyring.go b/backend/internal/usecase/identity/keyring.go new file mode 100644 index 0000000..0e48ee7 --- /dev/null +++ b/backend/internal/usecase/identity/keyring.go @@ -0,0 +1,90 @@ +package identity + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "fmt" + + "lincodex/backend/internal/port/outbound" +) + +// MinKeySecretBytes is the shortest secret that NewKeyring accepts. +const MinKeySecretBytes = 32 + +// Domain-separation labels. Each purpose gets its own key derived from the +// one secret, so a digest made for one purpose never matches another. +const ( + labelIdempotencyScope = "lincodex/identity/idempotency-scope/v1" + labelFingerprint = "lincodex/identity/request-fingerprint/v1" + labelEmailBucket = "lincodex/identity/email-bucket/v1" + labelClientBucket = "lincodex/identity/client-bucket/v1" +) + +// Keyring computes the keyed digests of the anonymous identity operations: +// the idempotency scope, the request fingerprint, and the rate limit bucket +// of an email address. All of them are HMAC-SHA-256 values, so what the +// stores hold can neither confirm that an address is registered nor serve as +// an offline check of a password without the server secret. +type Keyring struct { + scopeKey []byte + fingerprintKey []byte + bucketKey []byte + clientKey []byte +} + +// NewKeyring derives the purpose keys from secret. +func NewKeyring(secret []byte) (*Keyring, error) { + if len(secret) < MinKeySecretBytes { + return nil, fmt.Errorf("identity.NewKeyring - secret must have at least %d bytes", MinKeySecretBytes) + } + return &Keyring{ + scopeKey: derive(secret, labelIdempotencyScope), + fingerprintKey: derive(secret, labelFingerprint), + bucketKey: derive(secret, labelEmailBucket), + clientKey: derive(secret, labelClientBucket), + }, nil +} + +func derive(secret []byte, label string) []byte { + mac := hmac.New(sha256.New, secret) + mac.Write([]byte(label)) + return mac.Sum(nil) +} + +// IdempotencyScope scopes a key by the operation, the key, and the +// normalized email. The parts are joined with NUL, which none of them can +// contain: operation names and keys are limited to printable ASCII and the +// email is printable ASCII. +func (keyring *Keyring) IdempotencyScope(operation, key, normalizedEmail string) [outbound.IdempotencyDigestSize]byte { + mac := hmac.New(sha256.New, keyring.scopeKey) + mac.Write([]byte(operation)) + mac.Write([]byte{0}) + mac.Write([]byte(key)) + mac.Write([]byte{0}) + mac.Write([]byte(normalizedEmail)) + return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil)) +} + +// Fingerprint identifies a request by its canonical body. +func (keyring *Keyring) Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte { + mac := hmac.New(sha256.New, keyring.fingerprintKey) + mac.Write(canonicalBody) + return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil)) +} + +// EmailBucket names the rate limit counters of one address, whether or not +// an account exists for it, so a refusal does not reveal an account. +func (keyring *Keyring) EmailBucket(normalizedEmail string) string { + mac := hmac.New(sha256.New, keyring.bucketKey) + mac.Write([]byte(normalizedEmail)) + return "identity:email:" + hex.EncodeToString(mac.Sum(nil)) +} + +// ClientBucket names the rate limit counters of one client from its opaque +// key, so the store never holds a network address in clear form. +func (keyring *Keyring) ClientBucket(clientKey string) string { + mac := hmac.New(sha256.New, keyring.clientKey) + mac.Write([]byte(clientKey)) + return "identity:client:" + hex.EncodeToString(mac.Sum(nil)) +} diff --git a/backend/internal/usecase/identity/register.go b/backend/internal/usecase/identity/register.go new file mode 100644 index 0000000..e9122ac --- /dev/null +++ b/backend/internal/usecase/identity/register.go @@ -0,0 +1,520 @@ +package identity + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" + "lincodex/backend/internal/usecase/consent" + "lincodex/backend/internal/usecase/notification" +) + +const ( + // registerOperation names RegisterAccount in the idempotency scope. + registerOperation = "RegisterAccount" + + // maxIdempotencyKeyLength is the longest Idempotency-Key of the contract. + maxIdempotencyKeyLength = 255 + + // maxTransactionAttempts bounds the retries of a registration or a resend + // after a lost race: a concurrent registration of the same address, a + // concurrent re-registration, or a deadlock. Each retry reads the account + // again, so it takes the branch that matches the winner. + maxTransactionAttempts = 3 + + // purgeBatch is how many expired idempotency records one registration + // removes, so the table stays bounded without a separate job. + purgeBatch = 10 + + idempotencyKeyPointer = "/Idempotency-Key" + consentTextVersionPointer = "/consent_c1/text_version" + emailPointer = "/email" + passwordPointer = "/password" + scenarioPointer = "/scenario" +) + +// RegistrationSettings holds the limits of the verification mail to one +// address. The registration and every resend count against both rules, so +// registering again and then resending cannot send more than the daily limit. +type RegistrationSettings struct { + // MailMinInterval is the shortest time between two verification messages + // to one address. + MailMinInterval time.Duration + // MailDailyLimit is the number of verification messages to one address in + // a window of 24 hours that starts with the first of them. + MailDailyLimit int64 + // ClientHourlyLimit is the number of registrations and resends per client + // in a window of one hour. It applies only to a request that carries a + // client key. + ClientHourlyLimit int64 +} + +const ( + // mailDailyWindow is the window of RegistrationSettings.MailDailyLimit. + mailDailyWindow = 24 * time.Hour + // clientWindow is the window of RegistrationSettings.ClientHourlyLimit. + clientWindow = time.Hour +) + +func (settings RegistrationSettings) mailRules() []outbound.RateLimitRule { + return []outbound.RateLimitRule{ + {Window: settings.MailMinInterval, Limit: 1}, + {Window: mailDailyWindow, Limit: settings.MailDailyLimit}, + } +} + +func (settings RegistrationSettings) validate() error { + switch { + case settings.MailMinInterval < time.Millisecond || settings.MailMinInterval >= mailDailyWindow: + return errors.New("mail minimum interval must be at least one millisecond and shorter than the daily window") + case settings.MailDailyLimit < 1: + return errors.New("mail daily limit must be positive") + case settings.ClientHourlyLimit < 1: + return errors.New("client hourly limit must be positive") + } + return nil +} + +// RegistrationDependencies are the collaborators of Registration. Every +// field is required. +type RegistrationDependencies struct { + Transactor outbound.Transactor + // ConsentTexts and Idempotency read outside a transaction: the consent + // text check and the replay check run before the registration + // transaction starts. + ConsentTexts outbound.ConsentRepositories + Idempotency outbound.IdempotencyRepository + Consents *consent.Service + Credentials *Credentials + Mailer *notification.ServiceMailer + Limiter outbound.RateLimiter + Keyring *Keyring + Clock func() time.Time + // Metrics receives the refusals of the limiter. Optional. + Metrics RateLimitMetrics +} + +// Scopes of a limiter refusal, as the metric labels them. +const ( + ScopeAddress = "address" + ScopeClient = "client" +) + +// RateLimitMetrics counts refused requests by scope, never by address. +type RateLimitMetrics interface { + ObserveIdentityRateLimited(scope string) +} + +// Registration registers accounts and resends the verification message. It +// holds no state; the same instance serves concurrent callers. +// +// Neither operation reveals whether an address belongs to an account: the +// outcome, the response, and the rate limit depend on the request alone, +// never on the stored accounts. Registration also computes the password hash +// on every branch before it reads the account. +type Registration struct { + deps RegistrationDependencies + settings RegistrationSettings +} + +// NewRegistration checks the dependencies and settings once, so a wiring +// mistake fails at startup and not at the first request. +func NewRegistration(deps RegistrationDependencies, settings RegistrationSettings) (*Registration, error) { + switch { + case deps.Transactor == nil, deps.ConsentTexts == nil, deps.Idempotency == nil, deps.Consents == nil, + deps.Credentials == nil, deps.Mailer == nil, deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil: + return nil, errors.New("identity.NewRegistration - every dependency must be set") + } + if err := settings.validate(); err != nil { + return nil, fmt.Errorf("identity.NewRegistration - validate settings: %w", err) + } + return &Registration{deps: deps, settings: settings}, nil +} + +// RegisterCommand is the content of a registration request, unvalidated. +type RegisterCommand struct { + IdempotencyKey string + Email string + Password string + Scenario string + // ConsentTextVersion is the version of the C1 text the user accepted. + ConsentTextVersion string + // ClientKey identifies the client for the per-client limit, for example + // the limiter key of its network address. Empty skips that limit. It is + // opaque, is only ever keyed-hashed here, and is never stored or logged. + ClientKey string +} + +// ResendCommand is the content of a resend request, unvalidated. +type ResendCommand struct { + Email string + // ClientKey is as in RegisterCommand. + ClientKey string +} + +// registerInput is a validated command. +type registerInput struct { + email domain.EmailAddress + scenario domain.Scenario + version domain.ConsentTextVersion + hash domain.PasswordHash + record outbound.IdempotencyRecord + fingerprint [outbound.IdempotencyDigestSize]byte +} + +// Register handles one registration request. A nil result means the neutral +// acceptance, whatever the state of the address: a new account was created, a +// pending registration was replaced, a verified account was left alone, or +// the request replays an earlier identical one. +// +// Errors: *InvalidFieldError for a value outside its rules, including a C1 +// text version that is no longer current; ErrIdempotencyKeyReused; +// *RateLimitedError; anything else is an internal failure. +// +// Order: validation, replay check, rate limit, password hash, transaction. +// A replay does not consume the limit, so a client that retries a lost +// answer is not refused for it. +func (registration *Registration) Register(ctx context.Context, command RegisterCommand) error { + const location = "Registration.Register" + input, err := registration.validateRegister(ctx, command) + if err != nil { + return fmt.Errorf("%s - validate request: %w", location, err) + } + existing, err := registration.deps.Idempotency.Find(ctx, input.record.Scope, registration.deps.Clock()) + switch { + case err == nil: + return replayOrReject(location, existing, input.fingerprint) + case !errors.Is(err, outbound.ErrIdempotencyRecordNotFound): + return fmt.Errorf("%s - read idempotency record: %w", location, err) + } + if err := registration.takeMailSlot(ctx, input.email, command.ClientKey); err != nil { + return fmt.Errorf("%s - limit verification mail: %w", location, err) + } + // The hash is computed on every branch, before the account is read, so + // the time of the response does not tell a new address from a known one. + input.hash, err = registration.deps.Credentials.HashNewPassword(ctx, command.Password) + if err != nil { + return fmt.Errorf("%s - hash password: %w", location, err) + } + err = registration.inTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return registration.registerInTransaction(ctx, unit, input) + }) + if err != nil { + return fmt.Errorf("%s - register in transaction: %w", location, err) + } + return nil +} + +func (registration *Registration) validateRegister(ctx context.Context, command RegisterCommand) (registerInput, error) { + if command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeyLength { + return registerInput{}, invalidField(idempotencyKeyPointer, errors.New("key must have 1 to 255 characters")) + } + email, err := domain.NewEmailAddress(command.Email) + if err != nil { + return registerInput{}, invalidField(emailPointer, err) + } + if _, err := domain.NewPassword(command.Password); err != nil { + return registerInput{}, invalidField(passwordPointer, err) + } + scenario, err := domain.ParseScenario(command.Scenario) + if err != nil { + return registerInput{}, invalidField(scenarioPointer, err) + } + version, err := domain.ParseConsentTextVersion(command.ConsentTextVersion) + if err != nil { + return registerInput{}, invalidField(consentTextVersionPointer, err) + } + // The check runs before any lookup of the address, so a stale version + // fails the same way for a new and for a known address. + _, err = registration.deps.Consents.CheckTextVersion(ctx, registration.deps.ConsentTexts, domain.ConsentPurposePersonalData, version) + if errors.Is(err, consent.ErrStaleConsentText) { + return registerInput{}, invalidField(consentTextVersionPointer, err) + } + if err != nil { + return registerInput{}, fmt.Errorf("check consent text version: %w", err) + } + fingerprint, err := registration.fingerprint(command) + if err != nil { + return registerInput{}, err + } + now := registration.deps.Clock() + return registerInput{ + email: email, + scenario: scenario, + version: version, + fingerprint: fingerprint, + record: outbound.IdempotencyRecord{ + Scope: registration.deps.Keyring.IdempotencyScope(registerOperation, command.IdempotencyKey, email.Normalized()), + Fingerprint: fingerprint, + CreatedAt: now, + ExpiresAt: now.Add(outbound.IdempotencyRetention), + }, + }, nil +} + +// fingerprint is the HMAC of the canonical body: a JSON array of the fields +// in a fixed order, with the values as the client sent them. +func (registration *Registration) fingerprint(command RegisterCommand) ([outbound.IdempotencyDigestSize]byte, error) { + canonical, err := json.Marshal([]string{command.Email, command.Password, command.Scenario, command.ConsentTextVersion}) + if err != nil { + return [outbound.IdempotencyDigestSize]byte{}, fmt.Errorf("encode canonical body: %w", err) + } + return registration.deps.Keyring.Fingerprint(canonical), nil +} + +func replayOrReject(location string, existing outbound.IdempotencyRecord, fingerprint [outbound.IdempotencyDigestSize]byte) error { + if existing.Fingerprint != fingerprint { + return fmt.Errorf("%s - compare fingerprints: %w", location, ErrIdempotencyKeyReused) + } + return nil +} + +// registerInTransaction applies one registration. The idempotency record is +// reserved first: a concurrent request with the same scope then waits for +// this transaction and replays its outcome. +func (registration *Registration) registerInTransaction(ctx context.Context, unit outbound.UnitOfWork, input registerInput) error { + const location = "Registration.registerInTransaction" + now := registration.deps.Clock() + stored, created, err := unit.IdempotencyRecords().Reserve(ctx, input.record) + if err != nil { + return fmt.Errorf("%s - reserve idempotency record: %w", location, err) + } + if !created { + return replayOrReject(location, stored, input.fingerprint) + } + if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, now, purgeBatch); err != nil { + return fmt.Errorf("%s - purge expired idempotency records: %w", location, err) + } + user, err := unit.Users().GetByEmail(ctx, input.email) + switch { + case errors.Is(err, outbound.ErrUserNotFound): + return registration.createAccount(ctx, unit, input, now) + case err != nil: + return fmt.Errorf("%s - read account: %w", location, err) + case user.EmailVerified(): + // A verified account never changes and nothing is sent: the notice + // "you already have an account" is not implemented, see the + // architecture document. + return nil + default: + return registration.reRegister(ctx, unit, input, user, now) + } +} + +func (registration *Registration) createAccount(ctx context.Context, unit outbound.UnitOfWork, input registerInput, now time.Time) error { + const location = "Registration.createAccount" + user, err := domain.NewUser(domain.Registration{ + Email: input.email, + PasswordHash: input.hash, + Scenario: input.scenario, + RegisteredAt: now, + }) + if err != nil { + return fmt.Errorf("%s - build account: %w", location, err) + } + if err := unit.Users().Create(ctx, user); err != nil { + return fmt.Errorf("%s - store account: %w", location, err) + } + if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, input.version); err != nil { + return fmt.Errorf("%s - record C1: %w", location, err) + } + pending, err := domain.NewPendingRegistration(input.hash, input.scenario) + if err != nil { + return fmt.Errorf("%s - build pending registration: %w", location, err) + } + return registration.issueVerification(ctx, unit, user, now, &pending) +} + +// reRegister starts a new registration of an unverified address. It never +// changes the credentials, scenario, or onboarding step of the account row: +// the new registration carries its own on its verification token, and +// confirming a token applies only the credentials of that token (TASK-054). +// So neither the first nor the latest registrant of an address can make its +// owner adopt a password the owner did not choose. The lock order of the +// identity repositories applies: tokens first, then the account. +// AdvanceRegistration deletes the earlier C1 of this account, so the new C1 is +// granted strictly after it. +func (registration *Registration) reRegister( + ctx context.Context, + unit outbound.UnitOfWork, + input registerInput, + user domain.User, + now time.Time, +) error { + const location = "Registration.reRegister" + if _, err := unit.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, now); err != nil { + return fmt.Errorf("%s - invalidate earlier tokens: %w", location, err) + } + advanced, err := unit.Users().AdvanceRegistration(ctx, user.ID, user.Version, now) + if err != nil { + return fmt.Errorf("%s - advance registration: %w", location, err) + } + if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, advanced.ID, input.version); err != nil { + return fmt.Errorf("%s - record C1: %w", location, err) + } + pending, err := domain.NewPendingRegistration(input.hash, input.scenario) + if err != nil { + return fmt.Errorf("%s - build pending registration: %w", location, err) + } + return registration.issueVerification(ctx, unit, advanced, now, &pending) +} + +// issueVerification stores a new token bound to the current registration +// version and queues its message, in the caller's transaction. +func (registration *Registration) issueVerification( + ctx context.Context, + unit outbound.UnitOfWork, + user domain.User, + now time.Time, + pending *domain.PendingRegistration, +) error { + const location = "Registration.issueVerification" + policy, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now) + if err != nil { + return fmt.Errorf("%s - read product policy: %w", location, err) + } + lifetime := policy.Policy().Identity.VerificationTokenLifetime + raw, err := domain.NewSecretToken() + if err != nil { + return fmt.Errorf("%s - generate token: %w", location, err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: user.ID, + Purpose: domain.EmailTokenPurposeEmailVerification, + TokenHash: raw.Hash(), + RegistrationVersion: user.RegistrationVersion, + IssuedAt: now, + Lifetime: lifetime.Duration(), + Pending: pending, + }) + if err != nil { + return fmt.Errorf("%s - build token: %w", location, err) + } + if err := unit.EmailTokens().Insert(ctx, token); err != nil { + return fmt.Errorf("%s - store token: %w", location, err) + } + _, err = registration.deps.Mailer.EnqueueVerification(ctx, unit, notification.TokenMailRequest{ + Recipient: user.Email, + Token: token, + RawToken: raw, + Lifetime: lifetime, + }) + if err != nil { + return fmt.Errorf("%s - queue message: %w", location, err) + } + return nil +} + +// ResendVerification issues a new verification token for an unverified +// account and queues its message. The explicit replacement policy: every +// unused token of the account is invalidated before the new one is stored, so +// at most one verification link works at a time, and the registration +// version of the account does not change. +// +// A nil result is the neutral acceptance, for an unknown address, a verified +// one, and an unverified one alike. The rate limit counts the request before +// the account is read, so a refusal says nothing about the account; it +// returns *RateLimitedError. +func (registration *Registration) ResendVerification(ctx context.Context, command ResendCommand) error { + const location = "Registration.ResendVerification" + email, err := domain.NewEmailAddress(command.Email) + if err != nil { + return fmt.Errorf("%s - validate request: %w", location, invalidField(emailPointer, err)) + } + if err := registration.takeMailSlot(ctx, email, command.ClientKey); err != nil { + return fmt.Errorf("%s - limit verification mail: %w", location, err) + } + err = registration.inTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return registration.resendInTransaction(ctx, unit, email) + }) + if err != nil { + return fmt.Errorf("%s - resend in transaction: %w", location, err) + } + return nil +} + +func (registration *Registration) resendInTransaction(ctx context.Context, unit outbound.UnitOfWork, email domain.EmailAddress) error { + const location = "Registration.resendInTransaction" + user, err := unit.Users().GetByEmail(ctx, email) + switch { + case errors.Is(err, outbound.ErrUserNotFound): + return nil + case err != nil: + return fmt.Errorf("%s - read account: %w", location, err) + case user.EmailVerified(): + return nil + } + now := registration.deps.Clock() + // A resend keeps the credentials of the registration it resends for. + var pending *domain.PendingRegistration + latest, found, err := unit.EmailTokens().LatestPending(ctx, user.ID, user.RegistrationVersion) + if err != nil { + return fmt.Errorf("%s - read pending credentials: %w", location, err) + } + if found { + pending = &latest + } + if pending == nil { + // No token of this registration carries credentials, which only a + // token that was invalidated concurrently can cause. A token without + // them could never be confirmed, so none is issued; the next + // registration of the address starts over. + return nil + } + if _, err := unit.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, now); err != nil { + return fmt.Errorf("%s - invalidate earlier tokens: %w", location, err) + } + return registration.issueVerification(ctx, unit, user, now, pending) +} + +// takeMailSlot counts the request against the per-client rule, when the +// request has a client key, and then against the per-address rules. The +// address counters see every request, whether or not an account exists, so a +// refusal does not reveal an account. A refused request counts nothing in the +// rule that refused it. +func (registration *Registration) takeMailSlot(ctx context.Context, email domain.EmailAddress, clientKey string) error { + if clientKey != "" { + err := registration.take(ctx, ScopeClient, registration.deps.Keyring.ClientBucket(clientKey), + outbound.RateLimitRule{Window: clientWindow, Limit: registration.settings.ClientHourlyLimit}) + if err != nil { + return err + } + } + return registration.take(ctx, ScopeAddress, registration.deps.Keyring.EmailBucket(email.Normalized()), registration.settings.mailRules()...) +} + +func (registration *Registration) take(ctx context.Context, scope, bucket string, rules ...outbound.RateLimitRule) error { + decision, err := registration.deps.Limiter.Take(ctx, bucket, rules...) + if err != nil { + return fmt.Errorf("take rate limit: %w", err) + } + if !decision.Allowed { + if registration.deps.Metrics != nil { + registration.deps.Metrics.ObserveIdentityRateLimited(scope) + } + return &RateLimitedError{RetryAfter: decision.RetryAfter} + } + return nil +} + +// inTransaction runs work and repeats it, up to maxTransactionAttempts times +// in total, after a lost race. Every repeat reads the account again, so it is +// safe: the first attempt rolled back completely. +func (registration *Registration) inTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error { + for attempt := 1; ; attempt++ { + err := registration.deps.Transactor.WithinTransaction(ctx, work) + if err == nil || !retryable(err) || attempt >= maxTransactionAttempts || ctx.Err() != nil { + return err + } + } +} + +func retryable(err error) bool { + return errors.Is(err, outbound.ErrEmailTaken) || + errors.Is(err, outbound.ErrUserVersionConflict) || + errors.Is(err, outbound.ErrTransactionConflict) +} diff --git a/deploy/Makefile b/deploy/Makefile index 19900e4..54f281b 100644 --- a/deploy/Makefile +++ b/deploy/Makefile @@ -8,6 +8,10 @@ MONITORING_PROJECT ?= monitoring APP_NETWORK ?= $(APP_PROJECT)_default ENV_FILE ?= $(ROOT)/.env CHECK_ENV_FILE := $(ROOT)/.env.example +# The example file has no usable IDENTITY_KEY_SECRET, which Compose requires. +# Commands that render or build from it get this value in their own +# environment only, never in .env targets, where it would override the real one. +CHECK_IDENTITY_KEY_SECRET := render-only-identity-key-secret-not-for-deployment CORE_FILE := $(ROOT)/deploy/docker/docker-compose.yml ML_FILE := $(ROOT)/deploy/docker/docker-compose.ml.yml MONITORING_FILE := $(ROOT)/deploy/docker/docker-compose.monitoring.yml @@ -36,15 +40,15 @@ config: ## Render all Compose files with safe example values @test -f "$(ROOT)/backend/Dockerfile" || { printf 'Missing backend/Dockerfile.\n' >&2; exit 2; } @test -f "$(ROOT)/frontend/Dockerfile" || { printf 'Missing frontend/Dockerfile.\n' >&2; exit 2; } @test -f "$(ROOT)/ml/Dockerfile" || { printf 'Missing ml/Dockerfile.\n' >&2; exit 2; } - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" config --quiet - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" config --quiet - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" config --quiet - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" config --quiet - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" -f "$(ML_RELEASE_FILE)" config --quiet - APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" -f "$(RELEASE_FILE)" config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" LINCODEX_RELEASE_TAG=000000000000 IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" -f "$(ML_RELEASE_FILE)" config --quiet + APP_PROJECT=lincodex-e2e-config APP_NETWORK=lincodex-e2e-config_default PLAYWRIGHT_VERSION="$(PLAYWRIGHT_VERSION)" E2E_UID=1000 E2E_GID=1000 E2E_SPEC_DIR="$(ROOT)/frontend/e2e" E2E_ARTIFACTS_DIR="$(ROOT)/frontend/test-results/e2e" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p lincodex-e2e-config -f "$(CORE_FILE)" -f "$(E2E_FILE)" --profile e2e config --quiet build: ## Build local frontend and backend images - APP_PROJECT="$(APP_PROJECT)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" build + APP_PROJECT="$(APP_PROJECT)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" build up: ## Start the core app, PostgreSQL, Redis, SeaweedFS, and Kafka without monitoring @test -f "$(ENV_FILE)" || { printf 'Missing %s. Copy .env.example to .env and replace the placeholder passwords.\n' "$(ENV_FILE)" >&2; exit 2; } @@ -59,7 +63,7 @@ logs: ## Follow core service logs APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(APP_PROJECT)" -f "$(CORE_FILE)" logs -f monitoring-config: ## Render the separate monitoring Compose file - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" config --quiet monitoring-up: ## Start monitoring as a separate Compose project @test -f "$(ENV_FILE)" || { printf 'Missing %s. Copy .env.example to .env and replace the placeholder passwords.\n' "$(ENV_FILE)" >&2; exit 2; } @@ -74,10 +78,10 @@ monitoring-logs: ## Follow monitoring service logs APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(ENV_FILE)" -p "$(MONITORING_PROJECT)" -f "$(MONITORING_FILE)" logs -f ml-config: ## Render the separate ML Compose file - APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" config --quiet + APP_PROJECT="$(APP_PROJECT)" APP_NETWORK="$(APP_NETWORK)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" config --quiet ml-build: ## Build the ML image without starting it - APP_PROJECT="$(APP_PROJECT)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" build + APP_PROJECT="$(APP_PROJECT)" IDENTITY_KEY_SECRET="$(CHECK_IDENTITY_KEY_SECRET)" $(DOCKER) compose --env-file "$(CHECK_ENV_FILE)" -p "$(ML_PROJECT)" -f "$(ML_FILE)" build ml-up: ## Start the ML service as a separate Compose project @test -f "$(ENV_FILE)" || { printf 'Missing %s. Copy .env.example to .env and replace the placeholder passwords.\n' "$(ENV_FILE)" >&2; exit 2; } diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml index 6bbd2ce..59c7a52 100644 --- a/deploy/docker/docker-compose.yml +++ b/deploy/docker/docker-compose.yml @@ -229,6 +229,12 @@ 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. + # 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} # 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/deploy/scripts/e2e.sh b/deploy/scripts/e2e.sh index 51eee35..247333e 100644 --- a/deploy/scripts/e2e.sh +++ b/deploy/scripts/e2e.sh @@ -150,6 +150,7 @@ EMAIL_FROM=no-reply@example.com EMAIL_TIMEOUT=10s APP_PUBLIC_URL=http://localhost:8080 PASSWORD_HASH_CONCURRENCY=1 +IDENTITY_KEY_SECRET=$(random_secret) POSTGRES_EXPORTER_USER= POSTGRES_EXPORTER_PASSWORD= EOF diff --git a/deploy/scripts/release_manifest.py b/deploy/scripts/release_manifest.py index 45be762..d013b67 100644 --- a/deploy/scripts/release_manifest.py +++ b/deploy/scripts/release_manifest.py @@ -50,6 +50,9 @@ EVIDENCE_SCHEMA = "lincodex.release-evidence/v1" RELEASE_REGISTRY = "lincodex.invalid" # Project name used only to render Compose files; nothing is started under it. RENDER_PROJECT = "lincodex-release" +# Compose requires IDENTITY_KEY_SECRET and .env.example has none; this value only +# lets a render or build go through and is never deployed. +RENDER_ONLY_IDENTITY_KEY = "render-only-identity-key-secret-not-for-deployment" CHECKS = ("smoke", "e2e") CHECK_SCOPE = { "smoke": ( @@ -538,7 +541,12 @@ class Docker: args += ["-f", str(root / name)] args += ["config", "--format", "json"] env = docker_env( - {"APP_PROJECT": RENDER_PROJECT, "APP_NETWORK": f"{RENDER_PROJECT}_default", "LINCODEX_RELEASE_TAG": tag} + { + "APP_PROJECT": RENDER_PROJECT, + "APP_NETWORK": f"{RENDER_PROJECT}_default", + "LINCODEX_RELEASE_TAG": tag, + "IDENTITY_KEY_SECRET": RENDER_ONLY_IDENTITY_KEY, + } ) return json.loads(run(args, cwd=root, env=env)) @@ -590,7 +598,12 @@ class Docker: args += ["--build-arg", f"{name}={value}"] args.append(service) env = docker_env( - {"APP_PROJECT": RENDER_PROJECT, "APP_NETWORK": f"{RENDER_PROJECT}_default", "LINCODEX_RELEASE_TAG": tag} + { + "APP_PROJECT": RENDER_PROJECT, + "APP_NETWORK": f"{RENDER_PROJECT}_default", + "LINCODEX_RELEASE_TAG": tag, + "IDENTITY_KEY_SECRET": RENDER_ONLY_IDENTITY_KEY, + } ) print(f"Building {service} for release {tag}", flush=True) if subprocess.run(args, cwd=root, env=env, check=False).returncode != 0: diff --git a/deploy/scripts/smoke.sh b/deploy/scripts/smoke.sh index eaf28fa..d9f500f 100644 --- a/deploy/scripts/smoke.sh +++ b/deploy/scripts/smoke.sh @@ -26,13 +26,15 @@ port=18080 network="${project}_default" storage_network="${project}_storage" started=0 +# .env.example has no usable IDENTITY_KEY_SECRET; the throwaway stack draws its own. +identity_key_secret=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n') # The smoke stack sends no mail: it uses EMAIL_PROVIDER=disabled from # .env.example and points mail links at its own loopback port. compose() { APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \ APP_SUBNET=172.29.81.0/24 APP_FRONTEND_IP=172.29.81.10 \ - APP_PUBLIC_URL="http://localhost:$port" LINCODEX_RELEASE_TAG="$release_tag" docker compose \ + APP_PUBLIC_URL="http://localhost:$port" LINCODEX_RELEASE_TAG="$release_tag" IDENTITY_KEY_SECRET="$identity_key_secret" docker compose \ --env-file "$env_file" \ -p "$project" \ "${compose_files[@]}" \ diff --git a/deploy/scripts/test_perimeter.py b/deploy/scripts/test_perimeter.py index a31aac8..05bb474 100644 --- a/deploy/scripts/test_perimeter.py +++ b/deploy/scripts/test_perimeter.py @@ -63,7 +63,10 @@ def size_bytes(value): def render_compose(file_names, project, extra_env=None, profiles=()): if isinstance(file_names, str): file_names = [file_names] - environment = dict(os.environ, APP_PROJECT=project, APP_NETWORK=f"{project}_default") + # The example file has no usable IDENTITY_KEY_SECRET, which Compose requires. + environment = dict( + os.environ, APP_PROJECT=project, APP_NETWORK=f"{project}_default", IDENTITY_KEY_SECRET="render-only-identity-key-secret" + ) for name in ("APP_HTTP_BIND", "APP_HTTP_PORT", "ML_BIND_ADDRESS", "APP_SUBNET", "APP_FRONTEND_IP", "TRUSTED_PROXY_CIDRS"): environment.pop(name, None) environment.update(extra_env or {}) diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index b7b426f..214f0b3 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -674,7 +674,7 @@ What the ports guarantee: ### Password hashing -Implemented (TASK-052) and tested, but not wired into bootstrap: registration (TASK-053) and login (TASK-055) will create the hasher from configuration and call it. +Implemented (TASK-052) and tested: registration (TASK-053) creates the hasher from configuration and calls it; login (TASK-055) will do the same. - `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. @@ -731,6 +731,32 @@ Implemented (TASK-063): `consent.Service` in `backend/internal/usecase/consent/` - Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers (TASK-064, TASK-053, TASK-201). - Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or TASK-064, and neither exists yet. +### Registration and verification resend + +Implemented (TASK-053): `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`. + +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. Requirements for the hand-off: + +- TASK-054 (`ConfirmEmail`): confirming a token applies the pending credentials of the clicked token, and only those, to the account row in the confirmation transaction (password hash, scenario, onboarding step), and must require the password of that registration to confirm a token that carries pending credentials, verified against the token's pending hash. Then a victim who clicks an attacker's link cannot adopt the attacker's password, and an attacker cannot confirm the victim's token. `EmailVerificationRequest` has no password field today; adding it is a contract change of TASK-054, not made here. The description of `RegisterAccount` in the contract still says a repeat registration replaces the password hash on the account; TASK-054 corrects it with that change. +- TASK-054 also: test both orderings (the attacker registers first and the victim second, and the reverse) and show that the owner never ends up with a password they did not choose; require that a C1 record exists and belongs to the registration version of the confirmed token; refuse a token that carries no pending credentials, with no legacy path that skips the password; null the `pending_*` columns of the token when it is consumed. +- TASK-055 (login): an unverified account never signs in. Login answers 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. + +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. The 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. 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 refused request counts nothing, 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. + +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. + +Targeted lockout. Because the per-address counters count every request whether or not the account exists, anyone can use up the address's 5 messages per 24 hours and so block the owner's registration and resend for up to 24 hours without knowing the address's state. This is the price of answering 429 identically for every address; it is accepted as a known limitation of the anti-enumeration design. It is bounded (the per-client limit slows one source), and visible: `lincodex_identity_rate_limit_refusals_total{scope="address"}` rises. A large share of `scope="client"` refusals instead hints at a broken proxy chain (every client resolved to the proxy address); alert on the ratio of client to address refusals and check `TRUSTED_PROXY_CIDRS`. The label has two fixed values and never holds an address. No alerting rule is shipped yet. + +Without a resolved client address (the `ClientIP` middleware did not run) the per-client limit is skipped and only the per-address limits apply: a shared "unknown" bucket would let one client lock out everyone, the worse failure. `IDENTITY_KEY_SECRET` is required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` lets a development stand draw a random one. The limiter keys carry a Redis hash tag (`{key}`), so the multi-key script is cluster safe. + +Known limits. A resend for an unknown or verified address skips the token and message work, so its time differs from an unverified account by a few database statements; registration hides the difference behind the password hash. The password blocklist of the contract is not implemented yet; only the length rules of `domain.NewPassword` apply. + ### Organizations and memberships Implemented as storage, ports, and a source contract (TASK-077): migration `backend/db/migrations/00010_create_organizations.sql`, queries in `backend/db/queries/organizations.sql`, domain types in `backend/internal/domain/organization.go` and `membership.go`, the ports in `backend/internal/port/outbound/organizations.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/organizations.go`, and `ListMyOrganizations`, `CreateOrganization`, `GetOrganization`, and `UpdateOrganization` in the public contract ([api/README.en.md](../../api/README.en.md#organizations)). The create, read, and update usecases with their handlers (TASK-078) and the server-side context and membership checks of every tenant operation (TASK-079) are planned; until then the operations answer 401 or 501 and nothing in bootstrap calls the repositories. The only implemented behavior is the storage and its constraints. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index fbae2df..4a69ccf 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -72,6 +72,8 @@ The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` boot `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). +`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 the verification mail per address and the registrations per client; an empty value means the default. 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-and-verification-resend). + down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop. ### Public perimeter and client address diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index e21f07c..0ac98ef 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -674,7 +674,7 @@ contact_grant относится к паре кандидат-компания ### Хеширование паролей -Реализовано (TASK-052) и покрыто тестами, но в bootstrap не подключено: регистрация (TASK-053) и вход (TASK-055) будут создавать hasher из конфигурации и вызывать его. +Реализовано (TASK-052) и покрыто тестами: регистрация (TASK-053) создает hasher из конфигурации и вызывает его; вход (TASK-055) будет делать то же. - `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. @@ -731,6 +731,32 @@ contact_grant относится к паре кандидат-компания - Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков (TASK-064, TASK-053, TASK-201). - Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или TASK-064, и ни той, ни другой пока нет. +### Регистрация и повторная отправка подтверждения + +Реализовано (TASK-053): `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`. + +Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `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 не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает. Требования для передачи следующим задачам: + +- TASK-054 (`ConfirmEmail`): подтверждение токена применяет отложенные данные нажатого токена, и только их, к строке аккаунта в транзакции подтверждения (хеш пароля, сценарий, шаг онбординга) и обязано требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными, проверяя его по отложенному хешу токена. Тогда жертва, перешедшая по ссылке злоумышленника, не может принять его пароль, а злоумышленник не может подтвердить токен жертвы. Поля пароля в `EmailVerificationRequest` сегодня нет; его добавление - изменение контракта в TASK-054, здесь не делается. Описание `RegisterAccount` в контракте по-прежнему говорит, что повторная регистрация заменяет хеш пароля аккаунта; TASK-054 исправляет его вместе с этим изменением. +- TASK-054 дополнительно: тесты обоих порядков (злоумышленник регистрируется первым, жертва вторым, и наоборот), показывающие, что владелец никогда не получает пароль, который не выбирал; требовать, чтобы запись C1 существовала и относилась к версии регистрации подтверждаемого токена; отклонять токен без отложенных данных, без устаревшего пути в обход пароля; обнулять столбцы `pending_*` токена при его расходовании. +- TASK-055 (вход): неподтвержденный аккаунт никогда не входит. Вход отвечает как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не сравнивает пароль со строкой неподтвержденного аккаунта или с отложенными данными. + +Порядок проверок регистрации: валидация всего тела и версии текста 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`, хешируется секретом и пропускается, когда адрес неизвестен (общий бакет позволил бы одному клиенту заблокировать всех). Отклоненный запрос ничего не считает, отвечает 429 `rate_limited` с `Retry-After` в целых секундах с округлением вверх и не выпускает токен. Счетчики эфемерны: перезапуск Redis их сбрасывает, а квота почтового провайдера остается последней границей. Сбой Redis дает 500 и никогда не пропускает запрос. Ни адрес, ни токен не логируются. + +Политика замены токена. Каждый выпуск токена подтверждения (регистрация, повторная регистрация, повторная отправка) сначала аннулирует все неиспользованные токены подтверждения аккаунта и затем сохраняет новый, поэтому одновременно работает не больше одной ссылки. Повторная отправка не меняет пароль, сценарий, запись согласия и версию регистрации, меняется только токен. Письмо аннулированного токена воркер отправки отменяет, поэтому доставляется только текущая ссылка. Срок жизни токена берется из продуктовой политики (`identity.verification_token_lifetime_hours`, 24 в демонстрационной версии), а не из конфигурации. + +Целевая блокировка. Поскольку счетчики адреса считают каждый запрос независимо от наличия аккаунта, любой может израсходовать 5 писем адреса за 24 часа и так заблокировать регистрацию и повторную отправку его владельца на срок до 24 часов, не зная состояния адреса. Это цена одинакового 429 для любого адреса; принято как известное ограничение анти-энумерации. Оно ограничено (лимит клиента замедляет один источник) и заметно: растет `lincodex_identity_rate_limit_refusals_total{scope="address"}`. Большая доля отказов `scope="client"`, напротив, намекает на сломанную цепочку прокси (все клиенты определились как адрес прокси); настройте оповещение на отношение отказов клиента к отказам адреса и проверьте `TRUSTED_PROXY_CIDRS`. У метки два фиксированных значения, адрес в ней не бывает. Правило оповещения пока не поставляется. + +Без определенного адреса клиента (middleware `ClientIP` не выполнился) лимит клиента пропускается и действуют только лимиты адреса: общий бакет "unknown" позволил бы одному клиенту заблокировать всех, что хуже. `IDENTITY_KEY_SECRET` обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` позволяет стенду разработки взять случайный. Ключи лимитера содержат hash tag Redis (`{key}`), поэтому скрипт с несколькими ключами безопасен для кластера. + +Известные ограничения. Повторная отправка для неизвестного или подтвержденного адреса пропускает работу с токеном и письмом, поэтому ее время отличается от неподтвержденного аккаунта на несколько запросов к базе; регистрация скрывает разницу за хешем пароля. Blocklist паролей из контракта еще не реализован; действуют только правила длины `domain.NewPassword`. + ### Организации и членства Реализовано как хранение, порты и исходный контракт (TASK-077): миграция `backend/db/migrations/00010_create_organizations.sql`, запросы в `backend/db/queries/organizations.sql`, доменные типы в `backend/internal/domain/organization.go` и `membership.go`, порты в `backend/internal/port/outbound/organizations.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/organizations.go`, а также `ListMyOrganizations`, `CreateOrganization`, `GetOrganization` и `UpdateOrganization` в публичном контракте ([api/README.md](../../api/README.md#организации)). Usecase создания, чтения и обновления с обработчиками (TASK-078) и серверные проверки контекста и членства для каждой tenant-операции (TASK-079) запланированы; до этого операции отвечают 401 или 501, а bootstrap не вызывает репозитории. Реализованы только хранение и его ограничения. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index 479838b..25e477c 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -74,6 +74,8 @@ Backend получает `KAFKA_BROKERS` - список адресов bootstrap `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`) ограничивают письма подтверждения на адрес и регистрации на клиента; пустое значение означает значение по умолчанию. Метрика `lincodex_identity_rate_limit_refusals_total{scope}` считает отказы; большая доля `scope="client"` намекает на сломанную цепочку прокси (см. `TRUSTED_PROXY_CIDRS`). См. [ARCHITECTURE.md](ARCHITECTURE.md#регистрация-и-повторная-отправка-подтверждения). + down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова. ### Публичный периметр и адрес клиента diff --git a/observability/scripts/verify-product-metrics.sh b/observability/scripts/verify-product-metrics.sh index 4523e12..5ad0b2f 100755 --- a/observability/scripts/verify-product-metrics.sh +++ b/observability/scripts/verify-product-metrics.sh @@ -30,13 +30,15 @@ fixture_email="Metrics.Check.Fixture@example.com" fixture_email_lower=$(printf '%s' "$fixture_email" | tr '[:upper:]' '[:lower:]') evidence_dir="${METRICS_CHECK_EVIDENCE_DIR:-$(mktemp -d)}" core_started=0 +# .env.example has no usable IDENTITY_KEY_SECRET; the throwaway stack draws its own. +identity_key_secret=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n') monitoring_started=0 core() { APP_PROJECT="$project" APP_NETWORK="$app_network" APP_STORAGE_NETWORK="$storage_network" APP_HTTP_PORT="$port" \ APP_SUBNET=172.29.83.0/24 APP_FRONTEND_IP=172.29.83.10 \ APP_PUBLIC_URL="http://localhost:$port" EMAIL_PROVIDER=resend RESEND_API_KEY=re_placeholder_not_a_key \ - EMAIL_ACCOUNT=metrics-check docker compose --env-file "$env_file" -p "$project" -f "$core_file" "$@" + EMAIL_ACCOUNT=metrics-check IDENTITY_KEY_SECRET="$identity_key_secret" docker compose --env-file "$env_file" -p "$project" -f "$core_file" "$@" } monitoring() {