From d365a05c96ccbdf1beac1ebc2370b2abe21c728e Mon Sep 17 00:00:00 2001 From: shira Date: Sat, 10 Oct 2026 00:52:46 +0300 Subject: [PATCH] feat(identity): confirm the email address with a six-digit code from the message --- api/README.en.md | 4 +- api/README.md | 4 +- api/core/components/examples.yml | 23 + api/core/components/responses.yml | 18 + api/core/components/schemas.yml | 24 + .../components/schemas/identity_schemas.yml | 32 ++ api/core/openapi.bundle.yml | 117 +++++ api/core/openapi.yml | 2 + .../identity_email_verification_codes.yml | 62 +++ backend/README.en.md | 2 +- backend/README.md | 2 +- .../00046_add_email_verification_codes.sql | 70 +++ backend/db/queries/identity.sql | 94 +++- backend/integration_test/email_code_test.go | 363 +++++++++++++++ backend/integration_test/mail_sender_test.go | 5 + .../notification_subject_migration_test.go | 5 + backend/integration_test/registration_test.go | 38 +- .../adapter/primary/http/api/oas_cfg_gen.go | 1 + .../primary/http/api/oas_handlers_gen.go | 195 ++++++++ .../primary/http/api/oas_interfaces_gen.go | 4 + .../adapter/primary/http/api/oas_json_gen.go | 242 ++++++++++ .../primary/http/api/oas_operations_gen.go | 1 + .../primary/http/api/oas_parameters_gen.go | 92 ++++ .../http/api/oas_request_decoders_gen.go | 79 ++++ .../http/api/oas_response_encoders_gen.go | 75 +++ .../primary/http/api/oas_router_gen.go | 197 +++++--- .../primary/http/api/oas_schemas_gen.go | 56 ++- .../primary/http/api/oas_server_gen.go | 32 ++ .../primary/http/api/oas_unimplemented_gen.go | 35 ++ .../primary/http/api/oas_validators_gen.go | 93 ++++ .../http/identity_code_confirmation_test.go | 154 ++++++ .../http/identity_confirmation_test.go | 11 + .../adapter/primary/http/router_test.go | 9 + .../internal/adapter/primary/http/v1/auth.go | 51 ++ .../adapter/primary/http/v1/identity.go | 1 + .../adapter/secondary/postgres/identity.go | 128 ++++- .../secondary/postgres/sqlc/identity.sql.go | 186 +++++++- .../adapter/secondary/postgres/sqlc/models.go | 6 + .../secondary/postgres/sqlc/querier.go | 14 +- backend/internal/bootstrap/identity.go | 1 + backend/internal/domain/email_code.go | 106 +++++ backend/internal/domain/email_code_test.go | 194 ++++++++ backend/internal/domain/email_token.go | 35 +- backend/internal/port/outbound/identity.go | 14 + .../usecase/identity/code_confirmation.go | 191 ++++++++ .../identity/code_confirmation_test.go | 437 ++++++++++++++++++ .../internal/usecase/identity/confirmation.go | 11 +- .../usecase/identity/confirmation_test.go | 4 +- backend/internal/usecase/identity/keyring.go | 23 + .../internal/usecase/identity/keyring_test.go | 38 ++ backend/internal/usecase/identity/register.go | 20 +- .../usecase/notification/mailtemplate/data.go | 36 ++ .../notification/mailtemplate/renderer.go | 8 +- .../mailtemplate/renderer_test.go | 53 ++- .../templates/verification.v2.html.tmpl | 28 ++ .../templates/verification.v2.subject.tmpl | 1 + .../templates/verification.v2.txt.tmpl | 18 + .../testdata/verification.v1.txt.golden | 14 - ...tml.golden => verification.v2.html.golden} | 8 +- .../testdata/verification.v2.txt.golden | 20 + .../usecase/notification/service_mail.go | 15 +- .../usecase/notification/service_mail_test.go | 11 +- docs/en/ARCHITECTURE.md | 8 +- docs/en/DEPLOY.md | 4 +- docs/en/TESTING.md | 4 + docs/ru/ARCHITECTURE.md | 8 +- docs/ru/DEPLOY.md | 4 +- docs/ru/TESTING.md | 4 + frontend/e2e/auth-registration.spec.ts | 204 +++++--- .../confirm-email/ui/confirm-email-form.tsx | 2 +- .../register-account/ui/register-form.tsx | 9 +- .../src/features/verify-email-code/index.ts | 1 + .../model/verification-code.test.ts | 81 ++++ .../model/verification-code.ts | 113 +++++ .../ui/verification-code-form.module.css | 94 ++++ .../ui/verification-code-form.test.tsx | 74 +++ .../ui/verification-code-form.tsx | 275 +++++++++++ frontend/src/pages/auth/ui/register-page.tsx | 30 +- .../src/pages/auth/ui/verify-email-page.tsx | 20 +- .../api/endpoints/identity/identity.msw.ts | 15 + .../shared/api/endpoints/identity/identity.ts | 97 ++++ .../shared/api/identity-code-contract.test.ts | 35 ++ .../identity/confirmEmailByCodeBody.zod.ts | 27 ++ .../identity/confirmEmailByCodeHeaders.zod.ts | 17 + .../emailVerificationCodeRequest.zod.ts | 27 ++ .../src/shared/api/schemas/identity/index.ts | 4 + .../schemas/identity/verificationCode.zod.ts | 18 + 87 files changed, 4764 insertions(+), 224 deletions(-) create mode 100644 api/core/routes/identity_email_verification_codes.yml create mode 100644 backend/db/migrations/00046_add_email_verification_codes.sql create mode 100644 backend/integration_test/email_code_test.go create mode 100644 backend/internal/adapter/primary/http/identity_code_confirmation_test.go create mode 100644 backend/internal/domain/email_code.go create mode 100644 backend/internal/domain/email_code_test.go create mode 100644 backend/internal/usecase/identity/code_confirmation.go create mode 100644 backend/internal/usecase/identity/code_confirmation_test.go create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/verification.v2.html.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/verification.v2.subject.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/verification.v2.txt.tmpl delete mode 100644 backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden rename backend/internal/usecase/notification/mailtemplate/testdata/{verification.v1.html.golden => verification.v2.html.golden} (66%) create mode 100644 backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.txt.golden create mode 100644 frontend/src/features/verify-email-code/index.ts create mode 100644 frontend/src/features/verify-email-code/model/verification-code.test.ts create mode 100644 frontend/src/features/verify-email-code/model/verification-code.ts create mode 100644 frontend/src/features/verify-email-code/ui/verification-code-form.module.css create mode 100644 frontend/src/features/verify-email-code/ui/verification-code-form.test.tsx create mode 100644 frontend/src/features/verify-email-code/ui/verification-code-form.tsx create mode 100644 frontend/src/shared/api/identity-code-contract.test.ts create mode 100644 frontend/src/shared/api/schemas/identity/confirmEmailByCodeBody.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/confirmEmailByCodeHeaders.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/emailVerificationCodeRequest.zod.ts create mode 100644 frontend/src/shared/api/schemas/identity/verificationCode.zod.ts diff --git a/api/README.en.md b/api/README.en.md index 2df7fe0..2e0a91b 100644 --- a/api/README.en.md +++ b/api/README.en.md @@ -102,7 +102,7 @@ The ML service answers its errors with the same `Problem` schema. Its `ProblemCo ### Identity: sessions, cookie, and CSRF -The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders. +The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout`, and `GetCurrentAccount` are implemented in the backend. The session boundary authenticates every operation protected by the contract; its principal comes from a verified account and an active PostgreSQL session. Except for identity and the consent operations below, protected business operations currently pass the security boundary and answer 501 `not_implemented` after request validation. Frontend registration and confirmation screens remain placeholders. | Method and path | operationId | Security | Success | Specific errors | | --- | --- | --- | --- | --- | @@ -110,6 +110,7 @@ The `identity` tag covers registration, email verification, login, logout, and t | `POST /api/v1/identity/registrations` | `RegisterAccount` | public, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | public | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 | | `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | public | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid`, or `validation_failed`; 403 `csrf_check_failed`; 429 | +| `POST /api/v1/identity/email-verifications/code` | `ConfirmEmailByCode` | public | 200 `EmailVerificationResult` | 400 `verification_token_invalid` or `validation_failed`; 403 `csrf_check_failed`; 429 | | `POST /api/v1/identity/sessions` | `Login` | public | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` or `csrf_check_failed`, 429 | | `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | session | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` | | `DELETE /api/v1/identity/sessions/current` | `Logout` | session and CSRF | 204, `Set-Cookie` clears the cookie | 401 `unauthenticated` (also clears the cookie), 403 `csrf_check_failed` | @@ -126,6 +127,7 @@ Registration and verification: - Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions). - Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check. - `ConfirmEmail` takes both `token` and the `password` selected for that registration; clients that sent only a token must be updated. The password follows `LoginPassword`: NFKC normalization and 1 to 128 code points; the registration blocklist is not applied again. `Origin` must match `APP_PUBLIC_URL`; a missing Origin, the literal value null, or a foreign Origin answers 403 `csrf_check_failed`. Confirmation attempts are limited to 5 per token per hour and also use the shared `IDENTITY_CLIENT_HOURLY_LIMIT`; a refused attempt answers 429 `rate_limited` with `Retry-After`. +- `ConfirmEmailByCode` takes `email`, `code` (exactly six digits, `VerificationCode`), and `password`, the password of the registration that issued the code. Every refusal, including an unknown address, a wrong or expired code, a wrong password, and an invalidated token, answers 400 `verification_token_invalid`; a malformed body answers 400 `validation_failed` with the pointer `/code`, `/email`, or `/password`. Five failed checks against one open code invalidate its token, and the link stops working too. The code lives 30 minutes, or until the token ends when that is sooner. The address limit is shared with login (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`), and the client limit is `IDENTITY_CLIENT_HOURLY_LIMIT`. Success answers the same body as `ConfirmEmail` and creates no session. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend). - The verification link is `/verify-email#token=`. The frontend confirmation screen is still a placeholder. A client page must remove the fragment with `history.replaceState`, wait for an explicit user action, and post both token and registration password; a link scanner that only opens the page does not consume the token. - An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error; after confirmation the user can sign in separately. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token. diff --git a/api/README.md b/api/README.md index 4986c13..7476647 100644 --- a/api/README.md +++ b/api/README.md @@ -102,7 +102,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro ### Identity: сессии, cookie и CSRF -Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками. +Тег `identity` описывает регистрацию, подтверждение email, вход, выход и текущий аккаунт. Все операции есть в контракте. `RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`, `GetCurrentSession`, `Logout` и `GetCurrentAccount` реализованы в backend. Session boundary аутентифицирует все операции, защищенные контрактом; principal создается только из действующей PostgreSQL-сессии подтвержденного аккаунта. Помимо identity и перечисленных ниже операций согласий, защищенные бизнес-операции пока проходят security boundary и отвечают 501 `not_implemented` после проверки запроса. Экраны регистрации и подтверждения во frontend остаются заглушками. | Метод и путь | operationId | Защита | Успех | Конкретные ошибки | | --- | --- | --- | --- | --- | @@ -110,6 +110,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro | `POST /api/v1/identity/registrations` | `RegisterAccount` | публичная, Idempotency-Key | 202 `IdentityRequestAccepted` | 400 `validation_failed`, 403 `csrf_check_failed`, 409 `idempotency_in_progress`, 422 `idempotency_key_reused`, 429 | | `POST /api/v1/identity/email-verification-requests` | `ResendEmailVerification` | публичная | 202 `IdentityRequestAccepted` | 400, 403 `csrf_check_failed`, 429 | | `POST /api/v1/identity/email-verifications` | `ConfirmEmail` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_expired`, `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 | +| `POST /api/v1/identity/email-verifications/code` | `ConfirmEmailByCode` | публичная | 200 `EmailVerificationResult` | 400 `verification_token_invalid` или `validation_failed`; 403 `csrf_check_failed`; 429 | | `POST /api/v1/identity/sessions` | `Login` | публичная | 201 `Session`, `Set-Cookie`, `Cache-Control: no-store` | 400, 401 `invalid_credentials`, 403 `email_not_verified` или `csrf_check_failed`, 429 | | `GET /api/v1/identity/sessions/current` | `GetCurrentSession` | сессия | 200 `Session`, `Cache-Control: no-store` | 401 `unauthenticated` | | `DELETE /api/v1/identity/sessions/current` | `Logout` | сессия и CSRF | 204, `Set-Cookie` удаляет cookie | 401 `unauthenticated` (тоже удаляет cookie), 403 `csrf_check_failed` | @@ -126,6 +127,7 @@ ML-сервис отвечает на ошибки той же схемой `Pro - Каждый токен подтверждения привязан к версии регистрации, для которой выпущен, поэтому токен, выпущенный до повторной регистрации, никогда не подтверждает новые учетные данные. Повторная отправка выпускает токен для текущей версии с отложенными данными этой регистрации, аннулирует прежние и больше ничего не меняет. Запланированные значения: токен живет 24 часа; аккаунт, оставшийся неподтвержденным, удаляется вместе с записью согласия и токенами через 7 дней после последней регистрации. Эти сроки берутся из версионированной продуктовой политики (демонстрационная версия 1 семейства `product`), а не из конфигурации; см. [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#версии-продуктовой-политики). - Регистрация требует Idempotency-Key. Для этой анонимной операции ключ ограничивается операцией, самим ключом и HMAC нормализованного email; отпечаток - HMAC-SHA-256 с серверным секретом над каноническим JSON тела. Тело, пароль и их простые хеши не хранятся, а секрет не дает использовать отпечаток для офлайн-проверки пароля. - Запрос `ConfirmEmail` принимает и `token`, и выбранный при этой регистрации `password`; прежние клиенты, отправлявшие только токен, нужно обновить. Пароль обрабатывается по правилам `LoginPassword`: NFKC-нормализация и от 1 до 128 кодовых точек; blocklist регистрации повторно не применяется. `Origin` должен совпадать с `APP_PUBLIC_URL`; отсутствующий Origin, значение null или посторонний Origin дают 403 `csrf_check_failed`. Endpoint ограничивает попытки подтверждения одним токеном до 5 в час и применяет общий лимит клиента `IDENTITY_CLIENT_HOURLY_LIMIT`; отказ по лимиту дает 429 `rate_limited` с `Retry-After`. +- Запрос `ConfirmEmailByCode` принимает `email`, `code` (ровно шесть цифр, `VerificationCode`) и `password` - пароль регистрации, которая выпустила код. Любой отказ, включая неизвестный адрес, неверный или истекший код, неверный пароль и аннулированный токен, отвечает 400 `verification_token_invalid`; некорректное тело отвечает 400 `validation_failed` с указателем `/code`, `/email` или `/password`. Пять неудачных проверок одного открытого кода аннулируют его токен, и ссылка тоже перестает работать. Код действует 30 минут или до конца срока токена, если токен заканчивается раньше. Лимит адреса общий со входом (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`), лимит клиента - `IDENTITY_CLIENT_HOURLY_LIMIT`. Успех отвечает тем же телом, что и `ConfirmEmail`, и сессию не создает. Подробности: [ARCHITECTURE.md](../docs/ru/ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка). - Ссылка подтверждения имеет вид `/verify-email#token=`. Экран подтверждения во frontend пока остается заглушкой. Клиентская страница должна удалить фрагмент через `history.replaceState`, запросить явное действие пользователя и отправить токен вместе с паролем регистрации; сканер ссылок, который только открывает страницу, не расходует токен. - Истекший токен дает `verification_token_expired`; неизвестный, использованный, замененный или устаревший по версии, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`. В обоих случаях клиент предлагает новую ссылку; после подтверждения пользователь может отдельно войти. Повторное подтверждение использованным токеном намеренно не дает идемпотентный 200: по одному токену успешен ровно один запрос. diff --git a/api/core/components/examples.yml b/api/core/components/examples.yml index 74b1aca..f661471 100644 --- a/api/core/components/examples.yml +++ b/api/core/components/examples.yml @@ -156,6 +156,29 @@ VerificationTokenExpired: code: verification_token_expired detail: Request a new verification link. trace_id: 4c5d6e7f-8a9b-4c0d-9e1f-2a3b4c5d6e7f +VerificationCodeInvalid: + summary: The code does not verify the email + value: + type: urn:lincodex:problem:verification_token_invalid + title: Verification code is not valid + status: 400 + code: verification_token_invalid + detail: Check the code and the password, or request a new message. + trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-4c5d6e7f8a9b +VerificationCodeMalformed: + summary: The code is not six digits + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c + errors: + - in: body + pointer: /code + code: invalid + message: The value does not match the contract. VerificationTokenMalformed: summary: The token from the link is malformed value: diff --git a/api/core/components/responses.yml b/api/core/components/responses.yml index 871e65a..aa67346 100644 --- a/api/core/components/responses.yml +++ b/api/core/components/responses.yml @@ -189,6 +189,24 @@ EmailVerificationFailed: $ref: ./examples.yml#/VerificationTokenInvalid validation_failed: $ref: ./examples.yml#/VerificationTokenMalformed +EmailVerificationCodeFailed: + description: >- + The code does not verify the email. Code verification_token_invalid covers + every refusal in the same shape: an unknown address, an address without an + open code, a wrong code, an expired code, a wrong password, and a code that + was burned after five failed attempts. Code validation_failed means the + body does not match the contract, such as a code that is not six digits, + and carries the pointer `/code`, `/email`, or `/password`. Nothing was + changed in any case. + content: + application/problem+json: + schema: + $ref: ./schemas.yml#/Problem + examples: + verification_code_invalid: + $ref: ./examples.yml#/VerificationCodeInvalid + validation_failed: + $ref: ./examples.yml#/VerificationCodeMalformed InvalidCredentials: description: >- The email and password do not match an account; code diff --git a/api/core/components/schemas.yml b/api/core/components/schemas.yml index ad20bb2..a32a0f4 100644 --- a/api/core/components/schemas.yml +++ b/api/core/components/schemas.yml @@ -3729,6 +3729,30 @@ EmailVerificationRequest: minLength: 1 maxLength: 128 description: Password chosen for the registration that issued this token. It is sent in the request body and never appears in the verification link. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist. +VerificationCode: + type: string + minLength: 6 + maxLength: 6 + pattern: ^[0-9]{6}$ + description: Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code. +EmailVerificationCodeRequest: + type: object + description: Address, the six-digit code from its verification message, and the password chosen for the registration that issued the code. The password is checked the same way as in EmailVerificationRequest. + additionalProperties: false + required: + - email + - code + - password + properties: + email: + $ref: '#/EmailAddress' + code: + $ref: '#/VerificationCode' + password: + type: string + minLength: 1 + maxLength: 128 + description: Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist. EmailVerificationResult: type: object description: Result of a successful email verification. It does not start a session; the user signs in next and continues from `onboarding_step`. diff --git a/api/core/components/schemas/identity_schemas.yml b/api/core/components/schemas/identity_schemas.yml index f6947e8..c8f3976 100644 --- a/api/core/components/schemas/identity_schemas.yml +++ b/api/core/components/schemas/identity_schemas.yml @@ -207,6 +207,38 @@ schemas: sent in the request body and never appears in the verification link. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist. + VerificationCode: + type: string + minLength: 6 + maxLength: 6 + pattern: "^[0-9]{6}$" + description: >- + Six-digit code from the verification message, with leading zeros. It is + request input only; the server keeps a keyed digest of it, never the code. + EmailVerificationCodeRequest: + type: object + description: >- + Address, the six-digit code from its verification message, and the + password chosen for the registration that issued the code. The password + is checked the same way as in EmailVerificationRequest. + additionalProperties: false + required: + - email + - code + - password + properties: + email: + $ref: "#/schemas/EmailAddress" + code: + $ref: "#/schemas/VerificationCode" + password: + type: string + minLength: 1 + maxLength: 128 + description: >- + Password chosen for the registration that issued the code. The server + applies NFKC normalization and the login length bounds, without + reapplying the current new-registration blocklist. EmailVerificationResult: type: object description: >- diff --git a/api/core/openapi.bundle.yml b/api/core/openapi.bundle.yml index fdb9649..b46cf51 100644 --- a/api/core/openapi.bundle.yml +++ b/api/core/openapi.bundle.yml @@ -291,6 +291,65 @@ paths: $ref: '#/components/responses/TooManyRequests' default: $ref: '#/components/responses/Problem' + /api/v1/identity/email-verifications/code: + post: + operationId: ConfirmEmailByCode + summary: Verify an email with the six-digit code from the verification message. + description: |- + Public operation without a session. The verification message carries a six-digit code next to the link. The client sends the address, the code, and the password chosen for the registration that issued the code, so the user types only the code after registration. A reloaded page has no password in memory, so it asks for the address, the password, and the code together. + + The server finds the newest open verification token of the unverified account with this normalized address, whose registration is current and which carries a code. It compares the keyed digest of the code with the stored digest, checks the password against the token's pending password hash, and checks that the code has not expired. The code lives 30 minutes, or until the token ends if the token ends sooner. When all three checks pass, the server consumes the token, verifies the email, and applies the pending credentials in one transaction, exactly as the link confirmation does, and answers 200 with the same body. Success does not start a session. + + Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, or a code that was burned. This keeps the answer from showing which addresses have a pending registration. Every failed attempt of an open code counts against that token. The fifth failed attempt burns the token: the code and the link stop working, and the user must request a new message. A refused attempt changes nothing else. + + The same refusal is returned after the rate limits are checked. The operation is limited per client address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with Retry-After. A body that does not match the contract, such as a code that is not six digits, answers 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` otherwise. + security: [] + tags: + - identity + parameters: + - name: Origin + in: header + required: false + description: The exact configured public application origin. This optional parameter is read by the server as empty when absent, so the operation answers csrf_check_failed rather than treating a missing Origin as an allowed request. + schema: + type: string + minLength: 1 + maxLength: 2048 + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/EmailVerificationCodeRequest' + examples: + code: + summary: Address, code from the message, and the registration password + value: + email: candidate@example.com + code: '482915' + password: correct horse battery staple + responses: + '200': + description: The email is verified. + content: + application/json: + schema: + $ref: '#/components/schemas/EmailVerificationResult' + examples: + candidate: + summary: A candidate continues with consents + value: + email_verified: true + scenario: candidate + onboarding_step: candidate_consents + '400': + $ref: '#/components/responses/EmailVerificationCodeFailed' + '403': + $ref: '#/components/responses/CsrfCheckFailed' + '429': + $ref: '#/components/responses/TooManyRequests' + default: + $ref: '#/components/responses/Problem' /api/v1/identity/sessions: post: operationId: Login @@ -10019,6 +10078,30 @@ components: type: string enum: - ok + VerificationCode: + type: string + minLength: 6 + maxLength: 6 + pattern: ^[0-9]{6}$ + description: Six-digit code from the verification message, with leading zeros. It is request input only; the server keeps a keyed digest of it, never the code. + EmailVerificationCodeRequest: + type: object + description: Address, the six-digit code from its verification message, and the password chosen for the registration that issued the code. The password is checked the same way as in EmailVerificationRequest. + additionalProperties: false + required: + - email + - code + - password + properties: + email: + $ref: '#/components/schemas/EmailAddress' + code: + $ref: '#/components/schemas/VerificationCode' + password: + type: string + minLength: 1 + maxLength: 128 + description: Password chosen for the registration that issued the code. The server applies NFKC normalization and the login length bounds, without reapplying the current new-registration blocklist. AssessmentRealMode: type: string description: Server-selected mode available to a real category assessment. @@ -11863,6 +11946,17 @@ components: examples: limit_reached: $ref: '#/components/examples/HiddenOrganizationLimitReached' + EmailVerificationCodeFailed: + description: 'The code does not verify the email. Code verification_token_invalid covers every refusal in the same shape: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, and a code that was burned after five failed attempts. Code validation_failed means the body does not match the contract, such as a code that is not six digits, and carries the pointer `/code`, `/email`, or `/password`. Nothing was changed in any case.' + content: + application/problem+json: + schema: + $ref: '#/components/schemas/Problem' + examples: + verification_code_invalid: + $ref: '#/components/examples/VerificationCodeInvalid' + validation_failed: + $ref: '#/components/examples/VerificationCodeMalformed' securitySchemes: sessionCookie: type: apiKey @@ -12032,6 +12126,29 @@ components: pointer: /token code: invalid message: The value does not match the contract. + VerificationCodeInvalid: + summary: The code does not verify the email + value: + type: urn:lincodex:problem:verification_token_invalid + title: Verification code is not valid + status: 400 + code: verification_token_invalid + detail: Check the code and the password, or request a new message. + trace_id: 6e7f8a9b-0c1d-4e2f-9a3b-4c5d6e7f8a9b + VerificationCodeMalformed: + summary: The code is not six digits + value: + type: urn:lincodex:problem:validation_failed + title: Request validation failed + status: 400 + code: validation_failed + detail: One or more request fields are invalid. + trace_id: 7f8a9b0c-1d2e-4f3a-8b4c-5d6e7f8a9b0c + errors: + - in: body + pointer: /code + code: invalid + message: The value does not match the contract. CandidateSession: summary: Session of a verified candidate value: diff --git a/api/core/openapi.yml b/api/core/openapi.yml index bf83f88..8d8497a 100644 --- a/api/core/openapi.yml +++ b/api/core/openapi.yml @@ -105,6 +105,8 @@ paths: $ref: ./routes/identity_email_verification_requests.yml /api/v1/identity/email-verifications: $ref: ./routes/identity_email_verifications.yml + /api/v1/identity/email-verifications/code: + $ref: ./routes/identity_email_verification_codes.yml /api/v1/identity/sessions: $ref: ./routes/identity_sessions.yml /api/v1/identity/sessions/current: diff --git a/api/core/routes/identity_email_verification_codes.yml b/api/core/routes/identity_email_verification_codes.yml new file mode 100644 index 0000000..a02ead1 --- /dev/null +++ b/api/core/routes/identity_email_verification_codes.yml @@ -0,0 +1,62 @@ +post: + operationId: ConfirmEmailByCode + summary: Verify an email with the six-digit code from the verification message. + description: |- + Public operation without a session. The verification message carries a six-digit code next to the link. The client sends the address, the code, and the password chosen for the registration that issued the code, so the user types only the code after registration. A reloaded page has no password in memory, so it asks for the address, the password, and the code together. + + The server finds the newest open verification token of the unverified account with this normalized address, whose registration is current and which carries a code. It compares the keyed digest of the code with the stored digest, checks the password against the token's pending password hash, and checks that the code has not expired. The code lives 30 minutes, or until the token ends if the token ends sooner. When all three checks pass, the server consumes the token, verifies the email, and applies the pending credentials in one transaction, exactly as the link confirmation does, and answers 200 with the same body. Success does not start a session. + + Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an unknown address, an address without an open code, a wrong code, an expired code, a wrong password, or a code that was burned. This keeps the answer from showing which addresses have a pending registration. Every failed attempt of an open code counts against that token. The fifth failed attempt burns the token: the code and the link stop working, and the user must request a new message. A refused attempt changes nothing else. + + The same refusal is returned after the rate limits are checked. The operation is limited per client address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with Retry-After. A body that does not match the contract, such as a code that is not six digits, answers 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` otherwise. + security: [] + tags: + - identity + parameters: + - name: Origin + in: header + required: false + description: >- + The exact configured public application origin. This optional parameter + is read by the server as empty when absent, so the operation answers + csrf_check_failed rather than treating a missing Origin as an allowed + request. + schema: + type: string + minLength: 1 + maxLength: 2048 + requestBody: + required: true + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmailVerificationCodeRequest + examples: + code: + summary: Address, code from the message, and the registration password + value: + email: candidate@example.com + code: "482915" + password: "correct horse battery staple" + responses: + "200": + description: The email is verified. + content: + application/json: + schema: + $ref: ../components/schemas.yml#/EmailVerificationResult + examples: + candidate: + summary: A candidate continues with consents + value: + email_verified: true + scenario: candidate + onboarding_step: candidate_consents + "400": + $ref: ../components/responses.yml#/EmailVerificationCodeFailed + "403": + $ref: ../components/responses.yml#/CsrfCheckFailed + "429": + $ref: ../components/responses.yml#/TooManyRequests + default: + $ref: ../components/responses.yml#/Problem diff --git a/backend/README.en.md b/backend/README.en.md index 1207174..01b22d0 100644 --- a/backend/README.en.md +++ b/backend/README.en.md @@ -18,7 +18,7 @@ Registration, email confirmation, login, `GET /api/v1/identity/me`, `GET /api/v1 Sessions are stored in PostgreSQL. The browser receives a `__Host-lincodex_session` cookie with `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/`, and no `Domain`; the database stores only the token hash. The default idle timeout is 24 hours and the absolute lifetime is 168 hours. Configure them with `IDENTITY_SESSION_IDLE_TIMEOUT` and `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; the idle timeout cannot exceed the absolute lifetime. -Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, and `Login`) requires exactly one `Origin` header matching `APP_PUBLIC_URL`. Unsafe session operations also require the session-bound HMAC token in `X-CSRF-Token`; all API instances must use the same `IDENTITY_KEY_SECRET`. Origin checks do not trust `Host` or forwarded headers. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour. +Every unsafe public identity operation (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, and `Login`) requires exactly one `Origin` header matching `APP_PUBLIC_URL`. Unsafe session operations also require the session-bound HMAC token in `X-CSRF-Token`; all API instances must use the same `IDENTITY_KEY_SECRET`. Origin checks do not trust `Host` or forwarded headers. A wrong Origin or CSRF token returns `403` and leaves a valid session intact; successful logout revokes it on the server and clears the cookie. Login limits apply separately by client address and normalized email: `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to 30 attempts per hour and `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to 10 attempts per hour. HTTP-flow tests with PostgreSQL and Redis are part of `make -C backend test-int`; compile the integration suite without starting containers with `make -C backend test-int-compile`. diff --git a/backend/README.md b/backend/README.md index 7cf056d..edc1be1 100644 --- a/backend/README.md +++ b/backend/README.md @@ -18,7 +18,7 @@ Сессия хранится в PostgreSQL. Браузер получает cookie `__Host-lincodex_session` с атрибутами `Secure`, `HttpOnly`, `SameSite=Strict`, `Path=/` и без `Domain`; в базе хранится только хеш токена. Время бездействия по умолчанию - 24 часа, абсолютный срок - 168 часов. Эти значения задаются через `IDENTITY_SESSION_IDLE_TIMEOUT` и `IDENTITY_SESSION_ABSOLUTE_LIFETIME`; время бездействия не может превышать абсолютный срок. -Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `Login`) требует ровно один заголовок `Origin`, в точности совпадающий с `APP_PUBLIC_URL`. Небезопасные операции сессии также требуют `X-CSRF-Token`, HMAC-токен, связанный с текущей сессией; все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверка Origin не доверяет `Host` или forwarded-заголовкам. Неверный Origin или CSRF отвечает `403` и сохраняет действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час. +Каждая небезопасная публичная identity-операция (`RegisterAccount`, `ResendEmailVerification`, `ConfirmEmail`, `ConfirmEmailByCode`, `Login`) требует ровно один заголовок `Origin`, в точности совпадающий с `APP_PUBLIC_URL`. Небезопасные операции сессии также требуют `X-CSRF-Token`, HMAC-токен, связанный с текущей сессией; все API-инстансы должны использовать один `IDENTITY_KEY_SECRET`. Проверка Origin не доверяет `Host` или forwarded-заголовкам. Неверный Origin или CSRF отвечает `403` и сохраняет действующую сессию; успешный выход отзывает ее на сервере и очищает cookie. Лимит входа действует отдельно по адресу клиента и нормализованному email: `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию 30 попыток в час и `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` - 10 попыток в час. Проверки HTTP-сценариев с PostgreSQL и Redis входят в `make -C backend test-int`; компиляция integration suite без запуска контейнеров выполняется через `make -C backend test-int-compile`. diff --git a/backend/db/migrations/00046_add_email_verification_codes.sql b/backend/db/migrations/00046_add_email_verification_codes.sql new file mode 100644 index 0000000..0b0939a --- /dev/null +++ b/backend/db/migrations/00046_add_email_verification_codes.sql @@ -0,0 +1,70 @@ +-- +goose Up +-- Email verification codes: a six-digit code that travels with each +-- verification message next to the link. The table keeps only a keyed digest +-- of the code, its expiry, and the count of failed attempts. The count is +-- advanced by a single conditional UPDATE, so concurrent wrong attempts cannot +-- exceed the limit and none is lost. Tokens issued before this migration carry +-- no code and keep working by link only. +-- +-- The three columns are set together for a token that carries a code. The +-- application sets the code expiry to the earlier of the token expiry and the +-- code lifetime, and checks both at every use. +ALTER TABLE email_tokens +ADD COLUMN code_hash bytea, +ADD COLUMN code_expires_at timestamptz, +ADD COLUMN code_failed_attempts smallint NOT NULL DEFAULT 0, +ADD CONSTRAINT email_tokens_code_pair CHECK ( + (code_hash IS NULL) = (code_expires_at IS NULL) +), +ADD CONSTRAINT email_tokens_code_hash_length CHECK ( + code_hash IS NULL OR octet_length(code_hash) = 32 +), +ADD CONSTRAINT email_tokens_code_expiry CHECK ( + code_expires_at IS NULL OR code_expires_at > created_at +), +ADD CONSTRAINT email_tokens_code_purpose CHECK ( + code_hash IS NULL OR purpose = 'email_verification' +), +ADD CONSTRAINT email_tokens_code_attempts_range CHECK ( + code_failed_attempts BETWEEN 0 AND 5 +); + +COMMENT ON COLUMN email_tokens.code_hash IS +'HMAC-SHA-256 of the six-digit verification code under a server-side key; NULL when the token carries no code or the code has ended. The code itself is never stored.'; +COMMENT ON COLUMN email_tokens.code_expires_at IS +'End of the code validity: the earlier of the token expiry and the code lifetime. NULL together with code_hash.'; +COMMENT ON COLUMN email_tokens.code_failed_attempts IS +'Wrong code or password attempts counted against the open code; the token is invalidated when the count reaches the limit of five.'; + +-- +goose Down +-- A rollback removes the codes, so it refuses while a code is still usable. +-- A code expires within its 30-minute lifetime, so waiting for expiry is enough. +-- +goose StatementBegin +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM email_tokens + WHERE code_hash IS NOT NULL + AND consumed_at IS NULL + AND invalidated_at IS NULL + AND code_expires_at > now() + ) THEN + RAISE EXCEPTION USING + ERRCODE = 'object_not_in_prerequisite_state', + MESSAGE = 'email verification codes are still usable', + HINT = 'Wait until the open codes expire, then roll back again.'; + END IF; +END +$$; +-- +goose StatementEnd + +ALTER TABLE email_tokens +DROP CONSTRAINT email_tokens_code_attempts_range, +DROP CONSTRAINT email_tokens_code_purpose, +DROP CONSTRAINT email_tokens_code_expiry, +DROP CONSTRAINT email_tokens_code_hash_length, +DROP CONSTRAINT email_tokens_code_pair, +DROP COLUMN code_failed_attempts, +DROP COLUMN code_expires_at, +DROP COLUMN code_hash; diff --git a/backend/db/queries/identity.sql b/backend/db/queries/identity.sql index 85f35ba..5ad2b29 100644 --- a/backend/db/queries/identity.sql +++ b/backend/db/queries/identity.sql @@ -304,6 +304,8 @@ INSERT INTO email_tokens ( registration_version, created_at, expires_at, + code_hash, + code_expires_at, pending_password_hash, pending_scenario, pending_onboarding_step @@ -315,6 +317,8 @@ INSERT INTO email_tokens ( sqlc.arg(registration_version), sqlc.arg(created_at), sqlc.arg(expires_at), + sqlc.narg(code_hash), + sqlc.narg(code_expires_at), sqlc.narg(pending_password_hash), sqlc.narg(pending_scenario), sqlc.narg(pending_onboarding_step) @@ -349,6 +353,9 @@ SELECT expires_at, consumed_at, invalidated_at, + code_hash, + code_expires_at, + code_failed_attempts, pending_password_hash, pending_scenario, pending_onboarding_step @@ -356,6 +363,83 @@ FROM email_tokens WHERE token_hash = sqlc.arg(token_hash) AND purpose = sqlc.arg(purpose); +-- Reads the newest open verification token that carries a code for the +-- unverified account with this normalized address. The registration version +-- must be current, so a code of an earlier registration never matches. The +-- row is read before the code is compared; the consumption rechecks it. +-- name: GetOpenEmailCodeByAddress :one +SELECT + token.id, + token.user_id, + token.purpose, + token.token_hash, + token.registration_version, + token.created_at, + token.expires_at, + token.consumed_at, + token.invalidated_at, + token.code_hash, + token.code_expires_at, + token.code_failed_attempts, + token.pending_password_hash, + token.pending_scenario, + token.pending_onboarding_step +FROM email_tokens AS token +INNER JOIN users AS owner ON owner.id = token.user_id +WHERE + owner.email_normalized = sqlc.arg(email_normalized) + AND owner.email_verified_at IS NULL + AND owner.registration_version = token.registration_version + AND token.purpose = sqlc.arg(purpose) + AND token.consumed_at IS NULL + AND token.invalidated_at IS NULL + AND token.code_hash IS NOT NULL + AND token.pending_password_hash IS NOT NULL +ORDER BY token.created_at DESC, token.id DESC +LIMIT 1; + +-- Counts one failed code or password attempt against an open code. The +-- single UPDATE reads and writes the counter under the row lock, so concurrent +-- failures serialize and none is lost. The attempt that reaches the limit +-- invalidates the token and drops its code and pending credentials, so the +-- code and the link both stop working. A token that is no longer open matches +-- no row and is left unchanged. +-- name: RecordFailedEmailCodeAttempt :one +UPDATE email_tokens +SET + code_failed_attempts = code_failed_attempts + 1, + invalidated_at = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN sqlc.arg(attempted_at) + ELSE invalidated_at + END, + code_hash = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE code_hash + END, + code_expires_at = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE code_expires_at + END, + pending_password_hash = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE pending_password_hash + END, + pending_scenario = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE pending_scenario + END, + pending_onboarding_step = CASE + WHEN code_failed_attempts + 1 >= sqlc.arg(max_attempts) THEN NULL + ELSE pending_onboarding_step + END +WHERE + id = sqlc.arg(id) + AND consumed_at IS NULL + AND invalidated_at IS NULL + AND code_hash IS NOT NULL + AND code_failed_attempts < sqlc.arg(max_attempts) +RETURNING code_failed_attempts >= sqlc.arg(max_attempts) AS burned; + -- 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 @@ -416,10 +500,12 @@ FROM updated; UPDATE email_tokens SET invalidated_at = sqlc.arg(invalidated_at), - -- An invalidated token keeps no password hash: it can never be confirmed. + -- An invalidated token keeps no password hash or code: it can never be confirmed. pending_password_hash = NULL, pending_scenario = NULL, - pending_onboarding_step = NULL + pending_onboarding_step = NULL, + code_hash = NULL, + code_expires_at = NULL WHERE user_id = sqlc.arg(user_id) AND purpose = sqlc.arg(purpose) @@ -466,7 +552,9 @@ consumed AS ( consumed_at = sqlc.arg(consumed_at), pending_password_hash = NULL, pending_scenario = NULL, - pending_onboarding_step = NULL + pending_onboarding_step = NULL, + code_hash = NULL, + code_expires_at = NULL FROM candidate WHERE token.id = candidate.id RETURNING token.id, token.consumed_at, token.invalidated_at diff --git a/backend/integration_test/email_code_test.go b/backend/integration_test/email_code_test.go new file mode 100644 index 0000000..324abf2 --- /dev/null +++ b/backend/integration_test/email_code_test.go @@ -0,0 +1,363 @@ +//go:build integration + +package integration_test + +import ( + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "regexp" + "sync" + "testing" + "time" +) + +const ( + emailVerificationCodePath = "/api/v1/identity/email-verifications/code" + codeTestTimeout = 5 * time.Minute + // codeWaitAfterMessage waits out the verification message interval of the + // test stand. Its counters use the real clock, as the Redis limiter does. + codeWaitAfterMessage = registrationMinInterval + 100*time.Millisecond +) + +// verificationCodeText finds the code in the text part of the message. +var verificationCodeText = regexp.MustCompile(`Код подтверждения: ([0-9]{6})\b`) + +// codeTokenState is the stored state of one verification token that the code +// path reads and writes. +type codeTokenState struct { + codeStored bool + codeFailedAttempts int + consumed bool + invalidated bool + pendingStored bool + codeLifetimeMinute int64 +} + +func messageCode(t *testing.T, text string) string { + t.Helper() + match := verificationCodeText.FindStringSubmatch(text) + if match == nil { + t.Fatal("the verification message has no six-digit code") + } + return match[1] +} + +func messageToken(t *testing.T, text string) string { + t.Helper() + match := verificationLinkToken.FindStringSubmatch(text) + if match == nil { + t.Fatal("the verification message has no token in its link") + } + return match[1] +} + +// registerAndSendCode registers the address and returns the token of its link +// and the code of its message. +func (harness *registrationHarness) registerAndSendCode(ctx context.Context, t *testing.T, email, scenario, password string) (string, string) { + t.Helper() + text := harness.registerAndReceiveVerification(ctx, t, email, scenario, password) + return messageToken(t, text), messageCode(t, text) +} + +func (harness *registrationHarness) confirmByCode(t *testing.T, email, code, password string) registrationResponse { + t.Helper() + body, err := json.Marshal(struct { + Email string `json:"email"` + Code string `json:"code"` + Password string `json:"password"` + }{Email: email, Code: code, Password: password}) + if err != nil { + t.Fatalf("encode code confirmation request: %v", err) + } + return harness.post(t, emailVerificationCodePath, string(body), nil) +} + +func readCodeTokenState(ctx context.Context, t *testing.T, harness *registrationHarness, rawToken string) codeTokenState { + t.Helper() + hash := sha256.Sum256([]byte(rawToken)) + var state codeTokenState + err := harness.pool.QueryRow(ctx, ` +SELECT + code_hash IS NOT NULL, + code_failed_attempts, + consumed_at IS NOT NULL, + invalidated_at IS NOT NULL, + pending_password_hash IS NOT NULL, + coalesce(extract(epoch FROM (code_expires_at - created_at)) / 60, 0)::bigint +FROM email_tokens +WHERE token_hash = $1`, hash[:]).Scan( + &state.codeStored, &state.codeFailedAttempts, &state.consumed, &state.invalidated, + &state.pendingStored, &state.codeLifetimeMinute, + ) + if err != nil { + t.Fatalf("read code token state: %v", err) + } + return state +} + +// requireCodeRefusal checks the one refusal of the code operation: the same +// status, content type, and problem code whatever the cause, and no session or +// rate-limit header. +func requireCodeRefusal(t *testing.T, response registrationResponse) { + t.Helper() + requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid") + if response.setCookie != "" || response.retryAfter != "" { + t.Fatalf("refusal set a cookie %q or Retry-After %q", response.setCookie, response.retryAfter) + } +} + +// problemShape returns the body of a refusal without its per-request trace_id, +// so refusals of different causes can be compared. +func problemShape(t *testing.T, response registrationResponse) string { + t.Helper() + var problem map[string]any + if err := json.Unmarshal([]byte(response.body), &problem); err != nil { + t.Fatalf("decode refusal %q: %v", response.body, err) + } + delete(problem, "trace_id") + shape, err := json.Marshal(problem) + if err != nil { + t.Fatalf("encode refusal shape: %v", err) + } + return fmt.Sprintf("%d %s %s", response.status, response.contentType, shape) +} + +func TestEmailVerificationCodeOverHTTP(t *testing.T) { + env := bootstrap(t, postgresService, redisService) + ctx, cancel := context.WithTimeout(t.Context(), codeTestTimeout) + defer cancel() + harness := newRegistrationHarness(ctx, t, env, 1000) + publicOrigin := env.Config.AppPublicURL + reset := func(t *testing.T) { + t.Helper() + harness.truncate(ctx, t) + harness.clock.Set(harness.start) + } + + t.Run("the code from the message confirms the registration like the link", func(t *testing.T) { + reset(t) + const email = "code.confirm@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + before := readConfirmationState(ctx, t, harness, email, token) + if before.pendingPasswordHash == nil { + t.Fatal("registration did not store the pending password on the token") + } + state := readCodeTokenState(ctx, t, harness, token) + if !state.codeStored || state.codeLifetimeMinute != 30 || !state.pendingStored { + t.Fatalf("token code state = %+v, want a stored code of 30 minutes", state) + } + + response := harness.confirmByCode(t, email, code, registrationPassword) + requireConfirmationSuccess(t, response, "candidate", "candidate_consents") + after := readConfirmationState(ctx, t, harness, email, token) + assertConfirmationApplied(t, before, after, "candidate", "candidate_consents") + assertSingleConfirmationEvent(ctx, t, harness, email) + if after.sessionCount != 0 { + t.Fatalf("code confirmation created %d sessions, want none", after.sessionCount) + } + afterState := readCodeTokenState(ctx, t, harness, token) + if afterState.codeStored || !afterState.consumed || afterState.pendingStored { + t.Fatalf("consumed token keeps code or pending state: %+v", afterState) + } + harness.assertLogsHoldNoSecrets(t, code, registrationPassword, token) + + replay := harness.confirmByCode(t, email, code, registrationPassword) + requireCodeRefusal(t, replay) + if !sameConfirmationState(after, readConfirmationState(ctx, t, harness, email, token)) { + t.Fatal("replaying a consumed code changed the account") + } + }) + + t.Run("five wrong codes burn the token, and then even the right code and the link fail", func(t *testing.T) { + reset(t) + const email = "code.burn@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + wrong := wrongDigits(code) + for attempt := 1; attempt <= 5; attempt++ { + requireCodeRefusal(t, harness.confirmByCode(t, email, wrong, registrationPassword)) + state := readCodeTokenState(ctx, t, harness, token) + if state.codeFailedAttempts != attempt || state.invalidated != (attempt == 5) { + t.Fatalf("after wrong attempt %d the state is %+v", attempt, state) + } + } + requireCodeRefusal(t, harness.confirmByCode(t, email, code, registrationPassword)) + requireProblemStatus(t, harness.confirm(t, token, registrationPassword, &publicOrigin), http.StatusBadRequest, "verification_token_invalid") + state := readCodeTokenState(ctx, t, harness, token) + if state.consumed || state.codeStored || state.pendingStored { + t.Fatalf("a burned token keeps state: %+v", state) + } + if verified := harness.count(ctx, t, `SELECT count(*) FROM users WHERE email_normalized = $1 AND email_verified_at IS NOT NULL`, email); verified != 0 { + t.Fatal("a burned code verified the address") + } + harness.assertLogsHoldNoSecrets(t, code, wrong, registrationPassword, token) + }) + + t.Run("concurrent wrong codes count at most five attempts", func(t *testing.T) { + reset(t) + const email = "code.concurrent@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "employer", registrationPassword) + wrong := wrongDigits(code) + const parallel = 8 + responses := make([]registrationResponse, parallel) + var group sync.WaitGroup + for index := range parallel { + group.Add(1) + go func() { + defer group.Done() + responses[index] = harness.confirmByCode(t, email, wrong, registrationPassword) + }() + } + group.Wait() + for _, response := range responses { + requireCodeRefusal(t, response) + } + state := readCodeTokenState(ctx, t, harness, token) + if state.codeFailedAttempts != 5 || !state.invalidated { + t.Fatalf("concurrent wrong attempts left %+v, want exactly five counted and the token burned", state) + } + }) + + t.Run("a wrong password with the right code is refused and counted", func(t *testing.T) { + reset(t) + const email = "code.password@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + requireCodeRefusal(t, harness.confirmByCode(t, email, code, "this is the wrong password")) + state := readCodeTokenState(ctx, t, harness, token) + if state.codeFailedAttempts != 1 || state.consumed || state.invalidated { + t.Fatalf("after a wrong password the state is %+v", state) + } + requireConfirmationSuccess(t, harness.confirmByCode(t, email, code, registrationPassword), "candidate", "candidate_consents") + }) + + t.Run("an expired code is refused, while the link stays valid until the token expires", func(t *testing.T) { + reset(t) + const email = "code.expired@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + harness.clock.Set(harness.clock.Now().Add(31 * time.Minute)) + requireCodeRefusal(t, harness.confirmByCode(t, email, code, registrationPassword)) + state := readCodeTokenState(ctx, t, harness, token) + if state.codeFailedAttempts != 1 || state.consumed { + t.Fatalf("expired code state = %+v, want one counted attempt and an open token", state) + } + requireConfirmationSuccess(t, harness.confirm(t, token, registrationPassword, &publicOrigin), "candidate", "candidate_consents") + }) + + t.Run("the link consumes the code and the code consumes the link", func(t *testing.T) { + reset(t) + const linkFirst = "code.link-first@example.com" + token, code := harness.registerAndSendCode(ctx, t, linkFirst, "candidate", registrationPassword) + requireConfirmationSuccess(t, harness.confirm(t, token, registrationPassword, &publicOrigin), "candidate", "candidate_consents") + requireCodeRefusal(t, harness.confirmByCode(t, linkFirst, code, registrationPassword)) + + const codeFirst = "code.code-first@example.com" + token, code = harness.registerAndSendCode(ctx, t, codeFirst, "candidate", registrationPassword) + requireConfirmationSuccess(t, harness.confirmByCode(t, codeFirst, code, registrationPassword), "candidate", "candidate_consents") + requireProblemStatus(t, harness.confirm(t, token, registrationPassword, &publicOrigin), http.StatusBadRequest, "verification_token_invalid") + }) + + t.Run("a resend replaces the code and the earlier code stops working", func(t *testing.T) { + reset(t) + const email = "code.resend@example.com" + _, first := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + time.Sleep(codeWaitAfterMessage) + requestCount := len(harness.fixture.Requests()) + response := harness.resend(t, email) + requireAccepted(t, response) + second := messageCode(t, harness.receiveVerificationText(ctx, t, email, requestCount)) + if first == second { + t.Skip("the two random codes were equal; the replacement cannot be told apart") + } + requireCodeRefusal(t, harness.confirmByCode(t, email, first, registrationPassword)) + requireConfirmationSuccess(t, harness.confirmByCode(t, email, second, registrationPassword), "candidate", "candidate_consents") + }) + + t.Run("a registration replaced by a stranger's address cannot be confirmed with its code", func(t *testing.T) { + reset(t) + const email = "code.hijack@example.com" + const attackerPassword = "attacker registered this address first" + attackerToken, attackerCode := harness.registerAndSendCode(ctx, t, email, "candidate", attackerPassword) + time.Sleep(codeWaitAfterMessage) + harness.clock.Set(harness.clock.Now().Add(time.Minute)) + requestCount := len(harness.fixture.Requests()) + requireAccepted(t, harness.register(t, email, "candidate", "")) + ownerText := harness.receiveVerificationText(ctx, t, email, requestCount) + ownerCode := messageCode(t, ownerText) + ownerToken := messageToken(t, ownerText) + if state := readCodeTokenState(ctx, t, harness, attackerToken); !state.invalidated { + t.Fatal("the owner's registration did not replace the earlier token") + } + requireCodeRefusal(t, harness.confirmByCode(t, email, attackerCode, attackerPassword)) + requireCodeRefusal(t, harness.confirmByCode(t, email, ownerCode, attackerPassword)) + requireConfirmationSuccess(t, harness.confirmByCode(t, email, ownerCode, registrationPassword), "candidate", "candidate_consents") + if ownerState := readCodeTokenState(ctx, t, harness, ownerToken); !ownerState.consumed { + t.Fatal("the owner's code did not consume the owner's token") + } + }) + + t.Run("an unknown address and a wrong code give the same refusal", func(t *testing.T) { + reset(t) + const email = "code.enumeration@example.com" + _, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + unknown := harness.confirmByCode(t, "nobody.registered@example.com", code, registrationPassword) + wrong := harness.confirmByCode(t, email, wrongDigits(code), registrationPassword) + expired := harness.confirmByCode(t, "nobody.either@example.com", wrongDigits(code), "a password nobody set") + if problemShape(t, unknown) != problemShape(t, wrong) || problemShape(t, wrong) != problemShape(t, expired) { + t.Fatalf("refusals differ:\nunknown %s\nwrong %s\nother %s", problemShape(t, unknown), problemShape(t, wrong), problemShape(t, expired)) + } + }) + + t.Run("a malformed code is a validation failure before any lookup", func(t *testing.T) { + reset(t) + for _, body := range []string{ + `{"email":"candidate@example.com","code":"12345","password":"` + registrationPassword + `"}`, + `{"email":"candidate@example.com","code":"1234567","password":"` + registrationPassword + `"}`, + } { + response := harness.post(t, emailVerificationCodePath, body, nil) + requireProblemStatus(t, response, http.StatusBadRequest, "validation_failed") + } + }) + + t.Run("the address limit refuses after ten code requests", func(t *testing.T) { + reset(t) + const email = "code.limit@example.com" + _, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + wrong := wrongDigits(code) + for range registrationEmailHourlyLimit { + response := harness.confirmByCode(t, email, wrong, registrationPassword) + if response.status != http.StatusBadRequest { + t.Fatalf("request within the limit = %d %s", response.status, response.body) + } + } + limited := harness.confirmByCode(t, email, code, registrationPassword) + requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited") + if limited.retryAfter == "" { + t.Fatal("the refused code request has no Retry-After") + } + }) + + t.Run("an origin that is not the public one is refused before the usecase", func(t *testing.T) { + reset(t) + const email = "code.origin@example.com" + token, code := harness.registerAndSendCode(ctx, t, email, "candidate", registrationPassword) + body, err := json.Marshal(map[string]string{"email": email, "code": code, "password": registrationPassword}) + if err != nil { + t.Fatal(err) + } + response := harness.postWithOriginDefault(t, emailVerificationCodePath, string(body), map[string]string{"Origin": "https://foreign.example"}, false) + requireProblemStatus(t, response, http.StatusForbidden, "csrf_check_failed") + if state := readCodeTokenState(ctx, t, harness, token); state.codeFailedAttempts != 0 { + t.Fatal("a refused origin counted an attempt") + } + }) +} + +// wrongDigits returns a six-digit code that differs from code. +func wrongDigits(code string) string { + if code == "000000" { + return "000001" + } + return "000000" +} diff --git a/backend/integration_test/mail_sender_test.go b/backend/integration_test/mail_sender_test.go index 0ca5299..d6ca505 100644 --- a/backend/integration_test/mail_sender_test.go +++ b/backend/integration_test/mail_sender_test.go @@ -1841,6 +1841,10 @@ func (harness *senderHarness) enqueueToken( if err != nil { t.Fatalf("NewEmailToken() error = %v", err) } + code, err := domain.NewVerificationCode() + if err != nil { + t.Fatalf("NewVerificationCode() error = %v", err) + } var deliveryID uuid.UUID err = harness.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { if err := unit.EmailTokens().Insert(ctx, token); err != nil { @@ -1848,6 +1852,7 @@ func (harness *senderHarness) enqueueToken( } deliveryID, err = enqueue(ctx, unit, notification.TokenMailRequest{ Recipient: user.Email, Token: token, RawToken: raw, Lifetime: domain.Hours(lifetime / time.Hour), + Code: code, CodeLifetime: domain.VerificationCodeLifetime, }) return err }) diff --git a/backend/integration_test/notification_subject_migration_test.go b/backend/integration_test/notification_subject_migration_test.go index d137dd1..4b72b4d 100644 --- a/backend/integration_test/notification_subject_migration_test.go +++ b/backend/integration_test/notification_subject_migration_test.go @@ -33,6 +33,11 @@ func TestNotificationSubjectMigrations(t *testing.T) { if _, err := migrator.Up(ctx); err != nil { t.Fatalf("Up() error = %v", err) } + // Migration 00046 (verification codes) is newer than the subject migration + // under test. Roll it back first, so the rollback checks below act on 00045. + if result, err := migrator.DownOne(ctx); err != nil || result.Version != 46 { + t.Fatalf("roll back the newest migration: result %+v, error = %v; want migration 46", result, err) + } now := time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC) userID, deliveryID, invitationID, organizationID := uuid.New(), uuid.New(), uuid.New(), uuid.New() diff --git a/backend/integration_test/registration_test.go b/backend/integration_test/registration_test.go index 790587f..a7fdf08 100644 --- a/backend/integration_test/registration_test.go +++ b/backend/integration_test/registration_test.go @@ -50,8 +50,11 @@ const ( // The production default is a minute. registrationMinInterval = 3 * time.Second registrationDailyLimit = 3 - registrationSecret = "integration-test-identity-key-secret-0123456789" - registrationApplication = "registration_http" + // registrationEmailHourlyLimit is the production default of the login + // limit per address, which code confirmation shares. + registrationEmailHourlyLimit = 10 + registrationSecret = "integration-test-identity-key-secret-0123456789" + registrationApplication = "registration_http" ) var ( @@ -163,6 +166,7 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm }, identity.ConfirmationSettings{ TokenHourlyLimit: 2, ClientHourlyLimit: clientHourlyLimit, + EmailHourlyLimit: registrationEmailHourlyLimit, }) if err != nil { t.Fatalf("NewEmailConfirmation() error = %v", err) @@ -301,23 +305,41 @@ func (harness *registrationHarness) registerAndSendVerification( ctx context.Context, t *testing.T, email, scenario, password string, +) string { + t.Helper() + link := verificationLinkToken.FindStringSubmatch(harness.registerAndReceiveVerification(ctx, t, email, scenario, password)) + if link == nil { + t.Fatal("the received verification message has no token in its link fragment") + } + return link[1] +} + +// registerAndReceiveVerification registers the address, delivers the queued +// message through the fixture, and returns the text of the message. +func (harness *registrationHarness) registerAndReceiveVerification( + ctx context.Context, + t *testing.T, + email, scenario, password string, ) string { t.Helper() requestCount := len(harness.fixture.Requests()) response := harness.registerBody(t, registrationBody(email, scenario, password, registrationC1), "") requireAccepted(t, response) + return harness.receiveVerificationText(ctx, t, email, requestCount) +} + +// receiveVerificationText drains the sending worker and returns the text of the +// one message the fixture received after requestCount requests. +func (harness *registrationHarness) receiveVerificationText(ctx context.Context, t *testing.T, email string, requestCount int) string { + t.Helper() if settled := harness.drain(ctx, t); settled != 1 { t.Fatalf("settled %d deliveries, want 1", settled) } received := harness.fixture.Requests()[requestCount:] if len(received) != 1 || !slices.Equal(received[0].To, []string{email}) { - t.Fatalf("fixture received %d messages for the registration, want one to the registered address", len(received)) + t.Fatalf("fixture received %d messages, want one to the registered address", len(received)) } - link := verificationLinkToken.FindStringSubmatch(received[0].Text) - if link == nil { - t.Fatal("the received verification message has no token in its link fragment") - } - return link[1] + return received[0].Text } // truncate empties the tables of the flow. CASCADE also empties tables that diff --git a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go index e0637f7..90376c2 100644 --- a/backend/internal/adapter/primary/http/api/oas_cfg_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_cfg_gen.go @@ -23,6 +23,7 @@ var regexMap = map[string]ogenregex.Regexp{ "^@[A-Za-z0-9_]{5,32}$": ogenregex.MustCompile("^@[A-Za-z0-9_]{5,32}$"), "^SC-[0-9]{4}-[0-9]{6,10}$": ogenregex.MustCompile("^SC-[0-9]{4}-[0-9]{6,10}$"), "^[0-9]{4}-(0[1-9]|1[0-2])$": ogenregex.MustCompile("^[0-9]{4}-(0[1-9]|1[0-2])$"), + "^[0-9]{6}$": ogenregex.MustCompile("^[0-9]{6}$"), "^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"), "^[A-Za-z0-9._:-]+$": ogenregex.MustCompile("^[A-Za-z0-9._:-]+$"), "^[A-Za-z0-9_-]+$": ogenregex.MustCompile("^[A-Za-z0-9_-]+$"), diff --git a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go index 4062c68..66a3596 100644 --- a/backend/internal/adapter/primary/http/api/oas_handlers_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_handlers_gen.go @@ -1015,6 +1015,201 @@ func (s *Server) handleConfirmEmailRequest(args [0]string, argsEscaped bool, w h } } +// handleConfirmEmailByCodeRequest handles ConfirmEmailByCode operation. +// +// Public operation without a session. The verification message carries a six-digit code next to the +// link. The client sends the address, the code, and the password chosen for the registration that +// issued the code, so the user types only the code after registration. A reloaded page has no password +// in memory, so it asks for the address, the password, and the code together. +// +// The server finds the newest open verification token of the unverified account with this normalized +// address, whose registration is current and which carries a code. It compares the keyed digest of the +// code with the stored digest, checks the password against the token's pending password hash, and +// checks that the code has not expired. The code lives 30 minutes, or until the token ends if the +// token ends sooner. When all three checks pass, the server consumes the token, verifies the email, +// and applies the pending credentials in one transaction, exactly as the link confirmation does, and +// answers 200 with the same body. Success does not start a session. +// +// Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an +// unknown address, an address without an open code, a wrong code, an expired code, a wrong password, +// or a code that was burned. This keeps the answer from showing which addresses have a pending +// registration. Every failed attempt of an open code counts against that token. The fifth failed +// attempt burns the token: the code and the link stop working, and the user must request a new +// message. A refused attempt changes nothing else. +// +// The same refusal is returned after the rate limits are checked. The operation is limited per client +// address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email +// (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with +// Retry-After. A body that does not match the contract, such as a code that is not six digits, answers +// 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires +// an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` +// otherwise. +// +// POST /api/v1/identity/email-verifications/code +func (s *Server) handleConfirmEmailByCodeRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) { + statusWriter := &codeRecorder{ResponseWriter: w} + w = statusWriter + otelAttrs := []attribute.KeyValue{ + otelogen.OperationID("ConfirmEmailByCode"), + semconv.HTTPRequestMethodKey.String("POST"), + semconv.HTTPRouteKey.String("/api/v1/identity/email-verifications/code"), + } + // Add attributes from config. + otelAttrs = append(otelAttrs, s.cfg.Attributes...) + + // Start a span for this request. + ctx, span := s.cfg.Tracer.Start(r.Context(), ConfirmEmailByCodeOperation, + trace.WithAttributes(otelAttrs...), + serverSpanKind, + ) + defer span.End() + + // Add Labeler to context. + labeler := &Labeler{attrs: otelAttrs} + ctx = contextWithLabeler(ctx, labeler) + + // Run stopwatch. + startTime := time.Now() + defer func() { + elapsedDuration := time.Since(startTime) + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + code := statusWriter.status + if code != 0 { + codeAttr := semconv.HTTPResponseStatusCode(code) + attrs = append(attrs, codeAttr) + span.SetAttributes(attrs...) + } + attrOpt := metric.WithAttributes(attrs...) + + // Increment request counter. + s.requests.Add(ctx, 1, attrOpt) + + // Use floating point division here for higher precision (instead of Millisecond method). + s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt) + }() + + var ( + recordError = func(stage string, err error) { + span.RecordError(err) + + // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status + // Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges, + // unless there was another error (e.g., network error receiving the response body; or 3xx codes with + // max redirects exceeded), in which case status MUST be set to Error. + code := statusWriter.status + if code < 100 || code >= 500 { + span.SetStatus(codes.Error, stage) + } + + attrSet := labeler.AttributeSet() + attrs := attrSet.ToSlice() + if code != 0 { + attrs = append(attrs, semconv.HTTPResponseStatusCode(code)) + } + + s.errors.Add(ctx, 1, metric.WithAttributes(attrs...)) + } + err error + opErrContext = ogenerrors.OperationContext{ + Name: ConfirmEmailByCodeOperation, + ID: "ConfirmEmailByCode", + } + ) + params, err := decodeConfirmEmailByCodeParams(args, argsEscaped, r) + if err != nil { + err = &ogenerrors.DecodeParamsError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeParams", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + + var rawBody []byte + request, rawBody, close, err := s.decodeConfirmEmailByCodeRequest(r) + if err != nil { + err = &ogenerrors.DecodeRequestError{ + OperationContext: opErrContext, + Err: err, + } + defer recordError("DecodeRequest", err) + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + defer func() { + if err := close(); err != nil { + recordError("CloseRequest", err) + } + }() + + var response ConfirmEmailByCodeRes + if m := s.cfg.Middleware; m != nil { + mreq := middleware.Request{ + Context: ctx, + OperationName: ConfirmEmailByCodeOperation, + OperationSummary: "Verify an email with the six-digit code from the verification message.", + OperationID: "ConfirmEmailByCode", + Body: request, + RawBody: rawBody, + Params: middleware.Parameters{ + { + Name: "Origin", + In: "header", + }: params.Origin, + }, + Raw: r, + } + + type ( + Request = *EmailVerificationCodeRequest + Params = ConfirmEmailByCodeParams + Response = ConfirmEmailByCodeRes + ) + response, err = middleware.HookMiddleware[ + Request, + Params, + Response, + ]( + m, + mreq, + unpackConfirmEmailByCodeParams, + func(ctx context.Context, request Request, params Params) (response Response, err error) { + response, err = s.h.ConfirmEmailByCode(ctx, request, params) + return response, err + }, + ) + } else { + response, err = s.h.ConfirmEmailByCode(ctx, request, params) + } + if err != nil { + if errRes, ok := errors.Into[*ProblemStatusCode](err); ok { + if err := encodeErrorResponse(errRes, w, span); err != nil { + defer recordError("Internal", err) + } + return + } + if errors.Is(err, ht.ErrNotImplemented) { + s.cfg.ErrorHandler(ctx, w, r, err) + return + } + if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil { + defer recordError("Internal", err) + } + return + } + + if err := encodeConfirmEmailByCodeResponse(response, w, span); err != nil { + defer recordError("EncodeResponse", err) + if !errors.Is(err, ht.ErrInternalServerErrorResponse) { + s.cfg.ErrorHandler(ctx, w, r, err) + } + return + } +} + // handleCreateMyAssessmentAttemptRequest handles CreateMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, diff --git a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go index 728371c..f7ed783 100644 --- a/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_interfaces_gen.go @@ -13,6 +13,10 @@ type CancelMyInvitationRes interface { cancelMyInvitationRes() } +type ConfirmEmailByCodeRes interface { + confirmEmailByCodeRes() +} + type ConfirmEmailRes interface { confirmEmailRes() } diff --git a/backend/internal/adapter/primary/http/api/oas_json_gen.go b/backend/internal/adapter/primary/http/api/oas_json_gen.go index d751cc6..2d88454 100644 --- a/backend/internal/adapter/primary/http/api/oas_json_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_json_gen.go @@ -15417,6 +15417,82 @@ func (s *ConfirmEmailBadRequest) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes ConfirmEmailByCodeBadRequest as json. +func (s *ConfirmEmailByCodeBadRequest) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ConfirmEmailByCodeBadRequest from json. +func (s *ConfirmEmailByCodeBadRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConfirmEmailByCodeBadRequest to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ConfirmEmailByCodeBadRequest(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConfirmEmailByCodeBadRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConfirmEmailByCodeBadRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + +// Encode encodes ConfirmEmailByCodeForbidden as json. +func (s *ConfirmEmailByCodeForbidden) Encode(e *jx.Encoder) { + unwrapped := (*Problem)(s) + + unwrapped.Encode(e) +} + +// Decode decodes ConfirmEmailByCodeForbidden from json. +func (s *ConfirmEmailByCodeForbidden) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode ConfirmEmailByCodeForbidden to nil") + } + var unwrapped Problem + if err := func() error { + if err := unwrapped.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = ConfirmEmailByCodeForbidden(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *ConfirmEmailByCodeForbidden) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *ConfirmEmailByCodeForbidden) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes ConfirmEmailForbidden as json. func (s *ConfirmEmailForbidden) Encode(e *jx.Encoder) { unwrapped := (*Problem)(s) @@ -19271,6 +19347,132 @@ func (s *EmailAddress) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode implements json.Marshaler. +func (s *EmailVerificationCodeRequest) Encode(e *jx.Encoder) { + e.ObjStart() + s.encodeFields(e) + e.ObjEnd() +} + +// encodeFields encodes fields. +func (s *EmailVerificationCodeRequest) encodeFields(e *jx.Encoder) { + { + e.FieldStart("email") + s.Email.Encode(e) + } + { + e.FieldStart("code") + s.Code.Encode(e) + } + { + e.FieldStart("password") + e.Str(s.Password) + } +} + +var jsonFieldsNameOfEmailVerificationCodeRequest = [3]string{ + 0: "email", + 1: "code", + 2: "password", +} + +// Decode decodes EmailVerificationCodeRequest from json. +func (s *EmailVerificationCodeRequest) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode EmailVerificationCodeRequest to nil") + } + var requiredBitSet [1]uint8 + + if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error { + switch string(k) { + case "email": + requiredBitSet[0] |= 1 << 0 + if err := func() error { + if err := s.Email.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"email\"") + } + case "code": + requiredBitSet[0] |= 1 << 1 + if err := func() error { + if err := s.Code.Decode(d); err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"code\"") + } + case "password": + requiredBitSet[0] |= 1 << 2 + if err := func() error { + v, err := d.Str() + s.Password = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "decode field \"password\"") + } + default: + return errors.Errorf("unexpected field %q", k) + } + return nil + }); err != nil { + return errors.Wrap(err, "decode EmailVerificationCodeRequest") + } + // Validate required fields. + var failures []validate.FieldError + for i, mask := range [1]uint8{ + 0b00000111, + } { + if result := (requiredBitSet[i] & mask) ^ mask; result != 0 { + // Mask only required fields and check equality to mask using XOR. + // + // If XOR result is not zero, result is not equal to expected, so some fields are missed. + // Bits of fields which would be set are actually bits of missed fields. + missed := bits.OnesCount8(result) + for bitN := 0; bitN < missed; bitN++ { + bitIdx := bits.TrailingZeros8(result) + fieldIdx := i*8 + bitIdx + var name string + if fieldIdx < len(jsonFieldsNameOfEmailVerificationCodeRequest) { + name = jsonFieldsNameOfEmailVerificationCodeRequest[fieldIdx] + } else { + name = strconv.Itoa(fieldIdx) + } + failures = append(failures, validate.FieldError{ + Name: name, + Error: validate.ErrFieldRequired, + }) + // Reset bit. + result &^= 1 << bitIdx + } + } + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s *EmailVerificationCodeRequest) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *EmailVerificationCodeRequest) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode implements json.Marshaler. func (s *EmailVerificationRequest) Encode(e *jx.Encoder) { e.ObjStart() @@ -62758,6 +62960,46 @@ func (s *UpdateOrganizationUnauthorized) UnmarshalJSON(data []byte) error { return s.Decode(d) } +// Encode encodes VerificationCode as json. +func (s VerificationCode) Encode(e *jx.Encoder) { + unwrapped := string(s) + + e.Str(unwrapped) +} + +// Decode decodes VerificationCode from json. +func (s *VerificationCode) Decode(d *jx.Decoder) error { + if s == nil { + return errors.New("invalid: unable to decode VerificationCode to nil") + } + var unwrapped string + if err := func() error { + v, err := d.Str() + unwrapped = string(v) + if err != nil { + return err + } + return nil + }(); err != nil { + return errors.Wrap(err, "alias") + } + *s = VerificationCode(unwrapped) + return nil +} + +// MarshalJSON implements stdjson.Marshaler. +func (s VerificationCode) MarshalJSON() ([]byte, error) { + e := jx.Encoder{} + s.Encode(&e) + return e.Bytes(), nil +} + +// UnmarshalJSON implements stdjson.Unmarshaler. +func (s *VerificationCode) UnmarshalJSON(data []byte) error { + d := jx.DecodeBytes(data) + return s.Decode(d) +} + // Encode encodes VerificationToken as json. func (s VerificationToken) Encode(e *jx.Encoder) { unwrapped := string(s) diff --git a/backend/internal/adapter/primary/http/api/oas_operations_gen.go b/backend/internal/adapter/primary/http/api/oas_operations_gen.go index 1e7949b..93307f8 100644 --- a/backend/internal/adapter/primary/http/api/oas_operations_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_operations_gen.go @@ -10,6 +10,7 @@ const ( AcknowledgeMyAssessmentSignalNoticeOperation OperationName = "AcknowledgeMyAssessmentSignalNotice" CancelMyInvitationOperation OperationName = "CancelMyInvitation" ConfirmEmailOperation OperationName = "ConfirmEmail" + ConfirmEmailByCodeOperation OperationName = "ConfirmEmailByCode" CreateMyAssessmentAttemptOperation OperationName = "CreateMyAssessmentAttempt" CreateMySupportCaseOperation OperationName = "CreateMySupportCase" CreateOrganizationOperation OperationName = "CreateOrganization" diff --git a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go index 18d95b9..2985560 100644 --- a/backend/internal/adapter/primary/http/api/oas_parameters_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_parameters_gen.go @@ -407,6 +407,98 @@ func decodeConfirmEmailParams(args [0]string, argsEscaped bool, r *http.Request) return params, nil } +// ConfirmEmailByCodeParams is parameters of ConfirmEmailByCode operation. +type ConfirmEmailByCodeParams struct { + // The exact configured public application origin. This optional parameter is read by the server as + // empty when absent, so the operation answers csrf_check_failed rather than treating a missing Origin + // as an allowed request. + Origin OptString `json:",omitempty,omitzero"` +} + +func unpackConfirmEmailByCodeParams(packed middleware.Parameters) (params ConfirmEmailByCodeParams) { + { + key := middleware.ParameterKey{ + Name: "Origin", + In: "header", + } + if v, ok := packed[key]; ok { + params.Origin = v.(OptString) + } + } + return params +} + +func decodeConfirmEmailByCodeParams(args [0]string, argsEscaped bool, r *http.Request) (params ConfirmEmailByCodeParams, _ error) { + h := uri.NewHeaderDecoder(r.Header) + // Decode header: Origin. + if err := func() error { + cfg := uri.HeaderParameterDecodingConfig{ + Name: "Origin", + Explode: false, + } + if err := h.HasParam(cfg); err == nil { + if err := h.DecodeParam(cfg, func(d uri.Decoder) error { + var paramsDotOriginVal string + if err := func() error { + val, err := d.DecodeValue() + if err != nil { + return err + } + + c, err := conv.ToString(val) + if err != nil { + return err + } + + paramsDotOriginVal = c + return nil + }(); err != nil { + return err + } + params.Origin.SetTo(paramsDotOriginVal) + return nil + }); err != nil { + return err + } + if err := func() error { + if value, ok := params.Origin.Get(); ok { + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 2048, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(value)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return err + } + } + return nil + }(); err != nil { + return params, &ogenerrors.DecodeParamError{ + Name: "Origin", + In: "header", + Err: err, + } + } + return params, nil +} + // CreateMyAssessmentAttemptParams is parameters of CreateMyAssessmentAttempt operation. type CreateMyAssessmentAttemptParams struct { // Client-generated key that makes a retried mutating command safe; a UUID v4 is recommended. The value diff --git a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go index 0b43279..068bbf5 100644 --- a/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_request_decoders_gen.go @@ -330,6 +330,85 @@ func (s *Server) decodeConfirmEmailRequest(r *http.Request) ( } } +func (s *Server) decodeConfirmEmailByCodeRequest(r *http.Request) ( + req *EmailVerificationCodeRequest, + rawBody []byte, + close func() error, + rerr error, +) { + var closers []func() error + close = func() error { + var merr error + // Close in reverse order, to match defer behavior. + for i := len(closers) - 1; i >= 0; i-- { + c := closers[i] + merr = errors.Join(merr, c()) + } + return merr + } + defer func() { + if rerr != nil { + rerr = errors.Join(rerr, close()) + } + }() + ct, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) + if err != nil { + return req, rawBody, close, errors.Wrap(err, "parse media type") + } + switch { + case ct == "application/json": + if r.ContentLength == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + buf, err := io.ReadAll(r.Body) + defer func() { + _ = r.Body.Close() + }() + if err != nil { + return req, rawBody, close, err + } + + // Reset the body to allow for downstream reading. + r.Body = io.NopCloser(bytes.NewBuffer(buf)) + + if len(buf) == 0 { + return req, rawBody, close, validate.ErrBodyRequired + } + + rawBody = append(rawBody, buf...) + d := jx.DecodeBytes(buf) + + var request EmailVerificationCodeRequest + if err := func() error { + if err := request.Decode(d); err != nil { + return err + } + if err := d.Skip(); err != io.EOF { + return errors.New("unexpected trailing data") + } + return nil + }(); err != nil { + err = &ogenerrors.DecodeBodyError{ + ContentType: ct, + Body: buf, + Err: err, + } + return req, rawBody, close, err + } + if err := func() error { + if err := request.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + return req, rawBody, close, errors.Wrap(err, "validate") + } + return &request, rawBody, close, nil + default: + return req, rawBody, close, validate.InvalidContentType(ct) + } +} + func (s *Server) decodeCreateMyAssessmentAttemptRequest(r *http.Request) ( req AssessmentAttemptCreate, rawBody []byte, diff --git a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go index fcb7c77..68cea59 100644 --- a/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_response_encoders_gen.go @@ -474,6 +474,81 @@ func encodeConfirmEmailResponse(response ConfirmEmailRes, w http.ResponseWriter, } } +func encodeConfirmEmailByCodeResponse(response ConfirmEmailByCodeRes, w http.ResponseWriter, span trace.Span) error { + switch response := response.(type) { + case *EmailVerificationResult: + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.WriteHeader(200) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ConfirmEmailByCodeBadRequest: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(400) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *ConfirmEmailByCodeForbidden: + w.Header().Set("Content-Type", "application/problem+json") + w.WriteHeader(403) + + e := new(jx.Encoder) + response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + case *TooManyRequestsHeaders: + w.Header().Set("Content-Type", "application/problem+json") + w.Header().Set("Access-Control-Expose-Headers", "Retry-After") + // Encoding response headers. + { + h := uri.NewHeaderEncoder(w.Header()) + // Encode "Retry-After" header. + { + cfg := uri.HeaderParameterEncodingConfig{ + Name: "Retry-After", + Explode: false, + } + if err := h.EncodeParam(cfg, func(e uri.Encoder) error { + if val, ok := response.RetryAfter.Get(); ok { + return e.EncodeValue(conv.Int32ToString(val)) + } + return nil + }); err != nil { + return errors.Wrap(err, "encode Retry-After header") + } + } + } + w.WriteHeader(429) + + e := new(jx.Encoder) + response.Response.Encode(e) + if _, err := e.WriteTo(w); err != nil { + return errors.Wrap(err, "write") + } + + return nil + + default: + return errors.Errorf("unexpected response type: %T", response) + } +} + func encodeCreateMyAssessmentAttemptResponse(response CreateMyAssessmentAttemptRes, w http.ResponseWriter, span trace.Span) error { switch response := response.(type) { case *AssessmentAttemptHeaders: diff --git a/backend/internal/adapter/primary/http/api/oas_router_gen.go b/backend/internal/adapter/primary/http/api/oas_router_gen.go index 8efaf33..d84ad07 100644 --- a/backend/internal/adapter/primary/http/api/oas_router_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_router_gen.go @@ -11,46 +11,49 @@ import ( ) var ( - rn83AllowedHeaders = map[string]string{ + rn84AllowedHeaders = map[string]string{ "POST": "Content-Type", } rn9AllowedHeaders = map[string]string{ "POST": "Content-Type,Origin", } - rn79AllowedHeaders = map[string]string{ + rn10AllowedHeaders = map[string]string{ + "POST": "Content-Type,Origin", + } + rn80AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key", } - rn69AllowedHeaders = map[string]string{ + rn70AllowedHeaders = map[string]string{ "POST": "Content-Type", } - rn27AllowedHeaders = map[string]string{ + rn28AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn81AllowedHeaders = map[string]string{ + rn82AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn11AllowedHeaders = map[string]string{ + rn12AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn95AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn23AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn94AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn22AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn93AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn78AllowedHeaders = map[string]string{ + rn79AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn5AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn85AllowedHeaders = map[string]string{ + rn86AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", } - rn53AllowedHeaders = map[string]string{ + rn54AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "Content-Type,X-Csrf-Token", } @@ -60,65 +63,65 @@ var ( rn7AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn19AllowedHeaders = map[string]string{ + rn20AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn95AllowedHeaders = map[string]string{ + rn96AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn72AllowedHeaders = map[string]string{ + rn73AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } - rn56AllowedHeaders = map[string]string{ + rn57AllowedHeaders = map[string]string{ "DELETE": "X-Csrf-Token", "PUT": "X-Csrf-Token", } - rn90AllowedHeaders = map[string]string{ - "PUT": "Content-Type,X-Csrf-Token", - } rn91AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn38AllowedHeaders = map[string]string{ + rn92AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } rn39AllowedHeaders = map[string]string{ "PUT": "Content-Type,X-Csrf-Token", } - rn12AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + rn40AllowedHeaders = map[string]string{ + "PUT": "Content-Type,X-Csrf-Token", } rn13AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn15AllowedHeaders = map[string]string{ - "PATCH": "Content-Type,X-Csrf-Token", + rn14AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } rn16AllowedHeaders = map[string]string{ - "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", - } - rn46AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn77AllowedHeaders = map[string]string{ + rn17AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn88AllowedHeaders = map[string]string{ + rn47AllowedHeaders = map[string]string{ + "PATCH": "Content-Type,X-Csrf-Token", + } + rn78AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn96AllowedHeaders = map[string]string{ + rn89AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn86AllowedHeaders = map[string]string{ + rn97AllowedHeaders = map[string]string{ + "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", + } + rn87AllowedHeaders = map[string]string{ "POST": "Content-Type,X-Csrf-Token", } - rn18AllowedHeaders = map[string]string{ + rn19AllowedHeaders = map[string]string{ "POST": "Content-Type,Idempotency-Key,X-Csrf-Token", } - rn49AllowedHeaders = map[string]string{ + rn50AllowedHeaders = map[string]string{ "PATCH": "Content-Type,X-Csrf-Token", } - rn75AllowedHeaders = map[string]string{ + rn76AllowedHeaders = map[string]string{ "POST": "X-Csrf-Token", } ) @@ -275,7 +278,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn83AllowedHeaders, + allowedHeaders: rn84AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -293,7 +296,6 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { } if len(elem) == 0 { - // Leaf node. switch r.Method { case "POST": s.handleConfirmEmailRequest([0]string{}, elemIsEscaped, w, r) @@ -308,6 +310,33 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { return } + switch elem[0] { + case '/': // Prefix: "/code" + + if l := len("/code"); len(elem) >= l && elem[0:l] == "/code" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch r.Method { + case "POST": + s.handleConfirmEmailByCodeRequest([0]string{}, elemIsEscaped, w, r) + default: + s.notAllowed(w, r, notAllowedParams{ + allowedMethods: "POST", + allowedHeaders: rn10AllowedHeaders, + acceptPost: "application/json", + acceptPatch: "", + }) + } + + return + } + + } } @@ -352,7 +381,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn79AllowedHeaders, + allowedHeaders: rn80AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -376,7 +405,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn69AllowedHeaders, + allowedHeaders: rn70AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -403,7 +432,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,GET", - allowedHeaders: rn27AllowedHeaders, + allowedHeaders: rn28AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -456,7 +485,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn81AllowedHeaders, + allowedHeaders: rn82AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -504,7 +533,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn11AllowedHeaders, + allowedHeaders: rn12AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -578,7 +607,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn94AllowedHeaders, + allowedHeaders: rn95AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -605,7 +634,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn22AllowedHeaders, + allowedHeaders: rn23AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -671,7 +700,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn93AllowedHeaders, + allowedHeaders: rn94AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -698,7 +727,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn78AllowedHeaders, + allowedHeaders: rn79AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -909,7 +938,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE", - allowedHeaders: rn85AllowedHeaders, + allowedHeaders: rn86AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -943,7 +972,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn53AllowedHeaders, + allowedHeaders: rn54AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1124,7 +1153,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn19AllowedHeaders, + allowedHeaders: rn20AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1151,7 +1180,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn95AllowedHeaders, + allowedHeaders: rn96AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1229,7 +1258,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn72AllowedHeaders, + allowedHeaders: rn73AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1407,7 +1436,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "DELETE,PUT", - allowedHeaders: rn56AllowedHeaders, + allowedHeaders: rn57AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1498,7 +1527,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn90AllowedHeaders, + allowedHeaders: rn91AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1525,7 +1554,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "PUT", - allowedHeaders: rn91AllowedHeaders, + allowedHeaders: rn92AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1556,7 +1585,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn38AllowedHeaders, + allowedHeaders: rn39AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1585,7 +1614,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PUT", - allowedHeaders: rn39AllowedHeaders, + allowedHeaders: rn40AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -1611,7 +1640,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn12AllowedHeaders, + allowedHeaders: rn13AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1675,7 +1704,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn13AllowedHeaders, + allowedHeaders: rn14AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1714,7 +1743,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn15AllowedHeaders, + allowedHeaders: rn16AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1822,7 +1851,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn16AllowedHeaders, + allowedHeaders: rn17AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1863,7 +1892,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn46AllowedHeaders, + allowedHeaders: rn47AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -1943,7 +1972,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn77AllowedHeaders, + allowedHeaders: rn78AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -1971,7 +2000,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn88AllowedHeaders, + allowedHeaders: rn89AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2001,7 +2030,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn96AllowedHeaders, + allowedHeaders: rn97AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2034,7 +2063,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn86AllowedHeaders, + allowedHeaders: rn87AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2076,7 +2105,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,POST", - allowedHeaders: rn18AllowedHeaders, + allowedHeaders: rn19AllowedHeaders, acceptPost: "application/json", acceptPatch: "", }) @@ -2118,7 +2147,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "GET,PATCH", - allowedHeaders: rn49AllowedHeaders, + allowedHeaders: rn50AllowedHeaders, acceptPost: "", acceptPatch: "application/json", }) @@ -2195,7 +2224,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { default: s.notAllowed(w, r, notAllowedParams{ allowedMethods: "POST", - allowedHeaders: rn75AllowedHeaders, + allowedHeaders: rn76AllowedHeaders, acceptPost: "", acceptPatch: "", }) @@ -2458,7 +2487,6 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { } if len(elem) == 0 { - // Leaf node. switch method { case "POST": r.name = ConfirmEmailOperation @@ -2473,6 +2501,33 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) { return } } + switch elem[0] { + case '/': // Prefix: "/code" + + if l := len("/code"); len(elem) >= l && elem[0:l] == "/code" { + elem = elem[l:] + } else { + break + } + + if len(elem) == 0 { + // Leaf node. + switch method { + case "POST": + r.name = ConfirmEmailByCodeOperation + r.summary = "Verify an email with the six-digit code from the verification message." + r.operationID = "ConfirmEmailByCode" + r.operationGroup = "" + r.pathPattern = "/api/v1/identity/email-verifications/code" + r.args = args + r.count = 0 + return r, true + default: + return + } + } + + } } diff --git a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go index 847e415..cff2b5f 100644 --- a/backend/internal/adapter/primary/http/api/oas_schemas_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_schemas_gen.go @@ -7857,6 +7857,14 @@ type ConfirmEmailBadRequest Problem func (*ConfirmEmailBadRequest) confirmEmailRes() {} +type ConfirmEmailByCodeBadRequest Problem + +func (*ConfirmEmailByCodeBadRequest) confirmEmailByCodeRes() {} + +type ConfirmEmailByCodeForbidden Problem + +func (*ConfirmEmailByCodeForbidden) confirmEmailByCodeRes() {} + type ConfirmEmailForbidden Problem func (*ConfirmEmailForbidden) confirmEmailRes() {} @@ -9612,6 +9620,48 @@ func (s *DirectionCode) UnmarshalText(data []byte) error { type EmailAddress string +// Address, the six-digit code from its verification message, and the password chosen for the +// registration that issued the code. The password is checked the same way as in +// EmailVerificationRequest. +// Ref: #/components/schemas/EmailVerificationCodeRequest +type EmailVerificationCodeRequest struct { + Email EmailAddress `json:"email"` + Code VerificationCode `json:"code"` + // Password chosen for the registration that issued the code. The server applies NFKC normalization and + // the login length bounds, without reapplying the current new-registration blocklist. + Password string `json:"password"` +} + +// GetEmail returns the value of Email. +func (s *EmailVerificationCodeRequest) GetEmail() EmailAddress { + return s.Email +} + +// GetCode returns the value of Code. +func (s *EmailVerificationCodeRequest) GetCode() VerificationCode { + return s.Code +} + +// GetPassword returns the value of Password. +func (s *EmailVerificationCodeRequest) GetPassword() string { + return s.Password +} + +// SetEmail sets the value of Email. +func (s *EmailVerificationCodeRequest) SetEmail(val EmailAddress) { + s.Email = val +} + +// SetCode sets the value of Code. +func (s *EmailVerificationCodeRequest) SetCode(val VerificationCode) { + s.Code = val +} + +// SetPassword sets the value of Password. +func (s *EmailVerificationCodeRequest) SetPassword(val string) { + s.Password = val +} + // One-time token copied from the verification link and the password chosen for the registration that // issued it. The password is never included in the link. // Ref: #/components/schemas/EmailVerificationRequest @@ -9699,7 +9749,8 @@ func (s *EmailVerificationResult) SetOnboardingStep(val OnboardingStep) { s.OnboardingStep = val } -func (*EmailVerificationResult) confirmEmailRes() {} +func (*EmailVerificationResult) confirmEmailByCodeRes() {} +func (*EmailVerificationResult) confirmEmailRes() {} // Always true in a successful response. type EmailVerificationResultEmailVerified bool @@ -31017,6 +31068,7 @@ func (s *TooManyRequestsHeaders) SetResponse(val Problem) { func (*TooManyRequestsHeaders) acceptMyInvitationRes() {} func (*TooManyRequestsHeaders) cancelMyInvitationRes() {} +func (*TooManyRequestsHeaders) confirmEmailByCodeRes() {} func (*TooManyRequestsHeaders) confirmEmailRes() {} func (*TooManyRequestsHeaders) createMyAssessmentAttemptRes() {} func (*TooManyRequestsHeaders) createMySupportCaseRes() {} @@ -31136,6 +31188,8 @@ type UpdateOrganizationUnauthorized Problem func (*UpdateOrganizationUnauthorized) updateOrganizationRes() {} +type VerificationCode string + type VerificationToken string type ViewMyInvitationBadRequest Problem diff --git a/backend/internal/adapter/primary/http/api/oas_server_gen.go b/backend/internal/adapter/primary/http/api/oas_server_gen.go index 9b4dd32..3131ce5 100644 --- a/backend/internal/adapter/primary/http/api/oas_server_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_server_gen.go @@ -153,6 +153,38 @@ type Handler interface { // // POST /api/v1/identity/email-verifications ConfirmEmail(ctx context.Context, req *EmailVerificationRequest, params ConfirmEmailParams) (ConfirmEmailRes, error) + // ConfirmEmailByCode implements ConfirmEmailByCode operation. + // + // Public operation without a session. The verification message carries a six-digit code next to the + // link. The client sends the address, the code, and the password chosen for the registration that + // issued the code, so the user types only the code after registration. A reloaded page has no password + // in memory, so it asks for the address, the password, and the code together. + // + // The server finds the newest open verification token of the unverified account with this normalized + // address, whose registration is current and which carries a code. It compares the keyed digest of the + // code with the stored digest, checks the password against the token's pending password hash, and + // checks that the code has not expired. The code lives 30 minutes, or until the token ends if the + // token ends sooner. When all three checks pass, the server consumes the token, verifies the email, + // and applies the pending credentials in one transaction, exactly as the link confirmation does, and + // answers 200 with the same body. Success does not start a session. + // + // Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an + // unknown address, an address without an open code, a wrong code, an expired code, a wrong password, + // or a code that was burned. This keeps the answer from showing which addresses have a pending + // registration. Every failed attempt of an open code counts against that token. The fifth failed + // attempt burns the token: the code and the link stop working, and the user must request a new + // message. A refused attempt changes nothing else. + // + // The same refusal is returned after the rate limits are checked. The operation is limited per client + // address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email + // (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with + // Retry-After. A body that does not match the contract, such as a code that is not six digits, answers + // 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires + // an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` + // otherwise. + // + // POST /api/v1/identity/email-verifications/code + ConfirmEmailByCode(ctx context.Context, req *EmailVerificationCodeRequest, params ConfirmEmailByCodeParams) (ConfirmEmailByCodeRes, error) // CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, diff --git a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go index 54d022f..12610ab 100644 --- a/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_unimplemented_gen.go @@ -170,6 +170,41 @@ func (UnimplementedHandler) ConfirmEmail(ctx context.Context, req *EmailVerifica return r, ht.ErrNotImplemented } +// ConfirmEmailByCode implements ConfirmEmailByCode operation. +// +// Public operation without a session. The verification message carries a six-digit code next to the +// link. The client sends the address, the code, and the password chosen for the registration that +// issued the code, so the user types only the code after registration. A reloaded page has no password +// in memory, so it asks for the address, the password, and the code together. +// +// The server finds the newest open verification token of the unverified account with this normalized +// address, whose registration is current and which carries a code. It compares the keyed digest of the +// code with the stored digest, checks the password against the token's pending password hash, and +// checks that the code has not expired. The code lives 30 minutes, or until the token ends if the +// token ends sooner. When all three checks pass, the server consumes the token, verifies the email, +// and applies the pending credentials in one transaction, exactly as the link confirmation does, and +// answers 200 with the same body. Success does not start a session. +// +// Each refusal answers 400 `verification_token_invalid` with the same body, whatever the cause: an +// unknown address, an address without an open code, a wrong code, an expired code, a wrong password, +// or a code that was burned. This keeps the answer from showing which addresses have a pending +// registration. Every failed attempt of an open code counts against that token. The fifth failed +// attempt burns the token: the code and the link stop working, and the user must request a new +// message. A refused attempt changes nothing else. +// +// The same refusal is returned after the rate limits are checked. The operation is limited per client +// address (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized email +// (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`, shared with login); a refused request answers 429 with +// Retry-After. A body that does not match the contract, such as a code that is not six digits, answers +// 400 `validation_failed` before any lookup. Like every unsafe public identity operation, it requires +// an Origin equal to the configured public application origin and answers 403 `csrf_check_failed` +// otherwise. +// +// POST /api/v1/identity/email-verifications/code +func (UnimplementedHandler) ConfirmEmailByCode(ctx context.Context, req *EmailVerificationCodeRequest, params ConfirmEmailByCodeParams) (r ConfirmEmailByCodeRes, _ error) { + return r, ht.ErrNotImplemented +} + // CreateMyAssessmentAttempt implements CreateMyAssessmentAttempt operation. // // Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token, diff --git a/backend/internal/adapter/primary/http/api/oas_validators_gen.go b/backend/internal/adapter/primary/http/api/oas_validators_gen.go index fa5d156..a755f16 100644 --- a/backend/internal/adapter/primary/http/api/oas_validators_gen.go +++ b/backend/internal/adapter/primary/http/api/oas_validators_gen.go @@ -7204,6 +7204,22 @@ func (s *ConfirmEmailBadRequest) Validate() error { return nil } +func (s *ConfirmEmailByCodeBadRequest) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + +func (s *ConfirmEmailByCodeForbidden) Validate() error { + alias := (*Problem)(s) + if err := alias.Validate(); err != nil { + return err + } + return nil +} + func (s *ConfirmEmailForbidden) Validate() error { alias := (*Problem)(s) if err := alias.Validate(); err != nil { @@ -8757,6 +8773,63 @@ func (s EmailAddress) Validate() error { return nil } +func (s *EmailVerificationCodeRequest) Validate() error { + if s == nil { + return validate.ErrNilPointer + } + + var failures []validate.FieldError + if err := func() error { + if err := s.Email.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "email", + Error: err, + }) + } + if err := func() error { + if err := s.Code.Validate(); err != nil { + return err + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "code", + Error: err, + }) + } + if err := func() error { + if err := (validate.String{ + MinLength: 1, + MinLengthSet: true, + MaxLength: 128, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: nil, + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(s.Password)); err != nil { + return errors.Wrap(err, "string") + } + return nil + }(); err != nil { + failures = append(failures, validate.FieldError{ + Name: "password", + Error: err, + }) + } + if len(failures) > 0 { + return &validate.Error{Fields: failures} + } + return nil +} + func (s *EmailVerificationRequest) Validate() error { if s == nil { return validate.ErrNilPointer @@ -24718,6 +24791,26 @@ func (s *UpdateOrganizationUnauthorized) Validate() error { return nil } +func (s VerificationCode) Validate() error { + alias := (string)(s) + if err := (validate.String{ + MinLength: 6, + MinLengthSet: true, + MaxLength: 6, + MaxLengthSet: true, + Email: false, + Hostname: false, + Regex: regexMap["^[0-9]{6}$"], + MinNumeric: 0, + MinNumericSet: false, + MaxNumeric: 0, + MaxNumericSet: false, + }).Validate(string(alias)); err != nil { + return errors.Wrap(err, "string") + } + return nil +} + func (s VerificationToken) Validate() error { alias := (string)(s) if err := (validate.String{ diff --git a/backend/internal/adapter/primary/http/identity_code_confirmation_test.go b/backend/internal/adapter/primary/http/identity_code_confirmation_test.go new file mode 100644 index 0000000..c8a8508 --- /dev/null +++ b/backend/internal/adapter/primary/http/identity_code_confirmation_test.go @@ -0,0 +1,154 @@ +package httpadapter + +import ( + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + "time" + + "lincodex/backend/internal/adapter/primary/http/api" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/usecase/identity" +) + +const confirmationCodePath = "/api/v1/identity/email-verifications/code" + +const confirmationCodeBody = `{"email":"candidate@example.com","code":"482915","password":"correct horse battery staple"}` + +func TestConfirmEmailByCodeRequiresConfiguredOriginBeforeUsecase(t *testing.T) { + confirmation := &scriptedConfirmation{} + router := newConfirmationRouter(t, confirmation) + for _, test := range []struct { + name string + origin string + set bool + }{ + {name: "missing"}, + {name: "null", origin: "null", set: true}, + {name: "foreign", origin: "https://foreign.example", set: true}, + {name: "same host with different port", origin: "https://app.example:443", set: true}, + } { + t.Run(test.name, func(t *testing.T) { + headers := map[string]string{} + if test.set { + headers["Origin"] = test.origin + } + response := serveIdentityRequest(t, router, identityRequest{ + method: http.MethodPost, path: confirmationCodePath, body: confirmationCodeBody, headers: headers, + }) + requireProblem(t, response, http.StatusForbidden, api.ProblemCodeCsrfCheckFailed) + if confirmation.codeCalls != 0 { + t.Fatal("code confirmation usecase ran before the origin check") + } + }) + } +} + +func TestConfirmEmailByCodePassesRequestAndReturnsSavedDestination(t *testing.T) { + confirmation := &scriptedConfirmation{codeResult: identity.ConfirmationResult{ + Scenario: domain.ScenarioEmployer, + OnboardingStep: domain.OnboardingStepEmployerCompany, + }} + response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{ + method: http.MethodPost, + path: confirmationCodePath, + body: confirmationCodeBody, + headers: map[string]string{"Origin": "https://app.example"}, + }) + if response.Code != http.StatusOK || response.Header().Get("Set-Cookie") != "" { + t.Fatalf("response = %d, Set-Cookie %q, body %s", response.Code, response.Header().Get("Set-Cookie"), response.Body.String()) + } + var result map[string]any + if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil { + t.Fatalf("decode response: %v", err) + } + if result["email_verified"] != true || result["scenario"] != "employer" || result["onboarding_step"] != "employer_company" { + t.Fatalf("response body = %v", result) + } + command := confirmation.codeCommand + if confirmation.codeCalls != 1 || command.Email != "candidate@example.com" || command.Code != "482915" || + command.Password != "correct horse battery staple" || command.ClientKey == "" { + t.Fatalf("code confirmation call = %d, command %+v", confirmation.codeCalls, command) + } + if confirmation.calls != 0 { + t.Fatal("code confirmation called the link usecase") + } +} + +func TestConfirmEmailByCodeRejectsMalformedBodyBeforeUsecase(t *testing.T) { + for _, test := range []struct { + name string + body string + }{ + {name: "five digits", body: `{"email":"candidate@example.com","code":"48291","password":"correct horse battery staple"}`}, + {name: "seven digits", body: `{"email":"candidate@example.com","code":"4829150","password":"correct horse battery staple"}`}, + {name: "letters", body: `{"email":"candidate@example.com","code":"48291A","password":"correct horse battery staple"}`}, + {name: "separator", body: `{"email":"candidate@example.com","code":"482 915","password":"correct horse battery staple"}`}, + {name: "missing password", body: `{"email":"candidate@example.com","code":"482915"}`}, + {name: "token instead of code", body: `{"token":"` + strings.Repeat("A", 64) + `","password":"correct horse battery staple"}`}, + } { + t.Run(test.name, func(t *testing.T) { + confirmation := &scriptedConfirmation{} + response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{ + method: http.MethodPost, + path: confirmationCodePath, + body: test.body, + headers: map[string]string{"Origin": "https://app.example"}, + }) + requireProblem(t, response, http.StatusBadRequest, api.ProblemCodeValidationFailed) + if confirmation.codeCalls != 0 { + t.Fatal("code confirmation usecase ran for a malformed body") + } + }) + } +} + +func TestConfirmEmailByCodeMapsExpectedUsecaseFailures(t *testing.T) { + for _, test := range []struct { + name string + err error + statusCode int + code api.ProblemCode + retryAfter string + }{ + {name: "invalid code", err: identity.ErrVerificationTokenInvalid, statusCode: http.StatusBadRequest, code: api.ProblemCodeVerificationTokenInvalid}, + {name: "invalid field from usecase", err: &identity.InvalidFieldError{Pointer: "/code", Err: domain.ErrInvalidVerificationCode}, statusCode: http.StatusBadRequest, code: api.ProblemCodeValidationFailed}, + {name: "limited", err: &identity.RateLimitedError{RetryAfter: 1500 * time.Millisecond}, statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "2"}, + } { + t.Run(test.name, func(t *testing.T) { + confirmation := &scriptedConfirmation{codeErr: test.err} + response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{ + method: http.MethodPost, + path: confirmationCodePath, + body: confirmationCodeBody, + headers: map[string]string{"Origin": "https://app.example"}, + }) + requireProblem(t, response, test.statusCode, test.code) + if got := response.Header().Get("Retry-After"); got != test.retryAfter { + t.Fatalf("Retry-After = %q, want %q", got, test.retryAfter) + } + if confirmation.codeCalls != 1 { + t.Fatalf("code confirmation calls = %d, want 1", confirmation.codeCalls) + } + }) + } +} + +// An expired code never reaches the client as its own refusal: the usecase +// maps it to verification_token_invalid, and an unexpected storage error stays +// internal. +func TestConfirmEmailByCodeDoesNotConvertUnexpectedUsecaseErrors(t *testing.T) { + confirmation := &scriptedConfirmation{codeErr: errors.New("storage unavailable")} + response := serveIdentityRequest(t, newConfirmationRouter(t, confirmation), identityRequest{ + method: http.MethodPost, + path: confirmationCodePath, + body: confirmationCodeBody, + headers: map[string]string{"Origin": "https://app.example"}, + }) + requireProblem(t, response, http.StatusInternalServerError, api.ProblemCodeInternal) + if strings.Contains(response.Body.String(), "storage unavailable") { + t.Fatal("internal error text leaked into the response") + } +} diff --git a/backend/internal/adapter/primary/http/identity_confirmation_test.go b/backend/internal/adapter/primary/http/identity_confirmation_test.go index 8e0e210..88dd5eb 100644 --- a/backend/internal/adapter/primary/http/identity_confirmation_test.go +++ b/backend/internal/adapter/primary/http/identity_confirmation_test.go @@ -24,6 +24,11 @@ type scriptedConfirmation struct { command identity.ConfirmCommand result identity.ConfirmationResult calls int + + codeErr error + codeCommand identity.ConfirmCodeCommand + codeResult identity.ConfirmationResult + codeCalls int } func (confirmation *scriptedConfirmation) Confirm(_ context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error) { @@ -32,6 +37,12 @@ func (confirmation *scriptedConfirmation) Confirm(_ context.Context, command ide return confirmation.result, confirmation.err } +func (confirmation *scriptedConfirmation) ConfirmByCode(_ context.Context, command identity.ConfirmCodeCommand) (identity.ConfirmationResult, error) { + confirmation.codeCalls++ + confirmation.codeCommand = command + return confirmation.codeResult, confirmation.codeErr +} + func newConfirmationRouter(t *testing.T, confirmation v1.EmailConfirmation) http.Handler { t.Helper() logger := slog.New(slog.DiscardHandler) diff --git a/backend/internal/adapter/primary/http/router_test.go b/backend/internal/adapter/primary/http/router_test.go index 1efe68c..666c90e 100644 --- a/backend/internal/adapter/primary/http/router_test.go +++ b/backend/internal/adapter/primary/http/router_test.go @@ -185,6 +185,15 @@ func TestIdentityOperationsBeforeImplementation(t *testing.T) { statusCode: http.StatusNotImplemented, code: api.ProblemCodeNotImplemented, }, + { + name: "public email confirmation by code", + request: identityRequest{ + method: http.MethodPost, path: "/api/v1/identity/email-verifications/code", + body: `{"email":"candidate@example.com","code":"482915","password":"correct horse battery staple"}`, + }, + statusCode: http.StatusNotImplemented, + code: api.ProblemCodeNotImplemented, + }, { name: "public login", request: identityRequest{ diff --git a/backend/internal/adapter/primary/http/v1/auth.go b/backend/internal/adapter/primary/http/v1/auth.go index 85db3b4..65e5b63 100644 --- a/backend/internal/adapter/primary/http/v1/auth.go +++ b/backend/internal/adapter/primary/http/v1/auth.go @@ -46,6 +46,17 @@ func (handler *Handler) ConfirmEmail( return handler.identity.ConfirmEmail(ctx, request, params) } +func (handler *Handler) ConfirmEmailByCode( + ctx context.Context, + request *api.EmailVerificationCodeRequest, + params api.ConfirmEmailByCodeParams, +) (api.ConfirmEmailByCodeRes, error) { + if handler.identity == nil || handler.identity.confirmation == nil { + return handler.UnimplementedHandler.ConfirmEmailByCode(ctx, request, params) + } + return handler.identity.ConfirmEmailByCode(ctx, request, params) +} + func (handler *Handler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) { if handler.identity == nil || handler.identity.sessions == nil { return handler.UnimplementedHandler.Login(ctx, request) @@ -158,6 +169,46 @@ func (handler *IdentityHandler) ConfirmEmail( return nil, err } +// ConfirmEmailByCode verifies the address with the six-digit code. Its success +// body and its refusal shape match ConfirmEmail: every refusal is +// verification_token_invalid, so the answer never shows which addresses have a +// pending registration. +func (handler *IdentityHandler) ConfirmEmailByCode( + ctx context.Context, + request *api.EmailVerificationCodeRequest, + _ api.ConfirmEmailByCodeParams, +) (api.ConfirmEmailByCodeRes, error) { + if handler.confirmation == nil { + return nil, errors.New("IdentityHandler.ConfirmEmailByCode - confirmation is not configured") + } + if !originAllowed(ctx, handler.publicOrigin) { + return (*api.ConfirmEmailByCodeForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil + } + + result, err := handler.confirmation.ConfirmByCode(ctx, identity.ConfirmCodeCommand{ + Email: string(request.Email), + Code: string(request.Code), + Password: request.Password, + ClientKey: clientKey(ctx), + }) + switch { + case err == nil: + return &api.EmailVerificationResult{ + EmailVerified: api.EmailVerificationResultEmailVerifiedTrue, + Scenario: api.AccountScenario(result.Scenario), + OnboardingStep: api.OnboardingStep(result.OnboardingStep), + }, nil + case errors.Is(err, identity.ErrInvalidField): + return (*api.ConfirmEmailByCodeBadRequest)(&invalidFieldProblem(ctx, err).Response), nil + case errors.Is(err, identity.ErrVerificationTokenInvalid): + return (*api.ConfirmEmailByCodeBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil + } + if limited, ok := rateLimited(ctx, err); ok { + return limited, nil + } + return nil, err +} + func (handler *IdentityHandler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) { if !originAllowed(ctx, handler.publicOrigin) { return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil diff --git a/backend/internal/adapter/primary/http/v1/identity.go b/backend/internal/adapter/primary/http/v1/identity.go index 28a42bd..7dbbd92 100644 --- a/backend/internal/adapter/primary/http/v1/identity.go +++ b/backend/internal/adapter/primary/http/v1/identity.go @@ -16,6 +16,7 @@ type AccountRegistration interface { // EmailConfirmation is what IdentityHandler needs from the confirmation usecase. type EmailConfirmation interface { Confirm(ctx context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error) + ConfirmByCode(ctx context.Context, command identity.ConfirmCodeCommand) (identity.ConfirmationResult, error) } // IdentityHandlerOption configures an optional identity operation. diff --git a/backend/internal/adapter/secondary/postgres/identity.go b/backend/internal/adapter/secondary/postgres/identity.go index 5391d3e..d14e47d 100644 --- a/backend/internal/adapter/secondary/postgres/identity.go +++ b/backend/internal/adapter/secondary/postgres/identity.go @@ -395,7 +395,7 @@ func (repository emailTokenRepository) FindByHash( if owner.RegistrationVersion != row.RegistrationVersion { return domain.EmailToken{}, fmt.Errorf("%s - token belongs to an earlier registration: %w", location, outbound.ErrEmailTokenInvalidated) } - return emailTokenFromRow(row) + return emailTokenFromRow(emailTokenModelFromHashRow(row)) } func (repository emailTokenRepository) Insert(ctx context.Context, token domain.EmailToken) error { @@ -411,6 +411,10 @@ func (repository emailTokenRepository) Insert(ctx context.Context, token domain. CreatedAt: pgTime(token.CreatedAt), ExpiresAt: pgTime(token.ExpiresAt), } + if code := token.Code; code != nil { + params.CodeHash = code.Hash[:] + params.CodeExpiresAt = pgTime(code.ExpiresAt) + } 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} @@ -501,7 +505,7 @@ func (repository emailTokenRepository) Consume( ConsumedAt: pgTime(at), }) if err == nil { - return emailTokenFromRow(sqlc.EmailToken(row)) + return emailTokenFromRow(consumedEmailTokenRow(row)) } if !errors.Is(err, pgx.ErrNoRows) { return domain.EmailToken{}, fmt.Errorf("emailTokenRepository.Consume - update email token: %w", mapIdentityError(err)) @@ -512,6 +516,84 @@ func (repository emailTokenRepository) Consume( return domain.EmailToken{}, errors.New("emailTokenRepository.Consume - token became consumable after a failed attempt") } +// emailTokenModelFromHashRow maps the row of GetEmailTokenByHash, which selects +// the token by its hash, to the table model. +func emailTokenModelFromHashRow(row sqlc.GetEmailTokenByHashRow) sqlc.EmailToken { + return sqlc.EmailToken{ + ID: row.ID, + UserID: row.UserID, + Purpose: row.Purpose, + TokenHash: row.TokenHash, + RegistrationVersion: row.RegistrationVersion, + CreatedAt: row.CreatedAt, + ExpiresAt: row.ExpiresAt, + ConsumedAt: row.ConsumedAt, + InvalidatedAt: row.InvalidatedAt, + CodeHash: row.CodeHash, + CodeExpiresAt: row.CodeExpiresAt, + CodeFailedAttempts: row.CodeFailedAttempts, + PendingPasswordHash: row.PendingPasswordHash, + PendingScenario: row.PendingScenario, + PendingOnboardingStep: row.PendingOnboardingStep, + } +} + +// emailTokenModelFromOpenCodeRow maps the row of GetOpenEmailCodeByAddress to +// the table model. The columns are the same as in GetEmailTokenByHash. +func emailTokenModelFromOpenCodeRow(row sqlc.GetOpenEmailCodeByAddressRow) sqlc.EmailToken { + return sqlc.EmailToken{ + ID: row.ID, + UserID: row.UserID, + Purpose: row.Purpose, + TokenHash: row.TokenHash, + RegistrationVersion: row.RegistrationVersion, + CreatedAt: row.CreatedAt, + ExpiresAt: row.ExpiresAt, + ConsumedAt: row.ConsumedAt, + InvalidatedAt: row.InvalidatedAt, + CodeHash: row.CodeHash, + CodeExpiresAt: row.CodeExpiresAt, + CodeFailedAttempts: row.CodeFailedAttempts, + PendingPasswordHash: row.PendingPasswordHash, + PendingScenario: row.PendingScenario, + PendingOnboardingStep: row.PendingOnboardingStep, + } +} + +// consumedEmailTokenRow maps the row of ConsumeEmailToken, which holds the token +// as it was before the update, to the table model. The update clears the code, +// so the returned row has none to map. +func consumedEmailTokenRow(row sqlc.ConsumeEmailTokenRow) sqlc.EmailToken { + return sqlc.EmailToken{ + ID: row.ID, + UserID: row.UserID, + Purpose: row.Purpose, + TokenHash: row.TokenHash, + RegistrationVersion: row.RegistrationVersion, + CreatedAt: row.CreatedAt, + ExpiresAt: row.ExpiresAt, + ConsumedAt: row.ConsumedAt, + InvalidatedAt: row.InvalidatedAt, + PendingPasswordHash: row.PendingPasswordHash, + PendingScenario: row.PendingScenario, + PendingOnboardingStep: row.PendingOnboardingStep, + } +} + +// emailCodeFromColumns decodes the code state of a token row. A NULL digest +// means the token carries no code. +func emailCodeFromColumns(digest []byte, expiresAt pgtype.Timestamptz) (*domain.EmailCode, error) { + if len(digest) == 0 { + return nil, nil + } + var hash domain.VerificationCodeHash + if len(digest) != len(hash) || !expiresAt.Valid { + return nil, errors.New("postgres.emailCodeFromColumns - stored code state is incomplete") + } + copy(hash[:], digest) + return &domain.EmailCode{Hash: hash, ExpiresAt: expiresAt.Time}, nil +} + // explainUnconsumable classifies a token that the atomic consume did not // match. A nil result means the token is consumable again, which only a // concurrent transaction that changed and then rolled back the row can cause. @@ -540,6 +622,43 @@ func (repository emailTokenRepository) explainUnconsumable( } } +// FindOpenCodeByAddress reads the newest open token with a code of the +// unverified account at the address. The account is found by the normalized +// address; the code itself is compared by the usecase. +func (repository emailTokenRepository) FindOpenCodeByAddress(ctx context.Context, email domain.EmailAddress) (domain.EmailToken, error) { + const location = "emailTokenRepository.FindOpenCodeByAddress" + row, err := repository.queries.GetOpenEmailCodeByAddress(ctx, sqlc.GetOpenEmailCodeByAddressParams{ + EmailNormalized: email.Normalized(), + Purpose: string(domain.EmailTokenPurposeEmailVerification), + }) + if err != nil { + return domain.EmailToken{}, fmt.Errorf("%s - select open code: %w", location, mapNoRows(err, outbound.ErrEmailTokenNotFound)) + } + return emailTokenFromRow(emailTokenModelFromOpenCodeRow(row)) +} + +// RecordFailedCodeAttempt counts a failed attempt in one statement. A token +// that is no longer open matches no row, which is not an error: the attempt +// then counts nothing, and the caller refuses the request either way. +func (repository emailTokenRepository) RecordFailedCodeAttempt(ctx context.Context, id uuid.UUID, at time.Time) (bool, error) { + const location = "emailTokenRepository.RecordFailedCodeAttempt" + if err := requireTime(location, at, domain.ErrInvalidEmailToken); err != nil { + return false, err + } + burned, err := repository.queries.RecordFailedEmailCodeAttempt(ctx, sqlc.RecordFailedEmailCodeAttemptParams{ + MaxAttempts: domain.VerificationCodeMaxFailedAttempts, + AttemptedAt: pgTime(at), + ID: pgUUID(id), + }) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("%s - count failed attempt: %w", location, mapIdentityError(err)) + } + return burned, nil +} + func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) { purpose, err := domain.ParseEmailTokenPurpose(row.Purpose) if err != nil { @@ -553,8 +672,13 @@ func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) { if err != nil { return domain.EmailToken{}, err } + code, err := emailCodeFromColumns(row.CodeHash, row.CodeExpiresAt) + if err != nil { + return domain.EmailToken{}, err + } return domain.EmailToken{ Pending: pending, + Code: code, 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 6d323f2..1b0cfbc 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/identity.sql.go @@ -207,7 +207,9 @@ consumed AS ( consumed_at = $3, pending_password_hash = NULL, pending_scenario = NULL, - pending_onboarding_step = NULL + pending_onboarding_step = NULL, + code_hash = NULL, + code_expires_at = NULL FROM candidate WHERE token.id = candidate.id RETURNING token.id, token.consumed_at, token.invalidated_at @@ -459,6 +461,9 @@ SELECT expires_at, consumed_at, invalidated_at, + code_hash, + code_expires_at, + code_failed_attempts, pending_password_hash, pending_scenario, pending_onboarding_step @@ -472,11 +477,29 @@ type GetEmailTokenByHashParams struct { Purpose string } +type GetEmailTokenByHashRow 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 + CodeHash []byte + CodeExpiresAt pgtype.Timestamptz + CodeFailedAttempts int16 + PendingPasswordHash pgtype.Text + PendingScenario pgtype.Text + PendingOnboardingStep pgtype.Text +} + // Reads a token before password verification; Consume rechecks it in the // confirmation transaction and clears pending credentials when it succeeds. -func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error) { +func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (GetEmailTokenByHashRow, error) { row := q.db.QueryRow(ctx, getEmailTokenByHash, arg.TokenHash, arg.Purpose) - var i EmailToken + var i GetEmailTokenByHashRow err := row.Scan( &i.ID, &i.UserID, @@ -487,6 +510,9 @@ func (q *Queries) GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHa &i.ExpiresAt, &i.ConsumedAt, &i.InvalidatedAt, + &i.CodeHash, + &i.CodeExpiresAt, + &i.CodeFailedAttempts, &i.PendingPasswordHash, &i.PendingScenario, &i.PendingOnboardingStep, @@ -597,6 +623,88 @@ func (q *Queries) GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdemp return i, err } +const getOpenEmailCodeByAddress = `-- name: GetOpenEmailCodeByAddress :one +SELECT + token.id, + token.user_id, + token.purpose, + token.token_hash, + token.registration_version, + token.created_at, + token.expires_at, + token.consumed_at, + token.invalidated_at, + token.code_hash, + token.code_expires_at, + token.code_failed_attempts, + token.pending_password_hash, + token.pending_scenario, + token.pending_onboarding_step +FROM email_tokens AS token +INNER JOIN users AS owner ON owner.id = token.user_id +WHERE + owner.email_normalized = $1 + AND owner.email_verified_at IS NULL + AND owner.registration_version = token.registration_version + AND token.purpose = $2 + AND token.consumed_at IS NULL + AND token.invalidated_at IS NULL + AND token.code_hash IS NOT NULL + AND token.pending_password_hash IS NOT NULL +ORDER BY token.created_at DESC, token.id DESC +LIMIT 1 +` + +type GetOpenEmailCodeByAddressParams struct { + EmailNormalized string + Purpose string +} + +type GetOpenEmailCodeByAddressRow 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 + CodeHash []byte + CodeExpiresAt pgtype.Timestamptz + CodeFailedAttempts int16 + PendingPasswordHash pgtype.Text + PendingScenario pgtype.Text + PendingOnboardingStep pgtype.Text +} + +// Reads the newest open verification token that carries a code for the +// unverified account with this normalized address. The registration version +// must be current, so a code of an earlier registration never matches. The +// row is read before the code is compared; the consumption rechecks it. +func (q *Queries) GetOpenEmailCodeByAddress(ctx context.Context, arg GetOpenEmailCodeByAddressParams) (GetOpenEmailCodeByAddressRow, error) { + row := q.db.QueryRow(ctx, getOpenEmailCodeByAddress, arg.EmailNormalized, arg.Purpose) + var i GetOpenEmailCodeByAddressRow + err := row.Scan( + &i.ID, + &i.UserID, + &i.Purpose, + &i.TokenHash, + &i.RegistrationVersion, + &i.CreatedAt, + &i.ExpiresAt, + &i.ConsumedAt, + &i.InvalidatedAt, + &i.CodeHash, + &i.CodeExpiresAt, + &i.CodeFailedAttempts, + &i.PendingPasswordHash, + &i.PendingScenario, + &i.PendingOnboardingStep, + ) + return i, err +} + const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one SELECT id, @@ -682,6 +790,8 @@ INSERT INTO email_tokens ( registration_version, created_at, expires_at, + code_hash, + code_expires_at, pending_password_hash, pending_scenario, pending_onboarding_step @@ -695,7 +805,9 @@ INSERT INTO email_tokens ( $7, $8, $9, - $10 + $10, + $11, + $12 ) ` @@ -707,6 +819,8 @@ type InsertEmailTokenParams struct { RegistrationVersion int64 CreatedAt pgtype.Timestamptz ExpiresAt pgtype.Timestamptz + CodeHash []byte + CodeExpiresAt pgtype.Timestamptz PendingPasswordHash pgtype.Text PendingScenario pgtype.Text PendingOnboardingStep pgtype.Text @@ -721,6 +835,8 @@ func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenPara arg.RegistrationVersion, arg.CreatedAt, arg.ExpiresAt, + arg.CodeHash, + arg.CodeExpiresAt, arg.PendingPasswordHash, arg.PendingScenario, arg.PendingOnboardingStep, @@ -834,10 +950,12 @@ const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execr UPDATE email_tokens SET invalidated_at = $1, - -- An invalidated token keeps no password hash: it can never be confirmed. + -- An invalidated token keeps no password hash or code: it can never be confirmed. pending_password_hash = NULL, pending_scenario = NULL, - pending_onboarding_step = NULL + pending_onboarding_step = NULL, + code_hash = NULL, + code_expires_at = NULL WHERE user_id = $2 AND purpose = $3 @@ -939,6 +1057,62 @@ func (q *Queries) PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeE return result.RowsAffected(), nil } +const recordFailedEmailCodeAttempt = `-- name: RecordFailedEmailCodeAttempt :one +UPDATE email_tokens +SET + code_failed_attempts = code_failed_attempts + 1, + invalidated_at = CASE + WHEN code_failed_attempts + 1 >= $1 THEN $2 + ELSE invalidated_at + END, + code_hash = CASE + WHEN code_failed_attempts + 1 >= $1 THEN NULL + ELSE code_hash + END, + code_expires_at = CASE + WHEN code_failed_attempts + 1 >= $1 THEN NULL + ELSE code_expires_at + END, + pending_password_hash = CASE + WHEN code_failed_attempts + 1 >= $1 THEN NULL + ELSE pending_password_hash + END, + pending_scenario = CASE + WHEN code_failed_attempts + 1 >= $1 THEN NULL + ELSE pending_scenario + END, + pending_onboarding_step = CASE + WHEN code_failed_attempts + 1 >= $1 THEN NULL + ELSE pending_onboarding_step + END +WHERE + id = $3 + AND consumed_at IS NULL + AND invalidated_at IS NULL + AND code_hash IS NOT NULL + AND code_failed_attempts < $1 +RETURNING code_failed_attempts >= $1 AS burned +` + +type RecordFailedEmailCodeAttemptParams struct { + MaxAttempts int16 + AttemptedAt pgtype.Timestamptz + ID pgtype.UUID +} + +// Counts one failed code or password attempt against an open code. The +// single UPDATE reads and writes the counter under the row lock, so concurrent +// failures serialize and none is lost. The attempt that reaches the limit +// invalidates the token and drops its code and pending credentials, so the +// code and the link both stop working. A token that is no longer open matches +// no row and is left unchanged. +func (q *Queries) RecordFailedEmailCodeAttempt(ctx context.Context, arg RecordFailedEmailCodeAttemptParams) (bool, error) { + row := q.db.QueryRow(ctx, recordFailedEmailCodeAttempt, arg.MaxAttempts, arg.AttemptedAt, arg.ID) + var burned bool + err := row.Scan(&burned) + return burned, err +} + const reserveIdempotencyRecord = `-- name: ReserveIdempotencyRecord :one INSERT INTO idempotency_records ( scope_hash, diff --git a/backend/internal/adapter/secondary/postgres/sqlc/models.go b/backend/internal/adapter/secondary/postgres/sqlc/models.go index 62e331a..3e6e060 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/models.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/models.go @@ -581,6 +581,12 @@ type EmailToken struct { PendingPasswordHash pgtype.Text PendingScenario pgtype.Text PendingOnboardingStep pgtype.Text + // HMAC-SHA-256 of the six-digit verification code under a server-side key; NULL when the token carries no code or the code has ended. The code itself is never stored. + CodeHash []byte + // End of the code validity: the earlier of the token expiry and the code lifetime. NULL together with code_hash. + CodeExpiresAt pgtype.Timestamptz + // Wrong code or password attempts counted against the open code; the token is invalidated when the count reaches the limit of five. + CodeFailedAttempts int16 } type Holding struct { diff --git a/backend/internal/adapter/secondary/postgres/sqlc/querier.go b/backend/internal/adapter/secondary/postgres/sqlc/querier.go index 7e6e16f..806d491 100644 --- a/backend/internal/adapter/secondary/postgres/sqlc/querier.go +++ b/backend/internal/adapter/secondary/postgres/sqlc/querier.go @@ -345,7 +345,7 @@ type Querier interface { GetEffectivePolicyVersion(ctx context.Context, arg GetEffectivePolicyVersionParams) (PolicyVersion, error) // Reads a token before password verification; Consume rechecks it in the // confirmation transaction and clears pending credentials when it succeeds. - GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (EmailToken, error) + GetEmailTokenByHash(ctx context.Context, arg GetEmailTokenByHashParams) (GetEmailTokenByHashRow, error) // Explains why ConsumeEmailToken matched no row. GetEmailTokenState(ctx context.Context, arg GetEmailTokenStateParams) (GetEmailTokenStateRow, error) GetHoldingIDByFounder(ctx context.Context, founderAccountID pgtype.UUID) (pgtype.UUID, error) @@ -390,6 +390,11 @@ type Querier interface { // employer sees it only while they are an active member. No row means the // content is no longer visible to this recipient. GetNotificationOrganizationNameForRecipient(ctx context.Context, arg GetNotificationOrganizationNameForRecipientParams) (string, error) + // Reads the newest open verification token that carries a code for the + // unverified account with this normalized address. The registration version + // must be current, so a code of an earlier registration never matches. The + // row is read before the code is compared; the consumption rechecks it. + GetOpenEmailCodeByAddress(ctx context.Context, arg GetOpenEmailCodeByAddressParams) (GetOpenEmailCodeByAddressRow, error) // Reads only the historical result. It intentionally does not join the live // organization or membership, whose profile and state may have since changed. GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error) @@ -1043,6 +1048,13 @@ type Querier interface { // the delivery is no longer pending or waiting, or another worker holds it. // now is the application clock. RecordDeliveryFailure(ctx context.Context, arg RecordDeliveryFailureParams) (string, error) + // Counts one failed code or password attempt against an open code. The + // single UPDATE reads and writes the counter under the row lock, so concurrent + // failures serialize and none is lost. The attempt that reaches the limit + // invalidates the token and drops its code and pending credentials, so the + // code and the link both stop working. A token that is no longer open matches + // no row and is left unchanged. + RecordFailedEmailCodeAttempt(ctx context.Context, arg RecordFailedEmailCodeAttemptParams) (bool, error) // The compare-and-swap of the first view: it applies only to a delivered // invitation at the version the caller read and before its deadline, and it // keeps the deadline. diff --git a/backend/internal/bootstrap/identity.go b/backend/internal/bootstrap/identity.go index b7ea153..5770310 100644 --- a/backend/internal/bootstrap/identity.go +++ b/backend/internal/bootstrap/identity.go @@ -136,6 +136,7 @@ func newIdentityHandler( }, identity.ConfirmationSettings{ TokenHourlyLimit: identity.DefaultTokenHourlyLimit, ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit), + EmailHourlyLimit: int64(settings.IdentityLoginEmailHourlyLimit), }) if err != nil { pool.Close() diff --git a/backend/internal/domain/email_code.go b/backend/internal/domain/email_code.go new file mode 100644 index 0000000..a498098 --- /dev/null +++ b/backend/internal/domain/email_code.go @@ -0,0 +1,106 @@ +package domain + +import ( + "crypto/rand" + "errors" + "fmt" + "io" + "log/slog" + "math/big" + "regexp" + "time" +) + +const ( + // VerificationCodeDigits is the length of the code in a verification + // message. The contract pattern is ^[0-9]{6}$. + VerificationCodeDigits = 6 + + // VerificationCodeMaxFailedAttempts is the number of failed attempts + // against one open code after which the code and its token are burned. + // The storage check constraint repeats this value. + VerificationCodeMaxFailedAttempts = 5 + + // VerificationCodeLifetime bounds how long a code works. A token lasts + // longer, so the code ends first; the code expiry is the earlier of the + // two, see NewEmailToken. + VerificationCodeLifetime = 30 * time.Minute + + // verificationCodeSpace is the number of distinct codes: 000000 to 999999. + verificationCodeSpace = 1_000_000 +) + +var ( + // ErrInvalidVerificationCode reports a code that is not six ASCII digits. + // Its message never contains the rejected value. + ErrInvalidVerificationCode = errors.New("invalid verification code") + + verificationCodeSpaceBig = big.NewInt(verificationCodeSpace) + verificationCodePattern = regexp.MustCompile(`^[0-9]{6}$`) +) + +// VerificationCode is the six-digit code of a verification message. Only the +// holder sees the value; String, GoString, Format, and LogValue redact it so +// that it does not reach logs by accident. Reveal returns it for the one place +// that must send it. The value sits behind a pointer, as in SecretToken. +type VerificationCode struct { + value *string +} + +// NewVerificationCode returns a code drawn uniformly from 000000 to 999999 +// with crypto/rand. +func NewVerificationCode() (VerificationCode, error) { + return newVerificationCode(rand.Reader) +} + +// newVerificationCode draws from random. crypto/rand.Int rejects the draws +// above the bound instead of reducing them modulo it, so every code is equally +// likely. +func newVerificationCode(random io.Reader) (VerificationCode, error) { + number, err := rand.Int(random, verificationCodeSpaceBig) + if err != nil { + return VerificationCode{}, fmt.Errorf("domain.NewVerificationCode - draw code: %w", err) + } + return VerificationCode{value: newRedactedValue(fmt.Sprintf("%0*d", VerificationCodeDigits, number.Int64()))}, nil +} + +// ParseVerificationCode accepts exactly six ASCII digits from a request. Spaces +// and separators are rejected rather than stripped, so the contract stays exact. +func ParseVerificationCode(raw string) (VerificationCode, error) { + if !verificationCodePattern.MatchString(raw) { + return VerificationCode{}, fmt.Errorf("domain.ParseVerificationCode - code must have %d digits: %w", VerificationCodeDigits, ErrInvalidVerificationCode) + } + return VerificationCode{value: newRedactedValue(raw)}, nil +} + +// Reveal returns the digits for delivery to the holder, or for the keyed +// digest. Never store or log the result. +func (code VerificationCode) Reveal() string { return redactedValue(code.value) } + +// IsZero reports a VerificationCode not built by NewVerificationCode or +// ParseVerificationCode. +func (code VerificationCode) IsZero() bool { return code.value == nil } + +func (code VerificationCode) String() string { return redactedSecret } + +func (code VerificationCode) GoString() string { return redactedSecret } + +// Format redacts every verb; without it %d would print the digits. +func (code VerificationCode) Format(state fmt.State, _ rune) { writeRedacted(state, redactedSecret) } + +func (code VerificationCode) LogValue() slog.Value { return slog.StringValue(redactedSecret) } + +// VerificationCodeHash is the keyed digest of a VerificationCode that storage +// keeps. It is an HMAC under a server secret: the code space has only a +// million values, so an unkeyed digest could be reversed by enumeration. +type VerificationCodeHash [SecretTokenHashSize]byte + +// IsZero reports the all-zero value, which marks a missing digest. +func (hash VerificationCodeHash) IsZero() bool { return hash == VerificationCodeHash{} } + +// EmailCode is the code state of an email token: its keyed digest and the end +// of its validity. +type EmailCode struct { + Hash VerificationCodeHash + ExpiresAt time.Time +} diff --git a/backend/internal/domain/email_code_test.go b/backend/internal/domain/email_code_test.go new file mode 100644 index 0000000..d4df02f --- /dev/null +++ b/backend/internal/domain/email_code_test.go @@ -0,0 +1,194 @@ +package domain + +import ( + "errors" + "fmt" + "io" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +// fixedReader yields the given bytes in order and then reports an error, so a +// draw that needs more entropy than the test provides fails loudly. +type fixedReader struct { + data []byte +} + +func (reader *fixedReader) Read(buffer []byte) (int, error) { + if len(reader.data) == 0 { + return 0, io.ErrUnexpectedEOF + } + count := copy(buffer, reader.data) + reader.data = reader.data[count:] + return count, nil +} + +func TestVerificationCodeRejectsDrawsAboveTheBoundInsteadOfReducingThem(t *testing.T) { + // crypto/rand.Int draws 20 random bits for the 1,000,000 codes and masks the + // top byte to 4 bits. 0x0FFFFF is 1048575, above the bound, so it is drawn + // again; the next draw 0x000007 is code 000007. A modulo reduction would + // have returned 048575 here and biased every code. + code, err := newVerificationCode(&fixedReader{data: []byte{0x0F, 0xFF, 0xFF, 0x00, 0x00, 0x07}}) + if err != nil { + t.Fatalf("newVerificationCode() error = %v", err) + } + if code.Reveal() != "000007" { + t.Fatalf("code = %q, want 000007", code.Reveal()) + } +} + +func TestVerificationCodeCoversTheWholeRange(t *testing.T) { + low, err := newVerificationCode(&fixedReader{data: []byte{0x00, 0x00, 0x00}}) + if err != nil { + t.Fatalf("newVerificationCode(0) error = %v", err) + } + high, err := newVerificationCode(&fixedReader{data: []byte{0x0F, 0x42, 0x3F}}) + if err != nil { + t.Fatalf("newVerificationCode(999999) error = %v", err) + } + if low.Reveal() != "000000" || high.Reveal() != "999999" { + t.Fatalf("bounds = %q and %q, want 000000 and 999999", low.Reveal(), high.Reveal()) + } +} + +func TestVerificationCodeDrawFailureIsReported(t *testing.T) { + if _, err := newVerificationCode(&fixedReader{}); err == nil { + t.Fatal("newVerificationCode() accepted a failing entropy source") + } +} + +func TestNewVerificationCodeIsRoughlyUniform(t *testing.T) { + const draws = 20_000 + var buckets [10]int + for range draws { + code, err := NewVerificationCode() + if err != nil { + t.Fatalf("NewVerificationCode() error = %v", err) + } + if len(code.Reveal()) != VerificationCodeDigits { + t.Fatalf("code %q does not have %d digits", code.Reveal(), VerificationCodeDigits) + } + buckets[code.Reveal()[0]-'0']++ + } + // The expected count per leading digit is 2000 with a standard deviation + // near 42. A window of about seven standard deviations keeps the test + // deterministic in practice and still rejects a visibly skewed generator. + for digit, count := range buckets { + if count < 1700 || count > 2300 { + t.Fatalf("leading digit %d appeared %d times in %d draws", digit, count, draws) + } + } +} + +func TestParseVerificationCodeAcceptsOnlySixASCIIDigits(t *testing.T) { + for _, valid := range []string{"000000", "482915", "999999"} { + code, err := ParseVerificationCode(valid) + if err != nil || code.Reveal() != valid { + t.Fatalf("ParseVerificationCode(%q) = %q, %v", valid, code.Reveal(), err) + } + } + for _, invalid := range []string{"", "48291", "4829156", "48291a", " 482915", "482915\n", "482 915", "482915", "-82915"} { + if _, err := ParseVerificationCode(invalid); !errors.Is(err, ErrInvalidVerificationCode) { + t.Fatalf("ParseVerificationCode(%q) error = %v, want ErrInvalidVerificationCode", invalid, err) + } + } +} + +func TestVerificationCodeNeverPrintsItsDigits(t *testing.T) { + code, err := ParseVerificationCode("482915") + if err != nil { + t.Fatal(err) + } + for _, rendered := range []string{ + fmt.Sprint(code), + fmt.Sprintf("%v %+v %#v %s %d", code, code, code, code, code), + code.LogValue().String(), + fmt.Sprint(struct{ Code VerificationCode }{code}), + } { + if strings.Contains(rendered, "482915") { + t.Fatalf("rendering %q contains the code", rendered) + } + } + if code.Reveal() != "482915" || code.IsZero() || !(VerificationCode{}).IsZero() { + t.Fatal("Reveal or IsZero does not report the stored code") + } +} + +func TestVerificationCodeHashIsZeroOnlyWhenUnset(t *testing.T) { + if !(VerificationCodeHash{}).IsZero() { + t.Fatal("the zero digest is not reported as zero") + } + if (VerificationCodeHash{1}).IsZero() { + t.Fatal("a set digest is reported as zero") + } +} + +func verificationTokenInput(t *testing.T, purpose EmailTokenPurpose) NewEmailTokenInput { + t.Helper() + raw, err := NewSecretToken() + if err != nil { + t.Fatal(err) + } + return NewEmailTokenInput{ + UserID: uuid.New(), + Purpose: purpose, + TokenHash: raw.Hash(), + RegistrationVersion: 1, + IssuedAt: time.Date(2026, time.October, 9, 12, 0, 0, 0, time.UTC), + Lifetime: 24 * time.Hour, + CodeHash: VerificationCodeHash{1}, + CodeLifetime: VerificationCodeLifetime, + } +} + +func TestNewEmailTokenEndsTheCodeAtTheEarlierOfTokenAndCodeLifetime(t *testing.T) { + input := verificationTokenInput(t, EmailTokenPurposeEmailVerification) + token, err := NewEmailToken(input) + if err != nil { + t.Fatalf("NewEmailToken() error = %v", err) + } + if token.Code == nil || token.Code.Hash != input.CodeHash { + t.Fatalf("token code = %+v, want the digest", token.Code) + } + if want := input.IssuedAt.Add(VerificationCodeLifetime); !token.Code.ExpiresAt.Equal(want) { + t.Fatalf("code expiry = %s, want %s", token.Code.ExpiresAt, want) + } + + input.Lifetime = 10 * time.Minute + token, err = NewEmailToken(input) + if err != nil { + t.Fatalf("NewEmailToken(short token) error = %v", err) + } + if !token.Code.ExpiresAt.Equal(token.ExpiresAt) { + t.Fatalf("code expiry = %s, want the token expiry %s", token.Code.ExpiresAt, token.ExpiresAt) + } +} + +func TestNewEmailTokenRequiresCodeFieldsTogetherAndOnlyForVerification(t *testing.T) { + cases := map[string]func(*NewEmailTokenInput){ + "hash without lifetime": func(input *NewEmailTokenInput) { input.CodeLifetime = 0 }, + "lifetime without hash": func(input *NewEmailTokenInput) { input.CodeHash = VerificationCodeHash{} }, + "negative lifetime": func(input *NewEmailTokenInput) { input.CodeLifetime = -time.Minute }, + } + for name, mutate := range cases { + input := verificationTokenInput(t, EmailTokenPurposeEmailVerification) + mutate(&input) + if _, err := NewEmailToken(input); !errors.Is(err, ErrInvalidEmailToken) { + t.Fatalf("NewEmailToken(%s) error = %v, want ErrInvalidEmailToken", name, err) + } + } + reset := verificationTokenInput(t, EmailTokenPurposePasswordReset) + if _, err := NewEmailToken(reset); !errors.Is(err, ErrInvalidEmailToken) { + t.Fatalf("NewEmailToken(reset with code) error = %v, want ErrInvalidEmailToken", err) + } + plain := verificationTokenInput(t, EmailTokenPurposeEmailVerification) + plain.CodeHash = VerificationCodeHash{} + plain.CodeLifetime = 0 + token, err := NewEmailToken(plain) + if err != nil || token.Code != nil { + t.Fatalf("NewEmailToken(no code) = %+v, %v; want no code state", token.Code, err) + } +} diff --git a/backend/internal/domain/email_token.go b/backend/internal/domain/email_token.go index d93918e..f949dc4 100644 --- a/backend/internal/domain/email_token.go +++ b/backend/internal/domain/email_token.go @@ -68,6 +68,9 @@ type EmailToken struct { ExpiresAt time.Time ConsumedAt *time.Time InvalidatedAt *time.Time + // Code is set on a verification token that carries a six-digit code and + // nil otherwise. Its digest is never the code itself. + Code *EmailCode // Pending is set on the verification token of a registration and nil on // a token that carries no credentials. Pending *PendingRegistration @@ -82,6 +85,11 @@ type NewEmailTokenInput struct { RegistrationVersion int64 IssuedAt time.Time Lifetime time.Duration + // CodeHash and CodeLifetime describe the optional verification code. Both + // are set together or both are zero. The code expires at the earlier of + // the token expiry and IssuedAt plus CodeLifetime. + CodeHash VerificationCodeHash + CodeLifetime time.Duration // Pending is optional; see PendingRegistration. Pending *PendingRegistration } @@ -99,24 +107,45 @@ func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) { return EmailToken{}, invalidEmailToken("issue time must be set") case input.Lifetime <= 0: return EmailToken{}, invalidEmailToken("lifetime must be positive") + case input.CodeHash.IsZero() != (input.CodeLifetime == 0): + return EmailToken{}, invalidEmailToken("code hash and code lifetime must be set together") + case input.CodeLifetime < 0: + return EmailToken{}, invalidEmailToken("code lifetime must not be negative") } if _, err := ParseEmailTokenPurpose(string(input.Purpose)); err != nil { return EmailToken{}, fmt.Errorf("domain.NewEmailToken - validate purpose: %w", err) } + if !input.CodeHash.IsZero() && input.Purpose != EmailTokenPurposeEmailVerification { + return EmailToken{}, invalidEmailToken("only an email verification token carries a code") + } id, err := uuid.NewV7() if err != nil { return EmailToken{}, fmt.Errorf("domain.NewEmailToken - generate token ID: %w", err) } - return EmailToken{ + expiresAt := input.IssuedAt.Add(input.Lifetime) + token := EmailToken{ ID: id, UserID: input.UserID, Purpose: input.Purpose, TokenHash: input.TokenHash, RegistrationVersion: input.RegistrationVersion, CreatedAt: input.IssuedAt, - ExpiresAt: input.IssuedAt.Add(input.Lifetime), + ExpiresAt: expiresAt, Pending: input.Pending, - }, nil + } + if !input.CodeHash.IsZero() { + token.Code = &EmailCode{Hash: input.CodeHash, ExpiresAt: earlierInstant(expiresAt, input.IssuedAt.Add(input.CodeLifetime))} + } + return token, nil +} + +// earlierInstant returns the earlier of two instants. The time type is not +// ordered by the built-in min. +func earlierInstant(left, right time.Time) time.Time { + if right.Before(left) { + return right + } + return left } func invalidEmailToken(reason string) error { diff --git a/backend/internal/port/outbound/identity.go b/backend/internal/port/outbound/identity.go index f916e5a..cb4d104 100644 --- a/backend/internal/port/outbound/identity.go +++ b/backend/internal/port/outbound/identity.go @@ -176,6 +176,20 @@ type EmailTokenRepository interface { // ErrUserVersionConflict; the rollback also restores the token. The // confirmation usecase maps that outcome to verification_token_invalid. Consume(ctx context.Context, hash domain.SecretTokenHash, purpose domain.EmailTokenPurpose, at time.Time) (domain.EmailToken, error) + + // FindOpenCodeByAddress returns the newest open verification token that + // carries a code for the unverified account with the normalized address, + // and whose registration is current. It returns ErrEmailTokenNotFound when + // there is none. The caller compares the code and the password, then + // consumes the token with Consume in its transaction. + FindOpenCodeByAddress(ctx context.Context, email domain.EmailAddress) (domain.EmailToken, error) + + // RecordFailedCodeAttempt counts one wrong code or password against the + // open token with the ID at the given time. The attempt that reaches + // domain.VerificationCodeMaxFailedAttempts invalidates the token, drops + // its code and pending credentials, and reports burned true. A token that + // is no longer open is left unchanged and reports false without an error. + RecordFailedCodeAttempt(ctx context.Context, id uuid.UUID, at time.Time) (burned bool, err error) } // SessionRepository stores server-side sessions by the hash of their token. diff --git a/backend/internal/usecase/identity/code_confirmation.go b/backend/internal/usecase/identity/code_confirmation.go new file mode 100644 index 0000000..7dbaf6e --- /dev/null +++ b/backend/internal/usecase/identity/code_confirmation.go @@ -0,0 +1,191 @@ +package identity + +import ( + "context" + "errors" + "fmt" + "time" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + // codePointer is the JSON Pointer of the code field in a request body. + codePointer = "/code" + + // addressCodeWindow is the window of the per-address limit. It is the + // window of the login limit, so both draw on one counter. + addressCodeWindow = time.Hour +) + +// ConfirmCodeCommand is the content of a confirmation by the six-digit code of +// a verification message, unvalidated. +type ConfirmCodeCommand struct { + Email string + Code string + Password string + // ClientKey is the opaque limiter key of the client network address. + ClientKey string +} + +// ConfirmByCode verifies the address with the code of its verification +// message. It checks the same things as the link confirmation: the open token +// of the current registration, the password chosen for that registration, and +// the consumption of the token in one transaction. The code also has its own +// expiry and attempt limit. +// +// Every refusal is ErrVerificationTokenInvalid, whatever its cause: an unknown +// address, no open code, a wrong code or password, an expired code, or a burned +// token. The answer then does not reveal which addresses have a pending +// registration. Each failed attempt against an open code is counted in the +// token row; the attempt that reaches the limit burns the token, so both the +// code and the link stop working. +// +// The password is checked on every branch, with the same hashing work, so the +// time of a refusal does not depend on whether the address has an account. +func (confirmation *EmailConfirmation) ConfirmByCode(ctx context.Context, command ConfirmCodeCommand) (ConfirmationResult, error) { + const location = "EmailConfirmation.ConfirmByCode" + email, err := domain.NewEmailAddress(command.Email) + if err != nil { + return ConfirmationResult{}, fmt.Errorf("%s - validate email: %w", location, invalidField(emailPointer, err)) + } + code, err := domain.ParseVerificationCode(command.Code) + if err != nil { + return ConfirmationResult{}, fmt.Errorf("%s - validate code: %w", location, invalidField(codePointer, err)) + } + if err := confirmation.takeCodeAttempt(ctx, email, command.ClientKey); err != nil { + return ConfirmationResult{}, fmt.Errorf("%s - limit code confirmation: %w", location, err) + } + open, found, err := confirmation.findOpenCode(ctx, email) + if err != nil { + return ConfirmationResult{}, fmt.Errorf("%s - read open code: %w", location, err) + } + passwordMatches, err := confirmation.codePasswordMatches(ctx, command.Password, open, found) + if err != nil { + return ConfirmationResult{}, fmt.Errorf("%s - verify registration password: %w", location, err) + } + now := confirmation.deps.Clock() + if !found || !passwordMatches || !codeMatches(confirmation.deps.Keyring, code, open, now) { + if found { + if _, err := confirmation.deps.Tokens.RecordFailedCodeAttempt(ctx, open.ID, now); err != nil { + return ConfirmationResult{}, fmt.Errorf("%s - count failed attempt: %w", location, err) + } + } + return ConfirmationResult{}, fmt.Errorf("%s - code does not confirm the registration: %w", location, ErrVerificationTokenInvalid) + } + + var result ConfirmationResult + err = confirmation.deps.Transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { + return confirmation.confirmInTransaction(ctx, unit, open.TokenHash, open, &result) + }) + if err != nil { + return ConfirmationResult{}, fmt.Errorf("%s - confirm registration: %w", location, codeOutcomeError(err)) + } + return result, nil +} + +// takeCodeAttempt counts the request against the client limit, when the request +// has a client key, and against the normalized address. The address counter +// sees every request, whether or not an account exists. +func (confirmation *EmailConfirmation) takeCodeAttempt(ctx context.Context, email domain.EmailAddress, clientKey string) error { + const location = "EmailConfirmation.takeCodeAttempt" + if clientKey != "" { + err := takeRateLimit(ctx, confirmation.deps.Limiter, confirmation.deps.Metrics, ScopeClient, + confirmation.deps.Keyring.ClientBucket(clientKey), + outbound.RateLimitRule{Window: clientWindow, Limit: confirmation.settings.ClientHourlyLimit}) + if err != nil { + return fmt.Errorf("%s - take client limit: %w", location, err) + } + } + err := takeRateLimit(ctx, confirmation.deps.Limiter, confirmation.deps.Metrics, ScopeAddress, + confirmation.deps.Keyring.EmailBucket(email.Normalized()), + outbound.RateLimitRule{Window: addressCodeWindow, Limit: confirmation.settings.EmailHourlyLimit}) + if err != nil { + return fmt.Errorf("%s - take address limit: %w", location, err) + } + return nil +} + +// takeRateLimit counts one request against one rule and reports a refusal as +// *RateLimitedError, after it notifies the metrics of the scope. +func takeRateLimit( + ctx context.Context, + limiter outbound.RateLimiter, + metrics RateLimitMetrics, + scope, bucket string, + rule outbound.RateLimitRule, +) error { + decision, err := limiter.Take(ctx, bucket, rule) + if err != nil { + return fmt.Errorf("take rate limit: %w", err) + } + if !decision.Allowed { + if metrics != nil { + metrics.ObserveIdentityRateLimited(scope) + } + return &RateLimitedError{RetryAfter: decision.RetryAfter} + } + return nil +} + +// findOpenCode returns the open code token of the address and whether one +// exists. The absence of a token is not an error: it is one of the refusals. +func (confirmation *EmailConfirmation) findOpenCode(ctx context.Context, email domain.EmailAddress) (domain.EmailToken, bool, error) { + token, err := confirmation.deps.Tokens.FindOpenCodeByAddress(ctx, email) + switch { + case errors.Is(err, outbound.ErrEmailTokenNotFound): + return domain.EmailToken{}, false, nil + case err != nil: + return domain.EmailToken{}, false, fmt.Errorf("EmailConfirmation.findOpenCode - read token: %w", err) + } + return token, true, nil +} + +// codePasswordMatches reports whether password is the one chosen for the +// registration of the open code. With no open code, or a password outside the +// login bounds, it spends the same hashing work on a dummy hash and reports no +// match; the work does not depend on whether the address has an account. +func (confirmation *EmailConfirmation) codePasswordMatches( + ctx context.Context, + password string, + open domain.EmailToken, + found bool, +) (bool, error) { + credentials := confirmation.deps.Credentials + if _, err := domain.ParseLoginPassword(password); err != nil || !found || open.Pending == nil { + err := credentials.VerifyDummyLoginPassword(ctx, password) + if err != nil && !errors.Is(err, outbound.ErrPasswordMismatch) { + return false, fmt.Errorf("EmailConfirmation.codePasswordMatches - verify dummy hash: %w", err) + } + return false, nil + } + err := credentials.VerifyLoginPassword(ctx, password, open.Pending.PasswordHash) + switch { + case err == nil: + return true, nil + case errors.Is(err, outbound.ErrPasswordMismatch), errors.Is(err, domain.ErrInvalidPassword): + return false, nil + default: + return false, fmt.Errorf("EmailConfirmation.codePasswordMatches - verify password: %w", err) + } +} + +// codeMatches reports whether code is the open code of the token, and whether +// both the code and the token are still within their validity. It is false when +// there is no open code. +func codeMatches(keyring *Keyring, code domain.VerificationCode, open domain.EmailToken, now time.Time) bool { + if open.Code == nil || !open.Code.ExpiresAt.After(now) || !open.ExpiresAt.After(now) { + return false + } + return keyring.VerifyVerificationCode(code, open.Code.Hash) +} + +// codeOutcomeError maps the outcome of the code transaction to the single +// refusal of the code operation, so an expired token is not reported apart. +func codeOutcomeError(err error) error { + if errors.Is(err, ErrVerificationTokenExpired) { + return ErrVerificationTokenInvalid + } + return confirmationOutcomeError(err) +} diff --git a/backend/internal/usecase/identity/code_confirmation_test.go b/backend/internal/usecase/identity/code_confirmation_test.go new file mode 100644 index 0000000..2200a96 --- /dev/null +++ b/backend/internal/usecase/identity/code_confirmation_test.go @@ -0,0 +1,437 @@ +package identity + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/google/uuid" + + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/outbound" +) + +const ( + codeTestSecret = "code confirmation test key with enough entropy" + codeTestEmailLimit = 10 + codeTestClientLimit = 30 +) + +// codeTestStore models the verification token row that the confirmation +// reads and writes: the open code, its failed attempts, and the closing +// outcomes of consumption and burning. +type codeTestStore struct { + outbound.EmailTokenRepository + + token domain.EmailToken + missing bool + attempts int + recorded int + closed bool + consumed bool + invalidated bool +} + +func (store *codeTestStore) FindByHash(_ context.Context, hash domain.SecretTokenHash, _ domain.EmailTokenPurpose) (domain.EmailToken, error) { + if store.missing || hash != store.token.TokenHash { + return domain.EmailToken{}, outbound.ErrEmailTokenNotFound + } + token := store.token + if store.consumed { + consumedAt := token.CreatedAt + token.ConsumedAt = &consumedAt + } + if store.invalidated { + invalidatedAt := token.CreatedAt + token.InvalidatedAt = &invalidatedAt + } + return token, nil +} + +func (store *codeTestStore) FindOpenCodeByAddress(context.Context, domain.EmailAddress) (domain.EmailToken, error) { + if store.missing || store.closed || store.token.Code == nil { + return domain.EmailToken{}, outbound.ErrEmailTokenNotFound + } + return store.token, nil +} + +func (store *codeTestStore) RecordFailedCodeAttempt(_ context.Context, id uuid.UUID, _ time.Time) (bool, error) { + if store.missing || store.closed || id != store.token.ID { + return false, nil + } + store.recorded++ + store.attempts++ + if store.attempts >= domain.VerificationCodeMaxFailedAttempts { + store.closed = true + store.invalidated = true + return true, nil + } + return false, nil +} + +// Consume closes the token the way the link path does, so the code and the +// link share one consumption. +func (store *codeTestStore) Consume(_ context.Context, hash domain.SecretTokenHash, _ domain.EmailTokenPurpose, at time.Time) (domain.EmailToken, error) { + switch { + case store.missing || hash != store.token.TokenHash: + return domain.EmailToken{}, outbound.ErrEmailTokenNotFound + case store.consumed: + return domain.EmailToken{}, outbound.ErrEmailTokenConsumed + case store.invalidated: + return domain.EmailToken{}, outbound.ErrEmailTokenInvalidated + case !store.token.ExpiresAt.After(at): + return domain.EmailToken{}, outbound.ErrEmailTokenExpired + } + store.closed = true + store.consumed = true + token := store.token + token.ConsumedAt = &at + return token, nil +} + +// codeTestUnit gives the confirmation the four repositories a successful +// transaction uses. Any other accessor panics, which keeps the test honest. +type codeTestUnit struct { + outbound.UnitOfWork + + store *codeTestStore +} + +func (unit codeTestUnit) EmailTokens() outbound.EmailTokenRepository { return unit.store } + +func (unit codeTestUnit) Users() outbound.UserRepository { return codeTestUsers{store: unit.store} } + +func (unit codeTestUnit) ConsentLedger() outbound.ConsentLedger { return codeTestLedger{} } + +func (unit codeTestUnit) Outbox() outbound.OutboxWriter { return codeTestOutbox{} } + +type codeTestUsers struct { + outbound.UserRepository + + store *codeTestStore +} + +func (users codeTestUsers) ConfirmEmail(_ context.Context, id uuid.UUID, _ int64, _ domain.PendingRegistration, at time.Time) (domain.User, error) { + return domain.User{ + ID: id, + Scenario: domain.ScenarioCandidate, + OnboardingStep: domain.OnboardingStepCandidateConsents, + EmailVerifiedAt: &at, + Version: 2, + }, nil +} + +type codeTestLedger struct { + outbound.ConsentLedger +} + +func (codeTestLedger) LockRegistration(context.Context, uuid.UUID, int64) (domain.ConsentRecord, error) { + return domain.ConsentRecord{}, nil +} + +type codeTestOutbox struct{} + +func (codeTestOutbox) Append(context.Context, ...domain.DomainEvent) error { return nil } + +type codeTestTransactor struct { + unit outbound.UnitOfWork + calls int +} + +func (transactor *codeTestTransactor) WithinTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error { + transactor.calls++ + return work(ctx, transactor.unit) +} + +// codeTestLimiter records every key and refuses when deny is set. +type codeTestLimiter struct { + keys []string + rules [][]outbound.RateLimitRule + deny bool +} + +func (limiter *codeTestLimiter) Take(_ context.Context, key string, rules ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) { + limiter.keys = append(limiter.keys, key) + limiter.rules = append(limiter.rules, rules) + if limiter.deny { + return outbound.RateLimitDecision{Allowed: false, RetryAfter: time.Minute}, nil + } + return outbound.RateLimitDecision{Allowed: true}, nil +} + +type codeFixture struct { + now time.Time + keyring *Keyring + raw domain.SecretToken + code domain.VerificationCode + store *codeTestStore + hasher *countingHasher + limiter *codeTestLimiter + transactor *codeTestTransactor + confirmation *EmailConfirmation +} + +func newCodeFixture(t *testing.T) *codeFixture { + t.Helper() + now := time.Date(2026, time.October, 9, 12, 0, 0, 0, time.UTC) + keyring, err := NewKeyring([]byte(codeTestSecret)) + if err != nil { + t.Fatal(err) + } + raw, err := domain.NewSecretToken() + if err != nil { + t.Fatal(err) + } + code, err := domain.ParseVerificationCode("482915") + if err != nil { + t.Fatal(err) + } + passwordHash, err := domain.NewPasswordHash(confirmationTestPasswordHash) + if err != nil { + t.Fatal(err) + } + pending, err := domain.NewPendingRegistration(passwordHash, domain.ScenarioCandidate) + if err != nil { + t.Fatal(err) + } + token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ + UserID: uuid.New(), + Purpose: domain.EmailTokenPurposeEmailVerification, + TokenHash: raw.Hash(), + RegistrationVersion: 1, + IssuedAt: now, + Lifetime: 24 * time.Hour, + CodeHash: keyring.VerificationCodeDigest(code), + CodeLifetime: domain.VerificationCodeLifetime, + Pending: &pending, + }) + if err != nil { + t.Fatal(err) + } + store := &codeTestStore{token: token} + hasher := &countingHasher{} + limiter := &codeTestLimiter{} + transactor := &codeTestTransactor{unit: codeTestUnit{store: store}} + confirmation, err := NewEmailConfirmation(ConfirmationDependencies{ + Transactor: transactor, + Tokens: store, + Credentials: NewCredentials(hasher), + Limiter: limiter, + Keyring: keyring, + Clock: func() time.Time { return now }, + }, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: codeTestClientLimit, EmailHourlyLimit: codeTestEmailLimit}) + if err != nil { + t.Fatal(err) + } + return &codeFixture{ + now: now, keyring: keyring, raw: raw, code: code, store: store, hasher: hasher, + limiter: limiter, transactor: transactor, confirmation: confirmation, + } +} + +func (fixture *codeFixture) command(code, password string) ConfirmCodeCommand { + return ConfirmCodeCommand{Email: "Candidate@Example.com", Code: code, Password: password, ClientKey: "client-key"} +} + +func wrongCodeFor(code domain.VerificationCode) string { + if code.Reveal() == "000000" { + return "000001" + } + return "000000" +} + +func requireInvalidCode(t *testing.T, err error) { + t.Helper() + if !errors.Is(err, ErrVerificationTokenInvalid) { + t.Fatalf("ConfirmByCode() error = %v, want ErrVerificationTokenInvalid", err) + } +} + +func TestConfirmByCodeRejectsMalformedFieldsBeforeAnyLookup(t *testing.T) { + for _, test := range []struct { + name string + email string + code string + pointer string + }{ + {name: "email", email: "not-an-address", code: "482915", pointer: emailPointer}, + {name: "short code", email: "candidate@example.com", code: "48291", pointer: codePointer}, + {name: "long code", email: "candidate@example.com", code: "4829156", pointer: codePointer}, + {name: "letters", email: "candidate@example.com", code: "48291A", pointer: codePointer}, + {name: "spaces", email: "candidate@example.com", code: " 482915", pointer: codePointer}, + {name: "empty", email: "candidate@example.com", code: "", pointer: codePointer}, + } { + t.Run(test.name, func(t *testing.T) { + fixture := newCodeFixture(t) + _, err := fixture.confirmation.ConfirmByCode(context.Background(), ConfirmCodeCommand{ + Email: test.email, Code: test.code, Password: "correct horse battery staple", ClientKey: "client-key", + }) + var field *InvalidFieldError + if !errors.As(err, &field) || field.Pointer != test.pointer { + t.Fatalf("ConfirmByCode() error = %v, want invalid field %s", err, test.pointer) + } + if len(fixture.limiter.keys) != 0 || fixture.store.recorded != 0 || fixture.hasher.verifyCalls+fixture.hasher.dummyCalls != 0 { + t.Fatal("a malformed request reached the limiter, the store, or the hasher") + } + }) + } +} + +func TestConfirmByCodeChecksTheClientAndAddressLimitsBeforeTheLookup(t *testing.T) { + fixture := newCodeFixture(t) + fixture.limiter.deny = true + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command("482915", "correct horse battery staple")) + var limited *RateLimitedError + if !errors.As(err, &limited) || limited.RetryAfter != time.Minute { + t.Fatalf("ConfirmByCode() error = %v, want rate limit", err) + } + if len(fixture.limiter.keys) != 1 || fixture.limiter.keys[0] != fixture.keyring.ClientBucket("client-key") { + t.Fatalf("limiter keys = %v, want the client bucket only", fixture.limiter.keys) + } + fixture.limiter.keys = nil + fixture.limiter.rules = nil + if _, err := fixture.confirmation.ConfirmByCode(context.Background(), ConfirmCodeCommand{ + Email: "Candidate@Example.com", Code: "482915", Password: "correct horse battery staple", + }); !errors.As(err, &limited) { + t.Fatalf("ConfirmByCode() without client key error = %v, want the address rate limit", err) + } + if got, want := fixture.limiter.keys[0], fixture.keyring.EmailBucket("candidate@example.com"); got != want { + t.Fatalf("address bucket = %q, want the normalized address bucket", got) + } + rule := fixture.limiter.rules[0] + if len(rule) != 1 || rule[0].Window != time.Hour || rule[0].Limit != codeTestEmailLimit { + t.Fatalf("address rule = %+v, want one hour and the login limit", rule) + } + if fixture.store.recorded != 0 || fixture.hasher.dummyCalls+fixture.hasher.verifyCalls != 0 { + t.Fatal("a refused request reached the store or the hasher") + } +} + +func TestConfirmByCodeRefusesAnUnknownAddressWithTheSameWork(t *testing.T) { + fixture := newCodeFixture(t) + fixture.store.missing = true + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple")) + requireInvalidCode(t, err) + if fixture.hasher.dummyCalls != 1 || fixture.hasher.verifyCalls != 0 { + t.Fatalf("hasher calls = dummy %d, verify %d; want one dummy comparison", fixture.hasher.dummyCalls, fixture.hasher.verifyCalls) + } + if fixture.store.recorded != 0 || fixture.transactor.calls != 0 { + t.Fatal("an unknown address counted an attempt or opened a transaction") + } +} + +func TestConfirmByCodeWrongCodeBurnsTheTokenOnTheFifthAttempt(t *testing.T) { + fixture := newCodeFixture(t) + wrong := wrongCodeFor(fixture.code) + for attempt := 1; attempt <= domain.VerificationCodeMaxFailedAttempts; attempt++ { + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(wrong, "correct horse battery staple")) + requireInvalidCode(t, err) + if closed := fixture.store.closed; closed != (attempt == domain.VerificationCodeMaxFailedAttempts) { + t.Fatalf("after attempt %d the token closed = %v", attempt, closed) + } + } + if fixture.store.recorded != domain.VerificationCodeMaxFailedAttempts { + t.Fatalf("counted attempts = %d, want %d", fixture.store.recorded, domain.VerificationCodeMaxFailedAttempts) + } + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple")) + requireInvalidCode(t, err) + if fixture.transactor.calls != 0 { + t.Fatal("the right code confirmed after the token was burned") + } +} + +func TestConfirmByCodeWrongPasswordWithTheRightCodeIsRefusedAndCounted(t *testing.T) { + fixture := newCodeFixture(t) + fixture.hasher.verifyErr = outbound.ErrPasswordMismatch + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "a wrong password for this registration")) + requireInvalidCode(t, err) + if fixture.hasher.verifyCalls != 1 || fixture.store.recorded != 1 || fixture.transactor.calls != 0 { + t.Fatalf("verify %d, counted %d, transactions %d", fixture.hasher.verifyCalls, fixture.store.recorded, fixture.transactor.calls) + } + if fixture.store.closed { + t.Fatal("one wrong password closed the token") + } +} + +// An attacker who registered someone else's address knows the password of the +// registration but not the code, which goes only to the address owner. +func TestConfirmByCodeAttackerRegistrationNeedsTheOwnersCode(t *testing.T) { + fixture := newCodeFixture(t) + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(wrongCodeFor(fixture.code), "correct horse battery staple")) + requireInvalidCode(t, err) + if fixture.store.recorded != 1 || fixture.store.closed { + t.Fatalf("counted %d, closed %v; want one counted attempt and an open token", fixture.store.recorded, fixture.store.closed) + } +} + +func TestConfirmByCodeRefusesAnExpiredCode(t *testing.T) { + fixture := newCodeFixture(t) + fixture.confirmation.deps.Clock = func() time.Time { return fixture.now.Add(domain.VerificationCodeLifetime + time.Second) } + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple")) + requireInvalidCode(t, err) + if errors.Is(err, ErrVerificationTokenExpired) { + t.Fatal("an expired code reported its own refusal") + } + if fixture.store.recorded != 1 || fixture.transactor.calls != 0 { + t.Fatalf("counted %d, transactions %d", fixture.store.recorded, fixture.transactor.calls) + } +} + +func TestConfirmByCodeMalformedPasswordDoesNotSkipTheHashingWork(t *testing.T) { + fixture := newCodeFixture(t) + for _, password := range []string{"", strings.Repeat("p", 129)} { + fixture.hasher.dummyCalls = 0 + fixture.hasher.verifyCalls = 0 + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), password)) + requireInvalidCode(t, err) + if fixture.hasher.dummyCalls != 1 || fixture.hasher.verifyCalls != 0 { + t.Fatalf("password length %d: hasher calls dummy %d, verify %d", len(password), fixture.hasher.dummyCalls, fixture.hasher.verifyCalls) + } + } +} + +func TestConfirmByCodeConsumesTheTokenAndBlocksLaterUse(t *testing.T) { + fixture := newCodeFixture(t) + result, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple")) + if err != nil { + t.Fatalf("ConfirmByCode() error = %v", err) + } + if result.Scenario != domain.ScenarioCandidate || result.OnboardingStep != domain.OnboardingStepCandidateConsents { + t.Fatalf("result = %+v", result) + } + if !fixture.store.consumed || fixture.transactor.calls != 1 { + t.Fatalf("consumed %v, transactions %d", fixture.store.consumed, fixture.transactor.calls) + } + _, err = fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple")) + requireInvalidCode(t, err) + _, err = fixture.confirmation.Confirm(context.Background(), ConfirmCommand{Token: fixture.raw.Reveal(), Password: "correct horse battery staple"}) + requireInvalidCode(t, err) +} + +// The link consumes the same token, so a code confirmation after it is refused. +func TestLinkConfirmationBurnsTheCode(t *testing.T) { + fixture := newCodeFixture(t) + if _, err := fixture.confirmation.Confirm(context.Background(), ConfirmCommand{ + Token: fixture.raw.Reveal(), Password: "correct horse battery staple", ClientKey: "client-key", + }); err != nil { + t.Fatalf("Confirm() error = %v", err) + } + _, err := fixture.confirmation.ConfirmByCode(context.Background(), fixture.command(fixture.code.Reveal(), "correct horse battery staple")) + requireInvalidCode(t, err) + if fixture.transactor.calls != 1 { + t.Fatalf("transactions = %d, want only the link confirmation", fixture.transactor.calls) + } +} + +func TestVerificationCodeSettingsMustBePositive(t *testing.T) { + fixture := newCodeFixture(t) + _, err := NewEmailConfirmation(ConfirmationDependencies{ + Transactor: fixture.transactor, Tokens: fixture.store, Credentials: NewCredentials(fixture.hasher), + Limiter: fixture.limiter, Keyring: fixture.keyring, Clock: time.Now, + }, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 30}) + if err == nil { + t.Fatal("NewEmailConfirmation() accepted a missing address limit") + } +} diff --git a/backend/internal/usecase/identity/confirmation.go b/backend/internal/usecase/identity/confirmation.go index eb836a5..aa40033 100644 --- a/backend/internal/usecase/identity/confirmation.go +++ b/backend/internal/usecase/identity/confirmation.go @@ -31,11 +31,14 @@ type ConfirmationDependencies struct { Metrics RateLimitMetrics } -// ConfirmationSettings contains the attempt limits for one token and one -// client. The client limit matches registration and resend. +// ConfirmationSettings contains the attempt limits for one token, one client, +// and one normalized address. The client limit matches registration and +// resend. The address limit is the login limit: code confirmation draws on the +// same hourly budget as login for the address. type ConfirmationSettings struct { TokenHourlyLimit int64 ClientHourlyLimit int64 + EmailHourlyLimit int64 } // EmailConfirmation confirms the address and applies the credentials of the @@ -52,7 +55,7 @@ func NewEmailConfirmation(deps ConfirmationDependencies, settings ConfirmationSe case deps.Transactor == nil, deps.Tokens == nil, deps.Credentials == nil, deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil: return nil, errors.New("identity.NewEmailConfirmation - every dependency must be set") - case settings.TokenHourlyLimit < 1, settings.ClientHourlyLimit < 1: + case settings.TokenHourlyLimit < 1, settings.ClientHourlyLimit < 1, settings.EmailHourlyLimit < 1: return nil, errors.New("identity.NewEmailConfirmation - confirmation limits must be positive") } return &EmailConfirmation{deps: deps, settings: settings}, nil @@ -114,6 +117,8 @@ func (confirmation *EmailConfirmation) Confirm(ctx context.Context, command Conf return result, nil } +// confirmationOutcomeError maps the storage outcome of a link confirmation to +// the public refusals. Expiry is reported as its own refusal. func confirmationOutcomeError(err error) error { switch { case errors.Is(err, outbound.ErrEmailTokenExpired): diff --git a/backend/internal/usecase/identity/confirmation_test.go b/backend/internal/usecase/identity/confirmation_test.go index 5b8e789..4e367c0 100644 --- a/backend/internal/usecase/identity/confirmation_test.go +++ b/backend/internal/usecase/identity/confirmation_test.go @@ -108,7 +108,7 @@ func TestEmailConfirmationKeepsInvalidTokenPrecedenceOverExpiry(t *testing.T) { confirmation, err := NewEmailConfirmation(ConfirmationDependencies{ Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil), Limiter: limiter, Keyring: keyring, Clock: func() time.Time { return now }, - }, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20}) + }, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20, EmailHourlyLimit: 10}) if err != nil { t.Fatal(err) } @@ -138,7 +138,7 @@ func TestEmailConfirmationClientLimitRunsBeforeTokenLookup(t *testing.T) { confirmation, err := NewEmailConfirmation(ConfirmationDependencies{ Transactor: transactor, Tokens: tokens, Credentials: NewCredentials(nil), Limiter: limiter, Keyring: keyring, Clock: time.Now, - }, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20}) + }, ConfirmationSettings{TokenHourlyLimit: 5, ClientHourlyLimit: 20, EmailHourlyLimit: 10}) if err != nil { t.Fatal(err) } diff --git a/backend/internal/usecase/identity/keyring.go b/backend/internal/usecase/identity/keyring.go index eda0aca..14f721d 100644 --- a/backend/internal/usecase/identity/keyring.go +++ b/backend/internal/usecase/identity/keyring.go @@ -25,6 +25,7 @@ const ( labelEmailBucket = "lincodex/identity/email-bucket/v1" labelClientBucket = "lincodex/identity/client-bucket/v1" labelTokenBucket = "lincodex/identity/verification-token-bucket/v1" + labelVerificationCode = "lincodex/identity/verification-code/v1" labelSessionCSRF = "lincodex/identity/session-csrf/v1" labelCandidateView = "lincodex/identity/candidate-view/v1" @@ -45,6 +46,7 @@ type Keyring struct { bucketKey []byte clientKey []byte tokenKey []byte + codeKey []byte sessionCSRFKey []byte candidateViewKey []byte answerKey []byte @@ -64,6 +66,7 @@ func NewKeyring(secret []byte) (*Keyring, error) { bucketKey: derive(secret, labelEmailBucket), clientKey: derive(secret, labelClientBucket), tokenKey: derive(secret, labelTokenBucket), + codeKey: derive(secret, labelVerificationCode), sessionCSRFKey: derive(secret, labelSessionCSRF), candidateViewKey: derive(secret, labelCandidateView), answerKey: derive(secret, labelAnswerFingerprint), @@ -148,6 +151,26 @@ func (keyring *Keyring) VerificationTokenBucket(rawToken string) string { return "identity:verification-token:" + hex.EncodeToString(mac.Sum(nil)) } +// VerificationCodeDigest keys a six-digit verification code under the code +// purpose key. The code space holds only a million values, so an unkeyed digest +// could be reversed by enumeration; the keyed digest cannot be checked offline +// without the server secret. +func (keyring *Keyring) VerificationCodeDigest(code domain.VerificationCode) domain.VerificationCodeHash { + mac := hmac.New(sha256.New, keyring.codeKey) + mac.Write([]byte(code.Reveal())) + return domain.VerificationCodeHash(mac.Sum(nil)) +} + +// VerifyVerificationCode compares a supplied code with a stored digest in +// constant time. +func (keyring *Keyring) VerifyVerificationCode(code domain.VerificationCode, stored domain.VerificationCodeHash) bool { + if code.IsZero() || stored.IsZero() { + return false + } + computed := keyring.VerificationCodeDigest(code) + return hmac.Equal(computed[:], stored[:]) +} + // SessionCSRF derives a synchronizer token for exactly one session. The // purpose key and message are both domain-separated from every other keyring // use, and only the encoded result is returned to the HTTP adapter. diff --git a/backend/internal/usecase/identity/keyring_test.go b/backend/internal/usecase/identity/keyring_test.go index db11970..c07f303 100644 --- a/backend/internal/usecase/identity/keyring_test.go +++ b/backend/internal/usecase/identity/keyring_test.go @@ -143,3 +143,41 @@ func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t t.Fatal("the cursor signature shares a key with the idempotency scope") } } + +func TestVerificationCodeDigestIsKeyedAndPurposeSeparated(t *testing.T) { + keyring, err := NewKeyring([]byte("keyring test secret with enough entropy")) + if err != nil { + t.Fatal(err) + } + other, err := NewKeyring([]byte("another keyring secret with enough entropy")) + if err != nil { + t.Fatal(err) + } + code, err := domain.ParseVerificationCode("482915") + if err != nil { + t.Fatal(err) + } + digest := keyring.VerificationCodeDigest(code) + if digest != keyring.VerificationCodeDigest(code) { + t.Fatal("the same code gives different digests under one key") + } + if digest == other.VerificationCodeDigest(code) { + t.Fatal("two server secrets give the same digest for one code") + } + if digest == domain.VerificationCodeHash(sha256.Sum256([]byte("482915"))) { + t.Fatal("the stored digest is an unkeyed SHA-256 of the code") + } + if !keyring.VerifyVerificationCode(code, digest) { + t.Fatal("VerifyVerificationCode() rejected the matching code") + } + wrong, err := domain.ParseVerificationCode("482916") + if err != nil { + t.Fatal(err) + } + if keyring.VerifyVerificationCode(wrong, digest) { + t.Fatal("VerifyVerificationCode() accepted a wrong code") + } + if keyring.VerifyVerificationCode(domain.VerificationCode{}, digest) || keyring.VerifyVerificationCode(code, domain.VerificationCodeHash{}) { + t.Fatal("VerifyVerificationCode() accepted a missing code or digest") + } +} diff --git a/backend/internal/usecase/identity/register.go b/backend/internal/usecase/identity/register.go index 42406a7..b869d47 100644 --- a/backend/internal/usecase/identity/register.go +++ b/backend/internal/usecase/identity/register.go @@ -365,7 +365,9 @@ func (registration *Registration) reRegister( } // issueVerification stores a new token bound to the current registration -// version and queues its message, in the caller's transaction. +// version and queues its message, in the caller's transaction. The message +// carries a six-digit code next to the link; storage keeps only the keyed digest +// of the code, which ends with the token or after the code lifetime. func (registration *Registration) issueVerification( ctx context.Context, unit outbound.UnitOfWork, @@ -383,6 +385,10 @@ func (registration *Registration) issueVerification( if err != nil { return fmt.Errorf("%s - generate token: %w", location, err) } + code, err := domain.NewVerificationCode() + if err != nil { + return fmt.Errorf("%s - generate code: %w", location, err) + } token, err := domain.NewEmailToken(domain.NewEmailTokenInput{ UserID: user.ID, Purpose: domain.EmailTokenPurposeEmailVerification, @@ -390,6 +396,8 @@ func (registration *Registration) issueVerification( RegistrationVersion: user.RegistrationVersion, IssuedAt: now, Lifetime: lifetime.Duration(), + CodeHash: registration.deps.Keyring.VerificationCodeDigest(code), + CodeLifetime: domain.VerificationCodeLifetime, Pending: pending, }) if err != nil { @@ -399,10 +407,12 @@ func (registration *Registration) issueVerification( 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, + Recipient: user.Email, + Token: token, + RawToken: raw, + Lifetime: lifetime, + Code: code, + CodeLifetime: domain.VerificationCodeLifetime, }) if err != nil { return fmt.Errorf("%s - queue message: %w", location, err) diff --git a/backend/internal/usecase/notification/mailtemplate/data.go b/backend/internal/usecase/notification/mailtemplate/data.go index 2dd42fe..edeb697 100644 --- a/backend/internal/usecase/notification/mailtemplate/data.go +++ b/backend/internal/usecase/notification/mailtemplate/data.go @@ -4,6 +4,7 @@ import ( "fmt" "log/slog" "strings" + "time" "unicode" "unicode/utf8" @@ -36,6 +37,12 @@ type VerificationData struct { // TokenLifetime is the policy value stated in the copy, from 1 hour to // 7 days. TokenLifetime domain.Hours + // Code is the six-digit code the message shows. VerificationCode redacts + // itself in fmt and slog output. + Code domain.VerificationCode + // CodeLifetime is the validity of the code stated in the copy: whole + // minutes, from 1 to 60. + CodeLifetime time.Duration } // PasswordResetData is the input of the password reset message. @@ -77,6 +84,15 @@ type tokenLinkView struct { LifetimeHours int } +// verificationCodeView is what the verification templates receive: the link +// view plus the code and its validity in whole minutes. +type verificationCodeView struct { + tokenLinkView + + Code string + CodeLifetimeMinutes int +} + // notificationView is what the notification templates receive. TextBody is // the sanitized body for the plain-text part; Paragraphs holds the same lines // for the HTML part, where html/template escapes each line. @@ -97,6 +113,26 @@ func (renderer *Renderer) tokenLinkView(linkPath string, token domain.SecretToke return tokenLinkView{Link: renderer.tokenLink(linkPath, token), LifetimeHours: int(lifetime)}, nil } +// maxCodeLifetimeMinutes bounds the code copy; the code lifetime is a fixed +// product value of 30 minutes, so a longer value in the copy would be a bug. +const maxCodeLifetimeMinutes = 60 + +func (renderer *Renderer) verificationCodeView(data VerificationData) (verificationCodeView, error) { + const location = "Renderer.verificationCodeView" + link, err := renderer.tokenLinkView(verifyEmailPath, data.Token, data.TokenLifetime) + if err != nil { + return verificationCodeView{}, err + } + if data.Code.IsZero() { + return verificationCodeView{}, invalidData(location, "verification code must be set") + } + minutes := data.CodeLifetime / time.Minute + if data.CodeLifetime%time.Minute != 0 || minutes < 1 || minutes > maxCodeLifetimeMinutes { + return verificationCodeView{}, invalidData(location, fmt.Sprintf("code lifetime must be whole minutes from 1 to %d", maxCodeLifetimeMinutes)) + } + return verificationCodeView{tokenLinkView: link, Code: data.Code.Reveal(), CodeLifetimeMinutes: int(minutes)}, nil +} + func (renderer *Renderer) notificationView(data NotificationData) (notificationView, error) { if !utf8.ValidString(data.Subject) || !utf8.ValidString(data.Body) { return notificationView{}, invalidData("Renderer.notificationView", "subject and body must be valid UTF-8") diff --git a/backend/internal/usecase/notification/mailtemplate/renderer.go b/backend/internal/usecase/notification/mailtemplate/renderer.go index 4c1efc4..f4bd9f9 100644 --- a/backend/internal/usecase/notification/mailtemplate/renderer.go +++ b/backend/internal/usecase/notification/mailtemplate/renderer.go @@ -42,7 +42,7 @@ type TemplateVersion string // The versions that new renderings use. Changing copy means adding new // template files with the next version and pointing the constant at them. const ( - currentVerificationVersion TemplateVersion = "verification.v1" + currentVerificationVersion TemplateVersion = "verification.v2" currentPasswordResetVersion TemplateVersion = "password_reset.v1" currentNotificationVersion TemplateVersion = "notification.v1" ) @@ -110,10 +110,10 @@ func NewRenderer(publicOrigin string) (*Renderer, error) { return &Renderer{origin: origin, templates: templates}, nil } -// RenderVerification renders the email confirmation message. The link is -// /verify-email#token=. +// RenderVerification renders the email confirmation message with its six-digit +// code and the link. The link is /verify-email#token=. func (renderer *Renderer) RenderVerification(data VerificationData) (RenderedMail, error) { - view, err := renderer.tokenLinkView(verifyEmailPath, data.Token, data.TokenLifetime) + view, err := renderer.verificationCodeView(data) if err != nil { return RenderedMail{}, fmt.Errorf("Renderer.RenderVerification - validate data: %w", err) } diff --git a/backend/internal/usecase/notification/mailtemplate/renderer_test.go b/backend/internal/usecase/notification/mailtemplate/renderer_test.go index 2c8231e..9e7340c 100644 --- a/backend/internal/usecase/notification/mailtemplate/renderer_test.go +++ b/backend/internal/usecase/notification/mailtemplate/renderer_test.go @@ -12,6 +12,7 @@ import ( "strings" "testing" "testing/fstest" + "time" "lincodex/backend/internal/domain" ) @@ -50,6 +51,21 @@ func testToken(t *testing.T) domain.SecretToken { return token } +// testCode is a fixed synthetic code. It is not a credential. +const ( + syntheticCode = "482915" + testCodeLifetime = 30 * time.Minute +) + +func testCode(t *testing.T) domain.VerificationCode { + t.Helper() + code, err := domain.ParseVerificationCode(syntheticCode) + if err != nil { + t.Fatalf("ParseVerificationCode() error = %v", err) + } + return code +} + func hostileNotification() NotificationData { return NotificationData{Subject: hostileSubject, Body: hostileBody, LinkPath: "/candidate/invitations"} } @@ -58,7 +74,7 @@ func hostileNotification() NotificationData { func renderAll(t *testing.T, renderer *Renderer) map[Kind]RenderedMail { t.Helper() token := testToken(t) - verification, err := renderer.RenderVerification(VerificationData{Token: token, TokenLifetime: 24}) + verification, err := renderer.RenderVerification(VerificationData{Token: token, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime}) if err != nil { t.Fatalf("RenderVerification() error = %v", err) } @@ -102,7 +118,7 @@ func assertGolden(t *testing.T, path, got string) { func TestRenderingCarriesKindAndVersion(t *testing.T) { want := map[Kind]TemplateVersion{ - KindVerification: "verification.v1", + KindVerification: "verification.v2", KindPasswordReset: "password_reset.v1", KindNotification: "notification.v1", } @@ -146,7 +162,7 @@ func TestLoopbackOriginKeepsPort(t *testing.T) { if err != nil { t.Fatalf("NewRenderer() error = %v", err) } - mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 24}) + mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime}) if err != nil { t.Fatalf("RenderVerification() error = %v", err) } @@ -251,18 +267,29 @@ func TestNotificationRejectsLinksOutsideTheApp(t *testing.T) { func TestRejectsInvalidData(t *testing.T) { renderer := newTestRenderer(t) token := testToken(t) + code := testCode(t) tokenCases := map[string]VerificationData{ - "missing token": {TokenLifetime: 24}, - "zero lifetime": {Token: token}, - "negative": {Token: token, TokenLifetime: -1}, - "lifetime too big": {Token: token, TokenLifetime: maxTokenLifetime + 1}, + "missing token": {TokenLifetime: 24, Code: code, CodeLifetime: testCodeLifetime}, + "zero lifetime": {Token: token, Code: code, CodeLifetime: testCodeLifetime}, + "negative": {Token: token, TokenLifetime: -1, Code: code, CodeLifetime: testCodeLifetime}, + "lifetime too big": {Token: token, TokenLifetime: maxTokenLifetime + 1, Code: code, CodeLifetime: testCodeLifetime}, + "missing code": {Token: token, TokenLifetime: 24, CodeLifetime: testCodeLifetime}, + "zero code lifetime": {Token: token, TokenLifetime: 24, Code: code}, + "code lifetime seconds": {Token: token, TokenLifetime: 24, Code: code, CodeLifetime: testCodeLifetime + time.Second}, + "code lifetime too long": {Token: token, TokenLifetime: 24, Code: code, CodeLifetime: 61 * time.Minute}, } for name, data := range tokenCases { if _, err := renderer.RenderVerification(data); !errors.Is(err, ErrInvalidTemplateData) { t.Fatalf("RenderVerification(%s) error = %v", name, err) } - reset := PasswordResetData(data) - if _, err := renderer.RenderPasswordReset(reset); !errors.Is(err, ErrInvalidTemplateData) { + } + resetCases := map[string]PasswordResetData{ + "missing token": {TokenLifetime: 24}, + "zero lifetime": {Token: token}, + "negative": {Token: token, TokenLifetime: -1}, + } + for name, data := range resetCases { + if _, err := renderer.RenderPasswordReset(data); !errors.Is(err, ErrInvalidTemplateData) { t.Fatalf("RenderPasswordReset(%s) error = %v", name, err) } } @@ -287,7 +314,7 @@ func TestRejectsInvalidData(t *testing.T) { func TestLifetimeCopyUsesRussianPlural(t *testing.T) { renderer := newTestRenderer(t) for hours, want := range map[domain.Hours]string{1: "1 час.", 3: "3 часа.", 11: "11 часов.", 21: "21 час.", 24: "24 часа.", 48: "48 часов.", 168: "168 часов."} { - mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: hours}) + mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: hours, Code: testCode(t), CodeLifetime: testCodeLifetime}) if err != nil { t.Fatalf("RenderVerification(%d) error = %v", hours, err) } @@ -336,10 +363,10 @@ func TestContentHashPinsTheBody(t *testing.T) { base Kind }{ {"token", func() (RenderedMail, error) { - return renderer.RenderVerification(VerificationData{Token: otherToken, TokenLifetime: 24}) + return renderer.RenderVerification(VerificationData{Token: otherToken, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime}) }, KindVerification}, {"lifetime", func() (RenderedMail, error) { - return renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 25}) + return renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 25, Code: testCode(t), CodeLifetime: testCodeLifetime}) }, KindVerification}, {"body", func() (RenderedMail, error) { data := hostileNotification() @@ -376,7 +403,7 @@ func TestRenderingNeverReachesLogs(t *testing.T) { slog.New(slog.NewTextHandler(&output, nil)), slog.New(slog.NewJSONHandler(&output, nil)), } - verification := VerificationData{Token: token, TokenLifetime: 24} + verification := VerificationData{Token: token, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime} notification := hostileNotification() // RenderedMail hides its content even in an unexported field. // NotificationData redacts itself only where fmt can call its methods. diff --git a/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.html.tmpl b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.html.tmpl new file mode 100644 index 0000000..560a0db --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.html.tmpl @@ -0,0 +1,28 @@ + + + + + + +{{.Subject}} + + +
+
+

Lincodex

+

Подтвердите адрес почты

+

Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.

+

Код подтверждения:

+

{{.View.Code}}

+

Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}.

+

Или откройте ссылку и подтвердите адрес на открывшейся странице:

+

Подтвердить почту

+

Если кнопка не работает, скопируйте ссылку в адресную строку браузера:

+

{{.View.Link}}

+

Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.

+

Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.

+
+

Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.

+
+ + diff --git a/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.subject.tmpl b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.subject.tmpl new file mode 100644 index 0000000..e2eafe9 --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.subject.tmpl @@ -0,0 +1 @@ +Подтвердите почту в Lincodex diff --git a/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.txt.tmpl b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.txt.tmpl new file mode 100644 index 0000000..e3935d2 --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/templates/verification.v2.txt.tmpl @@ -0,0 +1,18 @@ +Подтвердите адрес почты + +Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации: + +Код подтверждения: {{.View.Code}} + +Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}. + +Или откройте ссылку и подтвердите адрес на открывшейся странице: + +{{.View.Link}} + +Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}. + +Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован. + +-- +Lincodex. Письмо отправлено автоматически, отвечать на него не нужно. diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden deleted file mode 100644 index 6e9827d..0000000 --- a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden +++ /dev/null @@ -1,14 +0,0 @@ -Subject: Подтвердите почту в Lincodex - -Подтвердите адрес почты - -Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице: - -https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv - -Ссылка действует 24 часа. - -Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован. - --- -Lincodex. Письмо отправлено автоматически, отвечать на него не нужно. diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.html.golden similarity index 66% rename from backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden rename to backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.html.golden index bcbdb86..484ba70 100644 --- a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden +++ b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.html.golden @@ -11,12 +11,16 @@

Lincodex

Подтвердите адрес почты

-

Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице.

+

Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.

+

Код подтверждения:

+

482915

+

Код действует 30 минут.

+

Или откройте ссылку и подтвердите адрес на открывшейся странице:

Подтвердить почту

Если кнопка не работает, скопируйте ссылку в адресную строку браузера:

https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv

Ссылка действует 24 часа.

-

Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.

+

Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.

Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.

diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.txt.golden b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.txt.golden new file mode 100644 index 0000000..f159799 --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v2.txt.golden @@ -0,0 +1,20 @@ +Subject: Подтвердите почту в Lincodex + +Подтвердите адрес почты + +Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации: + +Код подтверждения: 482915 + +Код действует 30 минут. + +Или откройте ссылку и подтвердите адрес на открывшейся странице: + +https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv + +Ссылка действует 24 часа. + +Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован. + +-- +Lincodex. Письмо отправлено автоматически, отвечать на него не нужно. diff --git a/backend/internal/usecase/notification/service_mail.go b/backend/internal/usecase/notification/service_mail.go index bc52734..fd8d9e4 100644 --- a/backend/internal/usecase/notification/service_mail.go +++ b/backend/internal/usecase/notification/service_mail.go @@ -29,6 +29,11 @@ type TokenMailRequest struct { // Lifetime is the validity of the token that the message states, in // whole hours. Lifetime domain.Hours + // Code is the six-digit code of an email verification message, and + // CodeLifetime its validity as the message states it. Both are required + // for email verification and unused by the other kinds. + Code domain.VerificationCode + CodeLifetime time.Duration } // ServiceMailer stores service mail of the account flows (email verification @@ -65,7 +70,15 @@ func (mailer *ServiceMailer) EnqueueVerification(ctx context.Context, unit outbo if err := checkTokenMailRequest(location, request, domain.EmailTokenPurposeEmailVerification); err != nil { return uuid.Nil, err } - content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{Token: request.RawToken, TokenLifetime: request.Lifetime}) + if request.Code.IsZero() { + return uuid.Nil, fmt.Errorf("%s - verification code must be set: %w", location, domain.ErrInvalidEmailToken) + } + content, err := mailer.renderer.RenderVerification(mailtemplate.VerificationData{ + Token: request.RawToken, + TokenLifetime: request.Lifetime, + Code: request.Code, + CodeLifetime: request.CodeLifetime, + }) if err != nil { return uuid.Nil, fmt.Errorf("%s - render message: %w", location, err) } diff --git a/backend/internal/usecase/notification/service_mail_test.go b/backend/internal/usecase/notification/service_mail_test.go index 31352be..c05cb88 100644 --- a/backend/internal/usecase/notification/service_mail_test.go +++ b/backend/internal/usecase/notification/service_mail_test.go @@ -47,7 +47,14 @@ func (h *serviceMailHarness) request(t *testing.T, purpose domain.EmailTokenPurp if err != nil { t.Fatalf("NewEmailAddress() error = %v", err) } - return TokenMailRequest{Recipient: recipient, Token: token, RawToken: raw, Lifetime: 24} + code, err := domain.NewVerificationCode() + if err != nil { + t.Fatalf("NewVerificationCode() error = %v", err) + } + return TokenMailRequest{ + Recipient: recipient, Token: token, RawToken: raw, Lifetime: 24, + Code: code, CodeLifetime: domain.VerificationCodeLifetime, + } } func TestServiceMailerStoresATokenBoundDeliveryUnderTheTokenID(t *testing.T) { @@ -125,6 +132,8 @@ func TestServiceMailerRefusesAWrongTokenBeforeRendering(t *testing.T) { "no recipient": func(request *TokenMailRequest) { request.Recipient = domain.EmailAddress{} }, "zero lifetime": func(request *TokenMailRequest) { request.Lifetime = 0 }, "lifetime >7d": func(request *TokenMailRequest) { request.Lifetime = 24 * 8 }, + "no code": func(request *TokenMailRequest) { request.Code = domain.VerificationCode{} }, + "code lifetime": func(request *TokenMailRequest) { request.CodeLifetime = 90 * time.Second }, } { request := h.request(t, domain.EmailTokenPurposeEmailVerification) change(&request) diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index b58e74d..4425e7a 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -350,6 +350,8 @@ Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in t Links. The token travels only in the URL fragment: `/verify-email#token=` and `/reset-password#token=`, built by `mailtemplate` (`tokenLink`). A browser never sends the fragment to a server, so the token stays out of the nginx access log, which records `$uri`, out of Referer headers, and out of the Go request log; it is not in the path and not in the query. The frontend reads and removes the fragment, waits for explicit confirmation, then sends the token and registration password in the API request. It also consumes a new link opened in the same tab and ignores results from an older in-flight request. The password reset route and API are not implemented. The renderer rejects a token in any other place, its golden files and tests fix the format, and the delivery tests check that the stored body holds the link with the fragment and no `?token=`. The body in `deliveries` holds the live token until the mail is sent or cancelled; see Personal data at rest. +Codes. Each verification message also carries a six-digit code: in the text part as the line `Код подтверждения: ` (the Russian copy), and in the HTML part as a large block. The code lives 30 minutes, or until its token ends when that is sooner, and the message states that lifetime. The code is an alternative to the link, not a replacement: `ConfirmEmailByCode` checks it (see Registration, email verification, and resend). Like the link, the code stays in the body of the delivery until the mail is sent or cancelled, and is then redacted; the token row keeps only a keyed digest of the code, never the code. Read access to `deliveries` before that point exposes the code too. + One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps: 1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending`, `waiting_quota`, or a scheduled `unknown`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. An initial uncertain result is scheduled only while the delivery is inside the automatic cutoff; terminal unknown rows and unknown rows without a due time wait for an operator. A single-use manual authorization also makes an unknown row due. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows. @@ -765,7 +767,7 @@ The brief references Russian Federal Law 152-FZ. The system design calls for sep Identity storage is implemented in migration `backend/db/migrations/00002_create_identity_tables.sql`, the queries in `backend/db/queries/identity.sql`, the domain types, outbound ports, and the PostgreSQL adapter. The backend API implements registration, verification resend, `ConfirmEmail`, login, and basic current-session operations. The frontend registration and confirmation screens are implemented; see the [API contract](../../api/README.en.md#identity-sessions-cookie-and-csrf). - `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case. -- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists allowed purposes, so password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. Migration 00014 adds `pending_password_hash`, `pending_scenario`, and `pending_onboarding_step`, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated. +- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists allowed purposes, so password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. Migration 00014 adds `pending_password_hash`, `pending_scenario`, and `pending_onboarding_step`, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated. Migration `00046_add_email_verification_codes.sql` adds `code_hash` (HMAC-SHA-256 of the six-digit code under a server key, NULL when the token carries no code or the code has ended), `code_expires_at`, and `code_failed_attempts` (0 to 5). The code expiry is the earlier of the token expiry and the 30-minute code lifetime, and the application checks both on every use. - `sessions`: a UUIDv7 `id` that never leaves the server, `token_hash` (SHA-256 of the cookie value, unique), `user_id`, `created_at`, `last_seen_at`, the absolute `expires_at`, and `revoked_at`. No IP address or user agent is stored. - Tokens and sessions reference `users` with `ON DELETE CASCADE`. Consent records reference it with `ON DELETE RESTRICT` instead; see [Consent ledger](#consent-ledger). CHECK constraints repeat the domain rules as a backstop: the ASCII address and its key, the PHC format, and timestamps (verification, consumption, invalidation, and revocation) not earlier than `created_at`. @@ -861,12 +863,14 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/auth.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`. -One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account. +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, the keyed digest of its six-digit code, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account. Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns `pending_*` of `email_tokens`, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the `users` row: `UserRepository.AdvanceRegistration` only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The `password_hash`, `scenario`, and `onboarding_step` of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on `domain.User`). Invalidating a token (`InvalidateActive`) clears its `pending_*` columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing. Email confirmation (`ConfirmEmail`) is implemented. It requires the password saved with that token's registration and checks it against the pending hash. In one transaction the backend checks the current registration version and its C1 record, consumes the token, verifies the address, applies the token's password hash, scenario, and onboarding step to the account, clears `pending_*`, and records exactly one secret-free `identity.email_verified` event. Any refusal leaves the account and token unchanged. Unknown, used, replaced, or superseded tokens, a wrong password, and missing pending credentials answer `verification_token_invalid`; an expired token answers `verification_token_expired`. The Origin must match exactly `APP_PUBLIC_URL`. Confirmation does not create a session. The frontend confirmation screen is implemented and covered by the local registration browser flow. +Confirmation by code (`ConfirmEmailByCode`) is implemented in `backend/internal/usecase/identity/code_confirmation.go`. It takes the address, the six-digit code, and the password chosen for the registration. The checks run in this order. First the rate limits: per client (`IDENTITY_CLIENT_HOURLY_LIMIT`) and per normalized address, which shares the login counter (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`). Then the newest open verification token of the unverified account at that address, with the current registration version and a code. Then the password against the token's pending hash, then the keyed digest of the code (compared in constant time) and the code expiry. The password is checked on every branch with the same hashing work; with no open code a dummy hash is used, so the response time does not reveal the account. A successful check runs the same transaction as the link confirmation, so one token is consumed once: a code after the link is refused, and a link after the code is refused. Every failed check of an open code (a wrong code, a wrong password, or an expired code) adds one to `code_failed_attempts` in a single conditional UPDATE. The database serializes these updates, so concurrent wrong attempts never count more than five. The fifth failure invalidates the token and clears its code and pending credentials, so the link stops working too, and the user must request a new message. A resend invalidates the earlier codes together with the earlier tokens. Every refusal (an unknown address, no open code, a wrong code, an expired code, a wrong password, or an invalidated token) answers 400 `verification_token_invalid` with the same body, so the answer does not show which addresses have a pending registration. Success answers the same body as the link confirmation and creates no session. The verification message uses the template `verification.v2`; the earlier link-only template `verification.v1` is no longer rendered. + Login accepts only a verified email and checks the account's stored password, never pending registration credentials. An unknown address, wrong password, and invalid stored hash receive the same `invalid_credentials`; unknown addresses and invalid hashes also run `VerifyDummy`, and an invalid stored hash is logged without the email or hash. A correct password for an unverified account answers `email_not_verified` and creates no session. Successful login creates a new session; if the request carried a valid session cookie, the backend revokes it and creates the new session in one transaction. Failed login does not revoke an existing session, and a malformed cookie cannot become a principal. Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 05557bb..6f01bc9 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -10,7 +10,7 @@ This section is for anyone who starts the MVP on their own machine: the jury, th Implemented in this build (backend API and frontend screens): -- Candidate and employer registration with consent C1, email confirmation through the link in the message, sign-in, sign-out, and resuming from the saved step. Mail is sent only with `EMAIL_PROVIDER=resend`. +- Candidate and employer registration with consent C1, email confirmation with the six-digit code or the link from the message, sign-in, sign-out, and resuming from the saved step. Mail is sent only with `EMAIL_PROVIDER=resend`. - Candidate cabinet: consents C1-C5, a manual profile without a resume and without an FSP ID, the questionnaire with specializations and self-assessment, and the home page with the next step. - Skill assessment: the `demo_express` demonstration express run without a grade and the `demo_basic` full test with a result, result history, and skill evidence. On the demo stand a passed full test receives an uncalibrated synthetic category. The operator can read the [review band](#assessment-review-band). - Privacy: publication of the anonymous card (C2), preview, search status, hidden organizations, and the history of changes and card views. @@ -347,7 +347,7 @@ The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects e Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. With `EMAIL_PROVIDER=resend`, the backend runs a worker for service identity mail (email verification and password reset), and registration queues a verification email. Password reset is not implemented, and product notifications are stored as deliveries but not sent until product notification sending is implemented. See [Sending service mail](#sending-service-mail). -Release compatibility: `ConfirmEmail` requires both `token` and the password selected for that registration. Clients that send only the token must be updated. Migration `00016_bind_registration_consent.sql` adds the registration version to C1 and backfills legacy records from the current account version without requiring a live token. It checks that a registration C1 is not older than the latest registration and that an account has at most one active registration C1; on inconsistency, the migration stops without partial changes. A trigger fills the version when an old backend omits it and rejects a mismatched version sent by the new backend. A partial unique index allows at most one unrevoked registration C1 per account and registration version. Apply the migration before updating the backend. To roll back, deploy the old backend before reverting the migration. No new environment variable is needed. `APP_PUBLIC_URL` also defines the Origin that confirmation requests must send. +Release compatibility: `ConfirmEmail` requires both `token` and the password selected for that registration. Clients that send only the token must be updated. Migration `00016_bind_registration_consent.sql` adds the registration version to C1 and backfills legacy records from the current account version without requiring a live token. It checks that a registration C1 is not older than the latest registration and that an account has at most one active registration C1; on inconsistency, the migration stops without partial changes. A trigger fills the version when an old backend omits it and rejects a mismatched version sent by the new backend. A partial unique index allows at most one unrevoked registration C1 per account and registration version. Apply the migration before updating the backend. To roll back, deploy the old backend before reverting the migration. No new environment variable is needed. `APP_PUBLIC_URL` also defines the Origin that confirmation requests must send. The new `ConfirmEmailByCode` operation (`POST /api/v1/identity/email-verifications/code`) and migration `00046_add_email_verification_codes.sql` are additive: existing clients keep confirming by link. The migration can be rolled back once no usable code is left; its down step refuses until then. `resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; the sending worker owns retries, backoff, rate-limit pacing, and outcome records, while the quota gate schedules a known daily or monthly reset (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport). diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 55ef6db..88471dd 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -44,6 +44,8 @@ Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS TestEmailVerificationOverHTTP obtains a token from the Resend fixture after registration. It checks candidate and employer confirmation, no session or cookie, and unchanged state after an unknown, expired, replaced, or consumed token, a wrong password, or missing pending credentials. It also checks C1 version binding, missing, null, and foreign Origin values, plus rate limits, expiry after a lock wait, rollback after an outbox failure, and one event from concurrent confirmations. It covers the API only and does not send through an external mail provider. The separate local registration browser flow covers the frontend. +TestEmailVerificationCodeOverHTTP (`backend/integration_test/email_code_test.go`) takes the code and the link from the same fixture message. It checks that the code confirms like the link; that five wrong codes burn the token, after which the right code and the link both fail; that eight concurrent wrong codes count exactly five attempts; that a wrong password counts; that an expired code leaves the link valid; that the link and the code consume one token in either order; that a resend replaces the code; that a registration replaced by another registration cannot be confirmed with its code; that an unknown address and a wrong code give the same refusal; and that the address limit answers 429 after ten requests. Its origin case refuses a foreign Origin before the usecase runs. + API verification checks the OpenAPI subset exercised by pinned tools, fixtures, and contracts that actually ran. Its result applies only to those inputs. CI YAML in the repository does not mean a workflow has run on GitHub. Deployment smoke checks infrastructure routes, Compose startup, PostgreSQL/Redis/SeaweedFS readiness, Redis authentication and cache configuration, rejection of anonymous SeaweedFS bucket access, isolation of SeaweedFS from the frontend (by name and by its storage network address), rejection of filer, master, and volume HTTP requests that do not come from inside the SeaweedFS container, and the backend startup log for `EMAIL_PROVIDER=disabled`. The backend relay connects to Kafka in the smoke stack, but the smoke does not check that it publishes. It stops Redis and SeaweedFS in turn to verify that /readyz returns 503 while /api/v1/healthz remains available, then verifies readiness recovery after each dependency restarts. It sends no mail and does not check mail delivery, contact release, protection of product data, ML robustness, ranking quality, PDF export, or the two-role flow. A separate monitoring check does not verify the core database or end-to-end telemetry from the application. @@ -75,6 +77,8 @@ The ordinary technical suite does not cover candidate or employer workflows, sig The registration-mode suite additionally runs `frontend/e2e/auth-registration.spec.ts`: candidate and employer registration with visible C1, real local resend and a distinct received message, same-tab replacement of the verification link, wrong-password retry, confirmation without automatic login, sign-in, and restoring the server step after reload. It checks keyboard focus and overflow at 360, 768, and 1280 pixels. Expired-link rendering uses a controlled problem response; actual token expiry is covered by backend integration tests. Only this isolated overlay sets `VERIFICATION_MAIL_MIN_INTERVAL=1s`; normal and release environments retain their configured interval. Auth traces, failure screenshots, and video are disabled; explicit review screenshots show only token-free states and synthetic addresses. No external mail or production edge flow is verified. +Since the code step, the same suite confirms each candidate and employer registration with the six-digit code from the message: a wrong code first, a reload that asks for the password again, and a check that no browser storage holds the password. A separate test keeps the link as the fallback: an expired link leads to the code step, which sends a new message, and the link from that message then confirms the registration. + In the same mode, the runner invokes `/consent-fixture` from the test backend image before starting the browser. The command exists only with the Go `e2e` build tag, requires `E2E_CONSENT_FIXTURE=1`, and uses domain objects and transactional ports to create a synthetic verified candidate, C1/C2, and two C4 scopes for different companies. A collision with an existing test address stops the run. Ordinary and release images contain neither the command nor its enabled flag. `frontend/e2e/consent-management.spec.ts` uses normal sign-in and real consent APIs to grant C3 independently, revoke C2 and one C4, retain the other scope, reload, and submit a C1 request whose returned status is shown. A controlled 403 exercises the failure UI; successful mutations reach PostgreSQL. Synthetic invitation IDs in the fixture do not prove the invitation acceptance flow. Traces and automatic screenshots are disabled; the explicit review screenshot contains only synthetic data. The same command also seeds a second synthetic candidate for `frontend/e2e/privacy-visibility.spec.ts`: an active C1 and C2, one C4 for the first of two new companies, and three recorded card reads (a card view and a contact read by the first company, a card view by the second). The reads are inserted through the privacy port because the organization read path needs search results that do not exist yet; they do not prove that path. With the real backend, the suite confirms the search status without publishing, publishes after the explicit C2 step, compares the owner preview with the API response, hides one company and brings it back, revokes C2 and checks the closure explanation, grants C2 again without reopening the card, and republishes with the keyboard alone; in the mail-fixture mode a freshly registered candidate with two declared specializations and no test publishes and sees the not-confirmed grade status for each. A stubbed group renders a confirmed Backend next to unconfirmed specializations, the evidence basis and calibration labels, empty histories, a failed save that keeps the draft, and a revoked C2. No test reads the card as an employer, so the immediate loss of access of a hidden employer is not checked in a browser. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index bfcde8f..5ae3041 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -350,6 +350,8 @@ Offsets и партиции. Каждый обработчик - один уча Ссылки. Токен передается только во фрагменте URL: `/verify-email#token=` и `/reset-password#token=`; ссылки строит `mailtemplate` (`tokenLink`). Браузер никогда не отправляет фрагмент серверу, поэтому токен не попадает в access log nginx, который пишет `$uri`, в заголовки Referer и в журнал запросов Go; его нет ни в пути, ни в query. Frontend читает и удаляет токен из фрагмента, затем после явного действия пользователя отправляет его вместе с паролем регистрации. Новая ссылка в той же вкладке заменяет токен; результат прежнего запроса не меняет новую форму. Маршрут и API сброса пароля не реализованы. Renderer отклоняет токен в любом другом месте, golden-файлы и тесты фиксируют формат, а тесты доставок проверяют, что сохраненное тело содержит ссылку с фрагментом и не содержит `?token=`. Тело в `deliveries` хранит действующий токен, пока письмо не отправлено или не отменено; см. "Персональные данные в хранилище". +Коды. Каждое письмо подтверждения содержит также шестизначный код: в текстовой части строкой `Код подтверждения: <код>`, в HTML-части крупным блоком. Код действует 30 минут либо до конца срока токена, если токен заканчивается раньше; письмо называет этот срок. Код - альтернатива ссылке, а не ее замена: его проверяет `ConfirmEmailByCode` (см. раздел о регистрации и подтверждении). Как и ссылка, код остается в теле доставки до отправки или отмены письма и затем очищается; строка токена хранит только keyed-дайджест кода, но не сам код. Чтение `deliveries` до этого момента раскрывает и код. + Один проход `ServiceMailSender.ProcessNext` проводит одну доставку через три шага: 1. Транзакция захвата. `DeliveryRepository.ClaimDue` берет самую просроченную доставку с `FOR UPDATE SKIP LOCKED`: вид `verification` или `password_reset` (литералы совпадают с предикатом `deliveries_due_idx`, поэтому опрос читает только этот малый индекс), статус `pending`, `waiting_quota` или запланированный `unknown`, наступивший `next_attempt_at`, доставка закреплена за настроенным аккаунтом провайдера и ее не держит живой lease. Неопределенный исход автоматически ставится на повтор только до cutoff; `unknown` без срока ждет оператора. Однократное разрешение оператора тоже ставит `unknown` в очередь. Захват записывает `claim_owner` и `claimed_until` (lease), не меняя версию и время обновления, поэтому несколько процессов не возьмут одну доставку. Lease измеряется часами базы данных (`clock_timestamp()` плюс длина lease, и он жив, пока `claimed_until` позже `clock_timestamp()`), а не часами экземпляра приложения; сроки доставок остаются на часах приложения, которые их записали. В той же транзакции отправитель переносит на настроенный аккаунт письма, сохраненные при `EMAIL_PROVIDER=disabled` (это разрешено только до первой попытки, пока ключ не видел ни один провайдер), выполняет проверку ниже, а затем `QuotaGate.PrepareSend`, который резервирует получателя или переводит доставку в `waiting_quota`. Транзакция фиксируется до вызова транспорта, поэтому медленный провайдер никогда не держит блокировку строки. Сбой внутри нее (детерминированный, например строка, которую нельзя восстановить) откатывает и lease, поэтому сбой записывается для строки отдельной транзакцией; см. "Сбойные строки". @@ -765,7 +767,7 @@ contact_grant относится к паре кандидат-компания Хранение identity реализовано миграцией `backend/db/migrations/00002_create_identity_tables.sql`, запросами `backend/db/queries/identity.sql`, доменными типами, outbound-портами и адаптером Postgres. Backend API реализует регистрацию, повторную отправку подтверждения, `ConfirmEmail`, вход и базовые операции с текущей сессией. Экраны регистрации и подтверждения во frontend реализованы; см. [контракт API](../../api/README.md#identity-сессии-cookie-и-csrf). - `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр. -- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. Миграция 00014 добавляет `pending_password_hash`, `pending_scenario` и `pending_onboarding_step`, чтобы каждый токен нес данные своей регистрации. CHECK допускает не больше одного из consumed и invalidated. +- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. Миграция 00014 добавляет `pending_password_hash`, `pending_scenario` и `pending_onboarding_step`, чтобы каждый токен нес данные своей регистрации. CHECK допускает не больше одного из consumed и invalidated. Миграция `00046_add_email_verification_codes.sql` добавляет `code_hash` (HMAC-SHA-256 шестизначного кода под серверным ключом; NULL, если у токена нет кода или код закончился), `code_expires_at` и `code_failed_attempts` (от 0 до 5). Срок кода - меньший из срока токена и 30-минутного срока кода; приложение проверяет оба при каждом использовании. - `sessions`: UUIDv7 `id`, который не покидает сервер, `token_hash` (SHA-256 значения cookie, уникальный), `user_id`, `created_at`, `last_seen_at`, абсолютный `expires_at` и `revoked_at`. IP-адрес и user agent не хранятся. - Токены и сессии ссылаются на `users` с `ON DELETE CASCADE`. Записи согласий ссылаются на него с `ON DELETE RESTRICT`; см. [Журнал согласий](#журнал-согласий). CHECK-ограничения дублируют доменные правила как последнюю защиту: ASCII-адрес и его ключ, формат PHC и времена (подтверждения, погашения, аннулирования и отзыва) не раньше `created_at`. @@ -853,12 +855,14 @@ contact_grant относится к паре кандидат-компания Реализовано: `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/auth.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`. -Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт. +Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, keyed-дайджест его шестизначного кода и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт. Отложенные учетные данные (защита от pre-hijack). Каждая регистрация, первая и каждая повторная, хранит хеш пароля, сценарий и первый шаг онбординга на своем токене подтверждения (столбцы `pending_*` таблицы `email_tokens`, миграция 00014). Повторная регистрация неподтвержденного адреса никогда не меняет учетные данные, сценарий и шаг онбординга строки `users`: `UserRepository.AdvanceRegistration` только увеличивает версию регистрации и время регистрации (и удаляет C1 прежней регистрации), а новый токен несет новые отложенные данные. Повторная отправка копирует отложенные данные новейшего токена регистрации. `password_hash`, `scenario` и `onboarding_step` строки неподтвержденного аккаунта не авторитетны, пока подтверждение не применит отложенные данные нажатого токена: в них значения первого регистранта лишь потому, что столбцы обязательны, и никакой код не вправе по ним аутентифицировать или им доверять (см. комментарий к `domain.User`). Аннулирование токена (`InvalidateActive`) очищает его столбцы `pending_*`, а CHECK не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает. Подтверждение почты (`ConfirmEmail`) реализовано. Оно требует пароль, сохраненный для регистрации этого токена, и проверяет его по отложенному хешу. В одной транзакции backend проверяет текущую версию регистрации и запись C1, погашает токен, подтверждает адрес, переносит с токена на аккаунт хеш пароля, сценарий и шаг онбординга, очищает `pending_*` и записывает ровно одно событие `identity.email_verified` без секретов. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный, устаревший токен, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`; истекший токен дает `verification_token_expired`. Origin должен точно совпадать с `APP_PUBLIC_URL`. Подтверждение не создает сессию. Экран подтверждения во frontend реализован и проверен локальным браузерным потоком регистрации. +Подтверждение кодом (`ConfirmEmailByCode`) реализовано в `backend/internal/usecase/identity/code_confirmation.go`. Оно принимает адрес, шестизначный код и пароль, выбранный при регистрации. Проверки идут в таком порядке. Сначала лимиты запросов: по клиенту (`IDENTITY_CLIENT_HOURLY_LIMIT`) и по нормализованному адресу, который делит счетчик со входом (`IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT`). Затем самый новый открытый токен подтверждения непроверенного аккаунта с этим адресом, с текущей версией регистрации и кодом. Затем пароль по отложенному хешу токена, затем keyed-дайджест кода (сравнение за постоянное время) и срок кода. Пароль проверяется на каждой ветке одинаковой работой хеширования: если открытого кода нет, используется фиктивный хеш, поэтому время ответа не раскрывает аккаунт. Успешная проверка выполняет ту же транзакцию, что и подтверждение по ссылке, поэтому токен погашается один раз: код после ссылки и ссылка после кода оба отказывают. Каждая неудачная проверка открытого кода (неверный код, неверный пароль или истекший код) добавляет единицу в `code_failed_attempts` одним условным UPDATE; база сериализует такие обновления, поэтому параллельные неверные попытки не засчитываются больше пяти. Пятая неудача аннулирует токен и очищает его код и отложенные учетные данные, поэтому перестает работать и ссылка, а пользователю нужно запросить новое письмо. Повторная отправка аннулирует прежние коды вместе с прежними токенами. Любой отказ (неизвестный адрес, нет открытого кода, неверный код, истекший код, неверный пароль или аннулированный токен) отвечает 400 `verification_token_invalid` одним и тем же телом, поэтому ответ не показывает, у каких адресов есть отложенная регистрация. Успех отвечает тем же телом, что и подтверждение по ссылке, и сессию не создает. Письмо подтверждения использует шаблон `verification.v2`; шаблон `verification.v1` (только ссылка) больше не рендерится. + Вход принимает только подтвержденный email и проверяет сохраненный пароль аккаунта, а не отложенные данные регистрации. Неизвестный адрес, неверный пароль и некорректный сохраненный хеш получают одинаковый `invalid_credentials`; неизвестный адрес и некорректный хеш дополнительно проходят `VerifyDummy`, а ошибка сохраненного хеша записывается в лог без email или хеша. Верный пароль для неподтвержденного аккаунта отвечает `email_not_verified` и не создает сессию. Успешный вход создает новую сессию; если запрос принес действующую cookie сессии, сервер отзывает ее и создает новую в одной транзакции. Неуспешный вход не отзывает старую сессию, а некорректная cookie не становится principal. Порядок проверок регистрации: валидация всего тела и версии текста C1, проверка воспроизведения, лимит, хеш пароля (в каждой ветке, до чтения аккаунта), транзакция. Ошибка валидации (400) не зависит от хранимых аккаунтов и не расходует лимит. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index cda8b6f..389aeb6 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -10,7 +10,7 @@ Реализовано в этой сборке (API backend и экраны frontend): -- Регистрация кандидата и работодателя с согласием C1, подтверждение email по ссылке из письма, вход, выход и продолжение с сохраненного шага. Письмо уходит только при `EMAIL_PROVIDER=resend`. +- Регистрация кандидата и работодателя с согласием C1, подтверждение email по коду или ссылке из письма, вход, выход и продолжение с сохраненного шага. Письмо уходит только при `EMAIL_PROVIDER=resend`. - Кабинет кандидата: согласия C1-C5, ручной профиль без резюме и без ФСП ID, анкета со специализациями и самооценкой, главная страница со следующим шагом. - Проверка навыков: демонстрационный экспресс-запуск `demo_express` без грейда и полный тест `demo_basic` с результатом, историей результатов и доказательством навыка. На демонстрационном стенде пройденный полный тест получает неоткалиброванную синтетическую категорию. Оператору доступна [полоса ручной проверки](#полоса-проверки-оценки). - Приватность: публикация анонимной карточки (C2), предпросмотр, статус поиска, скрытие организаций, история изменений и просмотров карточки. @@ -349,7 +349,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. При `EMAIL_PROVIDER=resend` backend запускает worker служебной почты identity (подтверждение почты и сброс пароля); регистрация ставит письмо подтверждения в очередь. Сброс пароля не реализован, а продуктовые уведомления сохраняются как доставки, но не отправляются до реализации их отправки. См. [Отправка служебной почты](#отправка-служебной-почты). -Совместимость выпуска: `ConfirmEmail` требует `token` и пароль, выбранный при соответствующей регистрации. Клиенты, которые отправляли только токен, нужно обновить. Миграция `00016_bind_registration_consent.sql` добавляет версию регистрации к C1 и заполняет ее для прежних записей по текущей версии аккаунта, без требования живого токена. Она проверяет, что регистрационная C1 не старше последней регистрации и что у аккаунта нет нескольких активных регистрационных C1; при несоответствии миграция останавливается без частичных изменений. Триггер заполняет версию, если старый backend не передал ее, и отклоняет несовпадающую версию от нового backend. Частичный уникальный индекс допускает не больше одной неотозванной регистрационной C1 на аккаунт и версию регистрации. Миграцию можно применить до обновления backend. При откате сначала верните старый backend, затем отмените миграцию. Новые переменные окружения не нужны. `APP_PUBLIC_URL` также задает Origin, который должен передавать запрос подтверждения. +Совместимость выпуска: `ConfirmEmail` требует `token` и пароль, выбранный при соответствующей регистрации. Клиенты, которые отправляли только токен, нужно обновить. Миграция `00016_bind_registration_consent.sql` добавляет версию регистрации к C1 и заполняет ее для прежних записей по текущей версии аккаунта, без требования живого токена. Она проверяет, что регистрационная C1 не старше последней регистрации и что у аккаунта нет нескольких активных регистрационных C1; при несоответствии миграция останавливается без частичных изменений. Триггер заполняет версию, если старый backend не передал ее, и отклоняет несовпадающую версию от нового backend. Частичный уникальный индекс допускает не больше одной неотозванной регистрационной C1 на аккаунт и версию регистрации. Миграцию можно применить до обновления backend. При откате сначала верните старый backend, затем отмените миграцию. Новые переменные окружения не нужны. `APP_PUBLIC_URL` также задает Origin, который должен передавать запрос подтверждения. Новая операция `ConfirmEmailByCode` (`POST /api/v1/identity/email-verifications/code`) и миграция `00046_add_email_verification_codes.sql` аддитивны: прежние клиенты продолжают подтверждать по ссылке. Откат миграции возможен, когда не осталось действующих кодов; ее down-шаг до этого момента отказывает. `resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов выполняет worker отправки, а ожидание известного сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт). diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index 0a13fdf..c1098c4 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -44,6 +44,8 @@ make -C ml check-generated использует datamodel-code-generator --check TestEmailVerificationOverHTTP получает токен из Resend fixture после регистрации. Тест проверяет подтверждение candidate и employer, отсутствие сессии и cookie, неизменность состояния при неизвестном, истекшем, замененном или погашенном токене, неверном пароле и отсутствии отложенных данных. Он также проверяет привязку C1 к версии регистрации, отсутствующий, null и чужой Origin, а также лимиты, истечение срока после ожидания блокировки, откат после сбоя outbox и одно событие при параллельном подтверждении. Тест охватывает только API; внешний почтовый провайдер не вызывается. Frontend проверяет отдельный локальный браузерный поток регистрации. +TestEmailVerificationCodeOverHTTP (`backend/integration_test/email_code_test.go`) берет код и ссылку из одного сообщения фикстуры. Он проверяет, что код подтверждает регистрацию так же, как ссылка; что пять неверных кодов аннулируют токен, после чего правильный код и ссылка не работают; что восемь параллельных неверных кодов засчитываются ровно как пять попыток; что неверный пароль засчитывается; что истекший код не отменяет ссылку; что ссылка и код погашают один токен в любом порядке; что повторная отправка заменяет код; что регистрация, замененная другой регистрацией, не подтверждается своим кодом; что неизвестный адрес и неверный код дают один и тот же отказ; что лимит адреса отвечает 429 после десяти запросов. Тест origin отклоняет чужой Origin до запуска usecase. + API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub. Deployment smoke проверяет инфраструктурные маршруты, запуск Compose, готовность PostgreSQL/Redis/SeaweedFS, аутентификацию и настройки кеша Redis, отказ SeaweedFS в анонимном доступе к bucket, изоляцию SeaweedFS от frontend (по имени и по адресу в сети хранилища), отказ HTTP API filer, master и volume на запросы не изнутри контейнера SeaweedFS и запись в логе запуска backend о `EMAIL_PROVIDER=disabled`. В smoke-стеке relay backend подключается к Kafka, но smoke не проверяет, что он публикует события. Он поочередно останавливает Redis и SeaweedFS и проверяет, что /readyz возвращает 503, а /api/v1/healthz остается доступным, затем проверяет восстановление готовности после запуска зависимости. Он не отправляет писем и не проверяет доставку почты, получение контактов, защищенность бизнес-данных, устойчивость ML, точность ранжирования, PDF экспорт или сценарий двух ролей. Отдельная проверка мониторинга не подтверждает core database или end-to-end доставку данных от приложения. @@ -75,6 +77,8 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись. +С появлением шага кода тот же набор проверяет подтверждение каждой регистрации кандидата и работодателя шестизначным кодом из письма: сначала неверный код, затем перезагрузка страницы, на которой пароль запрашивается снова, и проверка, что браузерное хранилище не содержит пароль. Отдельный тест оставляет ссылку запасным путем: истекшая ссылка ведет на шаг кода, который отправляет новое письмо, и ссылка из этого письма подтверждает регистрацию. + В этом же режиме runner перед браузером запускает `/consent-fixture` из тестового backend-образа. Команда доступна только с Go build tag `e2e`, требует `E2E_CONSENT_FIXTURE=1` и через домен и транзакционные порты создает синтетического подтвержденного кандидата, C1/C2 и два C4 для разных компаний. Совпадение тестового адреса с существующим аккаунтом останавливает запуск. Обычный и release-образы не содержат команду и не включают этот флаг. Сценарий `frontend/e2e/consent-management.spec.ts` использует обычный вход и реальные API согласий: отдельную выдачу C3, отзыв C2 и одного C4, сохранение другого scope, перезагрузку и C1 request со статусом из ответа. Отказ сервера для проверки UI задается управляемым 403; успешные изменения идут в PostgreSQL. Синтетические invitation IDs в fixture не доказывают реализацию принятия приглашений. Трассы и автоматические снимки отключены; явный снимок показывает только синтетические данные. Та же команда создает второго синтетического кандидата для `frontend/e2e/privacy-visibility.spec.ts`: действующие C1 и C2, один C4 для первой из двух новых компаний и три записанных чтения карточки (просмотр карточки и чтение контактов первой компанией, просмотр карточки второй). Чтения вставлены через порт приватности, потому что путь чтения организацией требует результатов поиска, которых еще нет; они не доказывают этот путь. На настоящем backend набор подтверждает статус поиска без публикации, публикует после явного шага C2, сверяет предпросмотр владельца с ответом API, скрывает одну компанию и возвращает ее, отзывает C2 и проверяет объяснение закрытия, снова выдает C2 без открытия карточки и публикует заново только с клавиатуры; в режиме с почтовой фикстурой свежезарегистрированный кандидат с двумя заявленными специализациями и без теста публикуется и видит "Грейд не подтвержден" для каждой. Группа с подменой API показывает подтвержденный Backend рядом с неподтвержденными специализациями, подписи основы и калибровки доказательств, пустые истории, неудачное сохранение с сохранением черновика и отозванный C2. Ни один тест не читает карточку как работодатель, поэтому немедленная потеря доступа скрытого работодателя в браузере не проверяется. diff --git a/frontend/e2e/auth-registration.spec.ts b/frontend/e2e/auth-registration.spec.ts index 66cf8ad..fe054f4 100644 --- a/frontend/e2e/auth-registration.spec.ts +++ b/frontend/e2e/auth-registration.spec.ts @@ -48,6 +48,17 @@ test.describe("registration, email confirmation, and onboarding", () => { return token; } + function codeFromMessage(message: InboxMessage): string { + const content = `${message.text ?? ""}\n${message.html ?? ""}`; + const code = /Код подтверждения: ([0-9]{6})\b/.exec(content)?.[1]; + if (!code) throw new Error("The local registration message had no verification code."); + return code; + } + + function wrongCodeFor(code: string): string { + return code === "000000" ? "000001" : "000000"; + } + async function openVerificationLink(page: Page, token: string): Promise { const target = new URL("/verify-email", process.env.E2E_BASE_URL); target.hash = `token=${token}`; @@ -90,6 +101,56 @@ test.describe("registration, email confirmation, and onboarding", () => { await page.screenshot({ path: screenshotPath, animations: "disabled" }); } + async function registerThroughForm( + page: Page, + scenario: "candidate" | "employer", + email: string, + password: string, + ): Promise { + const scenarioLabel = scenario === "candidate" ? "Кандидат" : "Работодатель"; + await page.goto("/register"); + await expect( + page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }), + ).toBeVisible(); + await expect(page.getByText(/C4/)).toHaveCount(0); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page.getByRole("radio", { name: new RegExp(scenarioLabel) }).check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + await expect( + page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)), + ).toBeVisible(); + } + + async function signInAndResume( + page: Page, + scenario: "candidate" | "employer", + email: string, + password: string, + nextStep: string, + ): Promise { + const noSessionResponse = page.waitForResponse( + (response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current", + ); + await page.goto(scenario === "candidate" ? "/candidate" : "/employer"); + expect((await noSessionResponse).status()).toBe(401); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page.getByRole("button", { name: "Войти" }).click(); + await expect(page.getByRole("heading", { name: nextStep })).toBeVisible(); + + const restoredSessionResponse = page.waitForResponse( + (response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current", + ); + await page.reload(); + expect((await restoredSessionResponse).status()).toBe(200); + await expect(page.getByRole("heading", { name: nextStep })).toBeVisible(); + await checkResponsiveKeyboardFlow(page); + } + async function completeScenario(page: Page, scenario: "candidate" | "employer") { test.skip(!mailFixtureEnabled, "Requires the local mail fixture target."); @@ -113,6 +174,15 @@ test.describe("registration, email confirmation, and onboarding", () => { await expect( page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)), ).toBeVisible(); + await expect(page.getByRole("heading", { name: "Введите код из письма" })).toBeVisible(); + await expect(page.getByLabel("Код из письма", { exact: true })).toBeVisible(); + + // The password is held in memory only: no browser storage keeps it, and + // the stored context has only the address, the scenario, and the flag. + const storedText = await page.evaluate(() => + JSON.stringify({ ...localStorage, ...sessionStorage }), + ); + expect(storedText.includes(password)).toBe(false); const registrationContextIsNonSecret = await page.evaluate(() => { const raw = sessionStorage.getItem("lincodex-registration-context"); if (!raw) return false; @@ -126,17 +196,79 @@ test.describe("registration, email confirmation, and onboarding", () => { }); expect(registrationContextIsNonSecret).toBe(true); + // A reload drops the memory copy, so the step asks for the password again. await page.reload(); await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); - await expect( - page.getByText(new RegExp(`Выбранный сценарий: ${scenarioLabel.toLowerCase()}`)), - ).toBeVisible(); + await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible(); await captureReviewScreenshot(page, scenario, "registration-accepted"); - const originalMessage = await waitForMessage(email); - const originalToken = tokenFromMessage(originalMessage); - await openVerificationLink(page, originalToken); + const message = await waitForMessage(email); + const code = codeFromMessage(message); + await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + await page.getByLabel("Код из письма", { exact: true }).fill(wrongCodeFor(code)); + const rejectedConfirmation = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/identity/email-verifications/code" && + response.request().method() === "POST", + ); + await page.getByRole("button", { name: "Подтвердить код" }).click(); + const rejectedResult = await rejectedConfirmation; + const rejectedProblem = (await rejectedResult.json()) as { code?: string }; + expect(rejectedResult.status()).toBe(400); + expect(rejectedProblem.code).toBe("verification_token_invalid"); + await expect(page.getByRole("alert")).toContainText("Код не подошел"); + await expect(page.getByLabel("Код из письма", { exact: true })).toHaveValue(""); + // Pasted text with a space keeps only the digits, so the code still fits. + const confirmation = page.waitForResponse( + (response) => + new URL(response.url()).pathname === "/api/v1/identity/email-verifications/code" && + response.request().method() === "POST", + ); + await page + .getByLabel("Код из письма", { exact: true }) + .fill(`${code.slice(0, 3)} ${code.slice(3)}`); + await page.getByRole("button", { name: "Подтвердить код" }).click(); + expect((await confirmation).status()).toBe(200); + await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); + await captureReviewScreenshot(page, scenario, "email-confirmed"); + const registrationContextWasCleared = await page.evaluate( + () => sessionStorage.getItem("lincodex-registration-context") === null, + ); + expect(registrationContextWasCleared).toBe(true); + + await signInAndResume(page, scenario, email, password, nextStep); + } + + test("candidate registration confirms with the emailed code and resumes at the saved step", async ({ + page, + }) => { + await completeScenario(page, "candidate"); + }); + + test("employer registration confirms with the emailed code and resumes at the saved step", async ({ + page, + }) => { + await completeScenario(page, "employer"); + }); + + // The link form is the labelled region "Подтвердить адрес"; the code step has + // its own password field with the same label. + function linkPassword(page: Page) { + return page + .getByRole("region", { name: "Подтвердить адрес" }) + .getByLabel("Пароль, выбранный при регистрации"); + } + + test("the link from the same message still confirms the registration", async ({ page }) => { + test.skip(!mailFixtureEnabled, "Requires the local mail fixture target."); + + const email = `auth-link-${crypto.randomUUID()}@example.test`; + const password = "correct horse battery staple 2026"; + await registerThroughForm(page, "candidate", email, password); + + const originalMessage = await waitForMessage(email); + await openVerificationLink(page, tokenFromMessage(originalMessage)); await page.route("**/api/v1/identity/email-verifications", (route) => route.fulfill({ status: 400, @@ -150,19 +282,21 @@ test.describe("registration, email confirmation, and onboarding", () => { }), }), ); - await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + await linkPassword(page).fill(password); await page.getByRole("button", { name: "Подтвердить почту" }).click(); await expect(page.getByRole("alert")).toContainText("Срок действия ссылки истек"); await page.unroute("**/api/v1/identity/email-verifications"); + // An expired link leads to the code step, which asks for the address and + // its own resend. The stand allows one message per second. await page.waitForTimeout(1100); + await page.getByLabel("Электронная почта").fill(email); const resendResponse = page.waitForResponse( (response) => new URL(response.url()).pathname === "/api/v1/identity/email-verification-requests" && response.request().method() === "POST", ); - await page.getByLabel("Адрес для письма").fill(email); - await page.getByRole("button", { name: "Отправить письмо повторно" }).click(); + await page.getByRole("button", { name: "Отправить код повторно" }).click(); expect((await resendResponse).status()).toBe(202); await expect(page.getByText(/^Запрос принят\./)).toBeVisible(); const resentMessage = await waitForMessage(email, originalMessage.id); @@ -173,65 +307,25 @@ test.describe("registration, email confirmation, and onboarding", () => { new URL(response.url()).pathname === "/api/v1/identity/email-verifications" && response.request().method() === "POST", ); - await page.getByLabel("Пароль, выбранный при регистрации").fill("incorrect password test"); + await linkPassword(page).fill("incorrect password test"); await page.getByRole("button", { name: "Подтвердить почту" }).click(); const rejectedResult = await rejectedConfirmation; const rejectedProblem = (await rejectedResult.json()) as { code?: string }; expect(rejectedResult.status()).toBe(400); - expect(rejectedProblem.code === "verification_token_invalid").toBe(true); - const rejectedToken = String(rejectedResult.request().postDataJSON().token ?? ""); - expect(rejectedToken.length > 0).toBe(true); + expect(rejectedProblem.code).toBe("verification_token_invalid"); await expect(page.getByRole("alert")).toContainText("Не удалось подтвердить почту"); - await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible(); - await expect(page.getByLabel("Адрес для письма")).toBeVisible(); - const fragmentAfterRejectedPassword = await page.evaluate(() => window.location.hash === ""); - expect(fragmentAfterRejectedPassword).toBe(true); + await expect(linkPassword(page)).toBeVisible(); const successfulConfirmation = page.waitForResponse( (response) => new URL(response.url()).pathname === "/api/v1/identity/email-verifications" && response.request().method() === "POST", ); - await page.getByLabel("Пароль, выбранный при регистрации").fill(password); + await linkPassword(page).fill(password); await page.getByRole("button", { name: "Подтвердить почту" }).click(); - const retriedToken = String( - (await successfulConfirmation).request().postDataJSON().token ?? "", - ); - expect(retriedToken === rejectedToken).toBe(true); - const fragmentAfterPasswordRetry = await page.evaluate(() => window.location.hash === ""); - expect(fragmentAfterPasswordRetry).toBe(true); + expect((await successfulConfirmation).status()).toBe(200); await expect(page.getByText(/Почта подтверждена/)).toBeVisible(); - await captureReviewScreenshot(page, scenario, "email-confirmed"); - const registrationContextWasCleared = await page.evaluate( - () => sessionStorage.getItem("lincodex-registration-context") === null, - ); - expect(registrationContextWasCleared).toBe(true); - const noSessionResponse = page.waitForResponse( - (response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current", - ); - await page.goto(scenario === "candidate" ? "/candidate" : "/employer"); - expect((await noSessionResponse).status()).toBe(401); - await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); - await page.getByLabel("Электронная почта").fill(email); - await page.getByLabel("Пароль", { exact: true }).fill(password); - await page.getByRole("button", { name: "Войти" }).click(); - await expect(page.getByRole("heading", { name: nextStep })).toBeVisible(); - - const restoredSessionResponse = page.waitForResponse( - (response) => new URL(response.url()).pathname === "/api/v1/identity/sessions/current", - ); - await page.reload(); - expect((await restoredSessionResponse).status()).toBe(200); - await expect(page.getByRole("heading", { name: nextStep })).toBeVisible(); - await checkResponsiveKeyboardFlow(page); - } - - test("candidate registration resumes at the saved candidate step", async ({ page }) => { - await completeScenario(page, "candidate"); - }); - - test("employer registration resumes at the saved company step", async ({ page }) => { - await completeScenario(page, "employer"); + await signInAndResume(page, "candidate", email, password, "Согласия"); }); }); diff --git a/frontend/src/features/confirm-email/ui/confirm-email-form.tsx b/frontend/src/features/confirm-email/ui/confirm-email-form.tsx index 38cca73..25e312d 100644 --- a/frontend/src/features/confirm-email/ui/confirm-email-form.tsx +++ b/frontend/src/features/confirm-email/ui/confirm-email-form.tsx @@ -175,7 +175,7 @@ export function ConfirmEmailForm({

) : (

- В ссылке нет действующего токена. Укажите адрес, чтобы запросить новое письмо. + В ссылке нет действующего токена. Введите адрес, пароль и код из письма ниже.

)} Перейти ко входу diff --git a/frontend/src/features/register-account/ui/register-form.tsx b/frontend/src/features/register-account/ui/register-form.tsx index 91ca2a9..d1afc22 100644 --- a/frontend/src/features/register-account/ui/register-form.tsx +++ b/frontend/src/features/register-account/ui/register-form.tsx @@ -20,7 +20,11 @@ type RegisterFormProps = { initialEmail?: string; initialScenario?: Scenario | ""; onDraftChange?: (draft: RegistrationDraft) => void; - onAccepted: (draft: RegistrationDraft) => void; + /** + * Called after the server accepted the request. The password is passed once, + * for the code step held in memory by the caller; it is never stored here. + */ + onAccepted: (draft: RegistrationDraft, password: string) => void; }; type FieldErrors = { @@ -155,6 +159,7 @@ export function RegisterForm({ consent_c1: { text_version: consent.data.text_version, accepted: true as const }, }; idempotencyKey.current ??= createIdempotencyKey(); + const submittedPassword = password; try { await registration.mutateAsync({ @@ -162,7 +167,7 @@ export function RegisterForm({ headers: { "Idempotency-Key": idempotencyKey.current }, }); setPassword(""); - onAccepted({ email, scenario }); + onAccepted({ email, scenario }, submittedPassword); } catch (error: unknown) { const result = registrationError(error); setFormError(result.message); diff --git a/frontend/src/features/verify-email-code/index.ts b/frontend/src/features/verify-email-code/index.ts new file mode 100644 index 0000000..02ea065 --- /dev/null +++ b/frontend/src/features/verify-email-code/index.ts @@ -0,0 +1 @@ +export { VerificationCodeForm } from "./ui/verification-code-form"; diff --git a/frontend/src/features/verify-email-code/model/verification-code.test.ts b/frontend/src/features/verify-email-code/model/verification-code.test.ts new file mode 100644 index 0000000..bc68ebd --- /dev/null +++ b/frontend/src/features/verify-email-code/model/verification-code.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; +import { + codeConfirmationRefusal, + codeFieldError, + digitsOnly, + emailFieldError, + passwordFieldError, + resendCooldownSeconds, + resendLabel, + resendRefusal, +} from "./verification-code"; + +function apiError(code: string, retryAfterSeconds?: number): Error { + return Object.assign(new Error(code), { code, retryAfterSeconds }); +} + +describe("code input", () => { + it("keeps only ASCII digits and at most six of them, so a pasted group still fits", () => { + expect(digitsOnly("482 915")).toBe("482915"); + expect(digitsOnly("код: 4829-15 и еще 99")).toBe("482915"); + expect(digitsOnly("123")).toBe(""); + expect(digitsOnly("")).toBe(""); + }); + + it("accepts exactly six digits", () => { + expect(codeFieldError("000000")).toBeNull(); + expect(codeFieldError("482915")).toBeNull(); + expect(codeFieldError("48291")).not.toBeNull(); + expect(codeFieldError("4829156")).not.toBeNull(); + expect(codeFieldError("48291a")).not.toBeNull(); + }); +}); + +describe("registration fields", () => { + it("checks the address and the password bounds of the login", () => { + expect(emailFieldError("candidate@example.com")).toBeNull(); + expect(emailFieldError("candidate")).not.toBeNull(); + expect(passwordFieldError("correct horse battery staple")).toBeNull(); + expect(passwordFieldError("")).not.toBeNull(); + expect(passwordFieldError("p".repeat(129))).not.toBeNull(); + expect(passwordFieldError("p".repeat(128))).toBeNull(); + }); +}); + +describe("confirmation refusals", () => { + it("gives every cause of an invalid code the same text and clears the code", () => { + const refusal = codeConfirmationRefusal(apiError("verification_token_invalid")); + expect(refusal.message).toContain("Код не подошел"); + expect(refusal.message).toContain("После пяти неверных попыток"); + expect(refusal.codeRefused).toBe(true); + expect(refusal.retryAfterSeconds).toBeUndefined(); + }); + + it("passes the server wait on a rate limit, and keeps the code for other failures", () => { + expect(codeConfirmationRefusal(apiError("rate_limited", 42))).toMatchObject({ + message: "Слишком много попыток. Подождите и повторите попытку.", + retryAfterSeconds: 42, + }); + expect(codeConfirmationRefusal(apiError("rate_limited")).retryAfterSeconds).toBeUndefined(); + expect(codeConfirmationRefusal(apiError("csrf_check_failed")).codeRefused).toBeUndefined(); + expect(codeConfirmationRefusal(new Error("network")).message).toContain("Проверьте соединение"); + }); + + it("maps a refused resend to its own copy and keeps the server wait", () => { + expect(resendRefusal(apiError("rate_limited", 17))).toEqual({ + message: "Слишком много запросов. Подождите и повторите попытку.", + retryAfterSeconds: 17, + }); + expect(resendRefusal(apiError("unknown")).message).toBe( + "Не удалось отправить код. Повторите попытку.", + ); + }); +}); + +describe("resend cooldown", () => { + it("shows the time left and the plain label once the wait is over", () => { + expect(resendCooldownSeconds).toBe(60); + expect(resendLabel(45)).toBe("Отправить код повторно через 45 с"); + expect(resendLabel(0)).toBe("Отправить код повторно"); + }); +}); diff --git a/frontend/src/features/verify-email-code/model/verification-code.ts b/frontend/src/features/verify-email-code/model/verification-code.ts new file mode 100644 index 0000000..7154b10 --- /dev/null +++ b/frontend/src/features/verify-email-code/model/verification-code.ts @@ -0,0 +1,113 @@ +import { EmailAddress, VerificationCode } from "../../../shared/api/schemas"; + +/** Number of digits in the code of a verification message. */ +export const verificationCodeLength = 6; + +/** + * Wait before a repeated message after one was queued. It matches the + * default minimum interval between two verification messages to one address, + * so the button is not offered when the server would refuse it. + */ +export const resendCooldownSeconds = 60; + +const refusedCodeMessage = + "Код не подошел. Проверьте код и пароль или запросите новый код. После пяти неверных попыток код перестает действовать."; + +/** Keeps the ASCII digits of pasted or typed text, up to the code length. */ +export function digitsOnly(raw: string): string { + return raw.replace(/\D/gu, "").slice(0, verificationCodeLength); +} + +export function codeFieldError(code: string): string | null { + return VerificationCode.safeParse(code).success ? null : "Введите 6 цифр из письма."; +} + +export function emailFieldError(email: string): string | null { + return EmailAddress.safeParse(email).success + ? null + : "Введите корректный адрес электронной почты."; +} + +/** Same bounds as the login password: 1 to 128 code points after NFKC. */ +export function passwordFieldError(password: string): string | null { + const length = Array.from(password.normalize("NFKC")).length; + return length >= 1 && length <= 128 + ? null + : "Введите пароль регистрации длиной от 1 до 128 символов после нормализации."; +} + +export type ApiRefusal = { + message: string; + /** Set when the server asked for a wait with Retry-After. */ + retryAfterSeconds?: number; + /** Set when the code itself is refused, so the field should be cleared. */ + codeRefused?: boolean; +}; + +function errorCode(error: unknown): string { + return error instanceof Error && "code" in error ? String(error.code) : ""; +} + +function retryAfter(error: unknown): number | undefined { + if (error instanceof Error && "retryAfterSeconds" in error) { + const value = error.retryAfterSeconds; + return typeof value === "number" && value > 0 ? value : undefined; + } + return undefined; +} + +/** + * Maps a refused code confirmation to copy. Every cause of + * verification_token_invalid shows the same text, because the server gives + * the same answer for each of them. + */ +export function codeConfirmationRefusal(error: unknown): ApiRefusal { + switch (errorCode(error)) { + case "verification_token_invalid": + return { message: refusedCodeMessage, codeRefused: true }; + case "rate_limited": + return { + message: "Слишком много попыток. Подождите и повторите попытку.", + ...optionalWait(error), + }; + case "validation_failed": + return { + message: "Проверьте введенные данные: код состоит из 6 цифр, адрес и пароль заполнены.", + }; + case "csrf_check_failed": + return { + message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.", + }; + default: + return { message: "Не удалось подтвердить почту. Проверьте соединение и повторите попытку." }; + } +} + +/** Maps a refused request for a new message to copy. */ +export function resendRefusal(error: unknown): ApiRefusal { + switch (errorCode(error)) { + case "rate_limited": + return { + message: "Слишком много запросов. Подождите и повторите попытку.", + ...optionalWait(error), + }; + case "csrf_check_failed": + return { + message: "Не удалось проверить источник запроса. Обновите страницу и повторите попытку.", + }; + default: + return { message: "Не удалось отправить код. Повторите попытку." }; + } +} + +function optionalWait(error: unknown): { retryAfterSeconds?: number } { + const seconds = retryAfter(error); + return seconds === undefined ? {} : { retryAfterSeconds: seconds }; +} + +/** Button label that shows the time left before a new message can be asked for. */ +export function resendLabel(secondsLeft: number): string { + return secondsLeft > 0 + ? `Отправить код повторно через ${secondsLeft} с` + : "Отправить код повторно"; +} diff --git a/frontend/src/features/verify-email-code/ui/verification-code-form.module.css b/frontend/src/features/verify-email-code/ui/verification-code-form.module.css new file mode 100644 index 0000000..45324aa --- /dev/null +++ b/frontend/src/features/verify-email-code/ui/verification-code-form.module.css @@ -0,0 +1,94 @@ +.form { + display: grid; + gap: var(--space-5); + min-width: 0; +} + +.field { + display: grid; + gap: var(--space-2); + min-width: 0; +} + +.label { + font-weight: var(--font-weight-bold); +} + +.input { + width: 100%; + min-height: 2.75rem; + padding: var(--space-2) var(--space-3); + border: var(--line-thin) solid var(--color-border-strong); + border-radius: var(--radius-s); + background: var(--color-surface); +} + +/* The code is the one field the user types from the message, so it is large + and spaced; it still fits a 360 px viewport because it has no fixed width. */ +.code-input { + width: 100%; + max-width: 18rem; + min-height: 3.25rem; + padding: var(--space-2) var(--space-3); + border: var(--line-strong) solid var(--color-border-strong); + border-radius: var(--radius-s); + background: var(--color-surface); + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 1.75rem; + font-variant-numeric: tabular-nums; + letter-spacing: 0.3em; +} + +.input[aria-invalid="true"], +.code-input[aria-invalid="true"] { + border-color: var(--color-danger); +} + +.hint, +.error { + font-size: var(--font-size-s); +} + +.hint { + color: var(--color-text-secondary); +} + +.address { + overflow-wrap: anywhere; +} + +.error, +.alert { + color: var(--color-danger); +} + +.alert { + padding: var(--space-3); + border-left: var(--line-strong) solid var(--color-danger); + background: var(--color-surface); +} + +.actions { + display: flex; + flex-wrap: wrap; + gap: var(--space-3); + align-items: center; +} + +.status { + min-height: 1.5em; + color: var(--color-text-secondary); +} + +.notice { + padding: var(--space-4); + border-left: var(--line-strong) solid var(--color-accent); + background: var(--color-surface); +} + +.resend { + display: grid; + gap: var(--space-3); + padding-top: var(--space-4); + border-top: var(--line-thin) solid var(--color-border-strong); +} diff --git a/frontend/src/features/verify-email-code/ui/verification-code-form.test.tsx b/frontend/src/features/verify-email-code/ui/verification-code-form.test.tsx new file mode 100644 index 0000000..e5d39bd --- /dev/null +++ b/frontend/src/features/verify-email-code/ui/verification-code-form.test.tsx @@ -0,0 +1,74 @@ +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { renderToStaticMarkup } from "react-dom/server"; +import { MemoryRouter } from "react-router-dom"; +import { describe, expect, it } from "vitest"; +import { VerificationCodeForm } from "./verification-code-form"; + +function render(props: Partial[0]> = {}): string { + const queryClient = new QueryClient(); + return renderToStaticMarkup( + + + undefined} {...props} /> + + , + ); +} + +describe("verification code form after registration", () => { + it("asks only for the code when the registration password is held in memory", () => { + const html = render({ + initialEmail: "candidate@example.com", + password: "correct horse battery staple", + messageJustSent: true, + }); + + expect(html).toContain("candidate@example.com"); + expect(html).not.toMatch(/type="password"/); + expect(html).not.toContain("Электронная почта"); + expect(html).not.toContain("correct horse battery staple"); + }); + + it("presents the code input for one-time codes and numeric keyboards", () => { + const html = render({ initialEmail: "candidate@example.com", password: "x" }); + + expect(html).toMatch(/]*id="[^"]*-code"[^>]*>/); + expect(html).toContain('inputMode="numeric"'); + expect(html).toContain('autoComplete="one-time-code"'); + // No maxLength: the browser would cut "482 915" to "482 91" before the + // digits are kept, so the field keeps every character and digitsOnly trims it. + expect(html).not.toContain("maxLength"); + expect(html).toContain("Код из письма"); + expect(html).toContain("Подтвердить код"); + }); + + it("starts the resend cooldown when a message was just queued", () => { + const html = render({ + initialEmail: "candidate@example.com", + password: "x", + messageJustSent: true, + }); + + expect(html).toMatch( + /]*disabled=""[^>]*>Отправить код повторно через 60 с<\/button>/, + ); + }); + + it("offers the resend at once when the step was reopened later", () => { + const html = render({ initialEmail: "candidate@example.com", password: "x" }); + + expect(html).toMatch(/]*>Отправить код повторно<\/button>/); + expect(html).not.toMatch(/Отправить код повторно через/); + }); +}); + +describe("verification code form on the verification page", () => { + it("asks for the address, the password, and the code when nothing is in memory", () => { + const html = render(); + + expect(html).toContain("Электронная почта"); + expect(html).toContain("Пароль, выбранный при регистрации"); + expect(html.match(/type="password"/g)).toHaveLength(1); + expect(html).toContain("Код из письма"); + }); +}); diff --git a/frontend/src/features/verify-email-code/ui/verification-code-form.tsx b/frontend/src/features/verify-email-code/ui/verification-code-form.tsx new file mode 100644 index 0000000..f837cec --- /dev/null +++ b/frontend/src/features/verify-email-code/ui/verification-code-form.tsx @@ -0,0 +1,275 @@ +import { useEffect, useId, useState, type ClipboardEvent, type FormEvent } from "react"; +import { + useConfirmEmailByCode, + useResendEmailVerification, +} from "../../../shared/api/endpoints/identity/identity"; +import { paths } from "../../../shared/config"; +import { Button, ButtonLink } from "../../../shared/ui"; +import { + codeConfirmationRefusal, + codeFieldError, + digitsOnly, + emailFieldError, + passwordFieldError, + resendCooldownSeconds, + resendLabel, + resendRefusal, +} from "../model/verification-code"; +import styles from "./verification-code-form.module.css"; + +type FieldErrors = { + email?: string | undefined; + password?: string | undefined; + code?: string | undefined; +}; + +type VerificationCodeFormProps = { + /** Address of the registration. Typed by the user when the form is opened without it. */ + initialEmail?: string; + /** + * Password of the registration, held in the parent's memory only. When it is + * absent, for example after a page reload, the form asks for it. + */ + password?: string | undefined; + /** A message was queued just now, so a new one waits for the cooldown. */ + messageJustSent?: boolean; + onConfirmed: () => void; +}; + +/** + * Confirms the address with the six-digit code from the verification message. + * The success result and its copy match the link page, so the next step is + * the same: sign in with the password, then continue from the saved step. + */ +export function VerificationCodeForm({ + initialEmail = "", + password: registrationPassword, + messageJustSent = false, + onConfirmed, +}: VerificationCodeFormProps) { + const id = useId(); + const confirm = useConfirmEmailByCode({ mutation: { gcTime: 0 } }); + const resend = useResendEmailVerification({ mutation: { gcTime: 0 } }); + const [email, setEmail] = useState(initialEmail); + const [typedPassword, setTypedPassword] = useState(""); + const [code, setCode] = useState(""); + const [fieldErrors, setFieldErrors] = useState({}); + const [formError, setFormError] = useState(null); + const [confirmed, setConfirmed] = useState(false); + const [secondsLeft, setSecondsLeft] = useState(messageJustSent ? resendCooldownSeconds : 0); + const [resendMessage, setResendMessage] = useState(""); + const asksForPassword = registrationPassword === undefined; + + useEffect(() => { + if (secondsLeft <= 0) return; + const timer = window.setTimeout(() => setSecondsLeft((current) => current - 1), 1000); + return () => window.clearTimeout(timer); + }, [secondsLeft]); + + function handlePaste(event: ClipboardEvent) { + event.preventDefault(); + setCode(digitsOnly(event.clipboardData.getData("text"))); + setFieldErrors((current) => ({ ...current, code: undefined })); + } + + async function submit(event: FormEvent) { + event.preventDefault(); + if (confirm.isPending) return; + + const password = registrationPassword ?? typedPassword; + const errors: FieldErrors = { + email: emailFieldError(email) ?? undefined, + password: asksForPassword ? (passwordFieldError(password) ?? undefined) : undefined, + code: codeFieldError(code) ?? undefined, + }; + setFieldErrors(errors); + setFormError(null); + if (errors.email || errors.password || errors.code) return; + + try { + await confirm.mutateAsync({ data: { email, code, password } }); + setCode(""); + setTypedPassword(""); + setConfirmed(true); + onConfirmed(); + } catch (error: unknown) { + const refusal = codeConfirmationRefusal(error); + setFormError(refusal.message); + if (refusal.codeRefused) setCode(""); + } + } + + async function requestNewCode() { + if (resend.isPending || secondsLeft > 0) return; + const emailError = emailFieldError(email); + if (emailError) { + setFieldErrors((current) => ({ ...current, email: emailError })); + setResendMessage(""); + return; + } + + setResendMessage(""); + try { + await resend.mutateAsync({ data: { email } }); + setSecondsLeft(resendCooldownSeconds); + setResendMessage( + "Запрос принят. Если адрес можно зарегистрировать, новое письмо с кодом придет на почту.", + ); + } catch (error: unknown) { + const refusal = resendRefusal(error); + if (refusal.retryAfterSeconds !== undefined) setSecondsLeft(refusal.retryAfterSeconds); + setResendMessage(refusal.message); + } + } + + if (confirmed) { + return ( +
+
+ Почта подтверждена. Войдите с паролем, который вы выбрали при регистрации. После входа + сервис откроет сохраненный шаг. +
+ Перейти ко входу +
+ ); + } + + const codeErrorId = `${id}-code-error`; + const emailErrorId = `${id}-email-error`; + const passwordErrorId = `${id}-password-error`; + + return ( +
+
void submit(event)} noValidate> + {asksForPassword ? ( + <> +
+ + { + setEmail(event.currentTarget.value); + setFieldErrors((current) => ({ ...current, email: undefined })); + }} + /> + {fieldErrors.email ? ( +

+ {fieldErrors.email} +

+ ) : null} +
+
+ + { + setTypedPassword(event.currentTarget.value); + setFieldErrors((current) => ({ ...current, password: undefined })); + }} + /> + {fieldErrors.password ? ( +

+ {fieldErrors.password} +

+ ) : null} +
+ + ) : ( +

+ Код отправлен на адрес {email}. Введите его, + чтобы подтвердить почту. +

+ )} + +
+ + { + setCode(digitsOnly(event.currentTarget.value)); + setFieldErrors((current) => ({ ...current, code: undefined })); + }} + onPaste={handlePaste} + /> + {fieldErrors.code ? ( +

+ {fieldErrors.code} +

+ ) : ( +

+ Шесть цифр. Код действует 30 минут. +

+ )} +
+ + {formError ? ( +

+ {formError} +

+ ) : null} + +
+ +
+

+ {confirm.isPending ? "Проверяем код..." : ""} +

+
+ +
+

+ Письмо не пришло? Проверьте папку «Спам» или запросите новый код. +

+
+ +
+

+ {resendMessage} +

+
+
+ ); +} diff --git a/frontend/src/pages/auth/ui/register-page.tsx b/frontend/src/pages/auth/ui/register-page.tsx index 4bd8558..0b8dfec 100644 --- a/frontend/src/pages/auth/ui/register-page.tsx +++ b/frontend/src/pages/auth/ui/register-page.tsx @@ -1,6 +1,6 @@ import { useState } from "react"; import { RegisterForm, type RegistrationDraft } from "../../../features/register-account"; -import { ResendVerificationForm } from "../../../features/resend-email-verification"; +import { VerificationCodeForm } from "../../../features/verify-email-code"; import { Button, Page, Section, TextLink } from "../../../shared/ui"; import { paths } from "../../../shared/config"; import { @@ -16,6 +16,11 @@ function scenarioLabel(scenario: RegistrationDraft["scenario"]): string { export function RegisterPage() { const [context, setContext] = useState(readRegistrationContext); + // The registration password lives only in this component's memory and is + // never written to storage. A reload drops it, and the code step then asks + // for it again. + const [registrationPassword, setRegistrationPassword] = useState(); + const [messageJustSent, setMessageJustSent] = useState(false); function saveDraft(draft: RegistrationDraft) { const next = { ...draft, accepted: false }; @@ -23,15 +28,25 @@ export function RegisterPage() { writeRegistrationContext(next); } - function markAccepted(draft: RegistrationDraft) { + function markAccepted(draft: RegistrationDraft, password: string) { const next = { ...draft, accepted: true }; setContext(next); writeRegistrationContext(next); + setRegistrationPassword(password); + setMessageJustSent(true); + } + + function finishConfirmation() { + setRegistrationPassword(undefined); + setMessageJustSent(false); + clearRegistrationContext(); } function startAgain() { clearRegistrationContext(); setContext({ email: "", scenario: "", accepted: false }); + setRegistrationPassword(undefined); + setMessageJustSent(false); } return ( @@ -43,10 +58,17 @@ export function RegisterPage() {

- Если для этого адреса требуется подтверждение, письмо будет отправлено. Выбранный + Если адрес можно зарегистрировать, письмо с кодом и ссылкой придет на него. Выбранный сценарий: {scenarioLabel(context.scenario)}.

- +
+ +
Перейти ко входу