feat(identity): register accounts and resend verification mail
This commit is contained in:
1 parent
5e202ac972
commit
4436f626a3
55 files changed
+3227
-88
No files matched your search
+27
-1
@@ -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$<salt>$<key>` 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.
|
||||
|
||||
@@ -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
|
||||
|
||||
+27
-1
@@ -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$<salt>$<key>` в 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 не вызывает репозитории. Реализованы только хранение и его ограничения.
|
||||
|
||||
@@ -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 с базой или файлами в рамках обычного останова.
|
||||
|
||||
### Публичный периметр и адрес клиента
|
||||
|
||||
Reference in new issue
Block a user