diff --git a/backend/integration_test/notification_restart_test.go b/backend/integration_test/notification_restart_test.go new file mode 100644 index 0000000..23093b1 --- /dev/null +++ b/backend/integration_test/notification_restart_test.go @@ -0,0 +1,222 @@ +//go:build integration + +package integration_test + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/twmb/franz-go/pkg/kgo" + + postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" + "lincodex/backend/internal/adapter/secondary/prometheus" + "lincodex/backend/internal/domain" + "lincodex/backend/internal/port/inbound" + "lincodex/backend/internal/usecase/notification" + "lincodex/backend/internal/worker/eventconsumer" +) + +// noticeConsumers names the Kafka groups of the two notification consumers +// of one deployment. A restarted process keeps its groups; a group that lost +// its offsets is a new name. +type noticeConsumers struct { + inboxGroup string + deliveryGroup string +} + +func newNoticeConsumers() noticeConsumers { + return noticeConsumers{inboxGroup: newConsumerGroup(), deliveryGroup: newConsumerGroup()} +} + +// TestInvitationNoticesSurviveRelayAndConsumerRestarts follows the real send +// of two invitations through the outbox, the relay, Kafka, and the two +// notification consumers that bootstrap registers. The relay dies after the +// broker acknowledged the events and before the mark committed; the backend +// is then restarted, so the same event IDs are published and consumed again; +// finally a consumer group that lost its offsets replays the whole topic. +// Each recipient keeps exactly one internal notification and one mail +// delivery, and the mail worker sends one message to each. +func TestInvitationNoticesSurviveRelayAndConsumerRestarts(t *testing.T) { + env := bootstrap(t, postgresService, kafkaService) + ctx, cancel := context.WithTimeout(t.Context(), productNoticeTimeout) + defer cancel() + fixture := newProductNoticeFixture(ctx, t, env) + recipients := []domain.User{ + fixture.candidate(t, "restart-first@example.test"), + fixture.candidate(t, "restart-second@example.test"), + } + for _, recipient := range recipients { + fixture.invite(t, recipient.ID) + } + // Each send appends invitation.delivered for the inbox and + // notification.mail_requested for the mail, each its own aggregate. + events := readOutboxEvents(ctx, t, fixture.pool) + if len(events) != 2*len(recipients) { + t.Fatalf("outbox holds %d events after %d sends, want %d", len(events), len(recipients), 2*len(recipients)) + } + published := int64(len(events)) + + // One partition keeps the committed offset equal to the number of + // records a consumer has finished. + topic := env.createKafkaTopic(ctx, t, 1) + relays := &relayHarness{ + env: env, pool: fixture.pool, transactor: fixture.transactor, + store: postgresadapter.NewOutboxRelayStore(fixture.pool, relayStoreTimeouts), + } + store := postgresadapter.NewEventConsumerStore(fixture.pool, consumerHandlerTime) + + // The relay produces every event and is killed before its mark commits. + passCtx, killPass := context.WithCancel(ctx) + defer killPass() + dying := relays.newRelay(crashAfterPublish{EventPublisher: relays.newPublisher(t, topic), crash: killPass}) + if result, err := dying.PublishPending(passCtx); !errors.Is(err, context.Canceled) || result.Published != 0 || result.Claimed != len(events) { + t.Fatalf("PublishPending() of the dying relay = %+v, %v; want every event claimed, none marked, and context.Canceled", result, err) + } + assertUnpublished(ctx, t, fixture.pool, len(events)) + + // The consumers of the first process apply the records. + deployment := newNoticeConsumers() + firstRun := prometheus.New() + fixture.runNoticeConsumers(ctx, t, env, store, topic, deployment, firstRun, published) + assertNoticeRecords(t, firstRun, notification.InboxConsumerName, len(recipients), 0) + assertNoticeRecords(t, firstRun, notification.DeliveryConsumerName, len(recipients), 0) + fixture.assertOneNoticePerRecipient(t, recipients) + + // After the restart the relay finds the events unmarked and publishes them + // again under the same event IDs, and the restarted consumers resume + // from their committed offsets. + restarted := relays.newRelay(relays.newPublisher(t, topic)) + if got := relays.publishUntilDrained(ctx, t, restarted); got != len(events) { + t.Fatalf("restarted relay published %d events, want the %d unmarked ones", got, len(events)) + } + assertUnpublished(ctx, t, fixture.pool, 0) + republished := env.consumeKafkaRecords(ctx, t, topic, int(2*published)) + assertSameEventIDs(t, republished, events) + secondRun := prometheus.New() + fixture.runNoticeConsumers(ctx, t, env, store, topic, deployment, secondRun, 2*published) + assertNoticeRecords(t, secondRun, notification.InboxConsumerName, 0, len(recipients)) + assertNoticeRecords(t, secondRun, notification.DeliveryConsumerName, 0, len(recipients)) + fixture.assertOneNoticePerRecipient(t, recipients) + + // Groups that lost their offsets replay the whole topic: every record is + // a duplicate. + replay := prometheus.New() + fixture.runNoticeConsumers(ctx, t, env, store, topic, newNoticeConsumers(), replay, 2*published) + assertNoticeRecords(t, replay, notification.InboxConsumerName, 0, 2*len(recipients)) + assertNoticeRecords(t, replay, notification.DeliveryConsumerName, 0, 2*len(recipients)) + fixture.assertOneNoticePerRecipient(t, recipients) + assertRowCount(ctx, t, fixture.pool, pgx.Identifier{"consumer_dead_letters"}, 0) + + // The mail worker sends one message to each recipient and then idles. + sender := fixture.sender(t, 100, 3000, 0, 0) + for range recipients { + if result := fixture.harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassAccepted { + t.Fatalf("notification pass = %+v, want accepted", result) + } + } + if result := fixture.harness.pass(ctx, t, sender); result.Outcome != inbound.MailPassIdle { + t.Fatalf("pass after every notice was sent = %+v, want idle", result) + } + for _, recipient := range recipients { + if sent := fixture.requestsFor(recipient.Email.Address()); len(sent) != 1 { + t.Fatalf("provider requests to one recipient = %d, want exactly one", len(sent)) + } + } +} + +// runNoticeConsumers runs the inbox and delivery consumers, as bootstrap +// builds them, in the groups of deployment until both committed offset, and +// then stops them as a process shutdown does. +func (fixture *productNoticeFixture) runNoticeConsumers( + ctx context.Context, + t *testing.T, + env *testEnvironment, + store *postgresadapter.EventConsumerStore, + topic string, + deployment noticeConsumers, + metrics *prometheus.Metrics, + offset int64, +) { + t.Helper() + logger := slog.New(slog.DiscardHandler) + handlers := map[string]inbound.EventHandler{ + deployment.inboxGroup: notification.NewInboxHandler(logger, false), + deployment.deliveryGroup: notification.NewDeliveryHandler( + notification.NewTemplateRenderer(fixture.renderer), fixture.account, fixture.clock.Now, logger), + } + sources := &consumerHarness{env: env} + stops := make([]func(), 0, len(handlers)) + for group, handler := range handlers { + source, closeSource := sources.newSource(t, topic, group) + consumer, err := eventconsumer.New(handler, source, store, metrics, logger, consumerTestSettings(consumerGrace)) + if err != nil { + t.Fatalf("eventconsumer.New(%s) error = %v", handler.ConsumerName(), err) + } + stopRun := runConsumer(ctx, t, consumer) + stops = append(stops, func() { + stopRun() + closeSource() + }) + } + for group := range handlers { + env.waitForCommittedOffsets(ctx, t, group, topic, map[int32]int64{0: offset}) + } + for _, stop := range stops { + stop() + } +} + +// assertOneNoticePerRecipient counts the internal notifications and the mail +// deliveries of each recipient. +func (fixture *productNoticeFixture) assertOneNoticePerRecipient(t *testing.T, recipients []domain.User) { + t.Helper() + for _, recipient := range recipients { + var inbox, deliveries int + if err := fixture.pool.QueryRow(fixture.ctx, ` + SELECT + (SELECT count(*) FROM notification_inbox_events WHERE recipient_user_id = $1), + (SELECT count(*) FROM deliveries WHERE recipient_user_id = $1 AND kind = 'notification')`, + recipient.ID).Scan(&inbox, &deliveries); err != nil { + t.Fatalf("count the notices of a recipient: %v", err) + } + if inbox != 1 || deliveries != 1 { + t.Fatalf("a recipient has %d inbox rows and %d notification deliveries, want one of each", inbox, deliveries) + } + } +} + +// assertNoticeRecords checks how many records a consumer applied and how many +// it recognized as duplicates. +func assertNoticeRecords(t *testing.T, metrics *prometheus.Metrics, consumer string, applied, duplicate int) { + t.Helper() + scraped := scrapeMetrics(metrics) + for outcome, want := range map[string]int{eventconsumer.OutcomeApplied: applied, eventconsumer.OutcomeDuplicate: duplicate} { + series := fmt.Sprintf(`lincodex_event_consumer_records_total{consumer=%q,outcome=%q} %d`, consumer, outcome, want) + if !strings.Contains(scraped, series+"\n") { + t.Fatalf("metrics lack %s", series) + } + } +} + +// assertSameEventIDs checks that the topic holds every outbox event exactly +// twice under its original event ID and nothing else. +func assertSameEventIDs(t *testing.T, records []*kgo.Record, events []storedEvent) { + t.Helper() + counts := make(map[string]int, len(events)) + for _, record := range records { + counts[headerValue(record, "event_id")]++ + } + for _, event := range events { + if counts[event.eventID.String()] != 2 { + t.Fatalf("event %s is on the topic %d times, want twice", event.eventID, counts[event.eventID.String()]) + } + } + if len(counts) != len(events) { + t.Fatalf("the topic holds %d event IDs, want the %d of the outbox", len(counts), len(events)) + } +} diff --git a/docs/en/TESTING.md b/docs/en/TESTING.md index 3462098..575dd15 100644 --- a/docs/en/TESTING.md +++ b/docs/en/TESTING.md @@ -73,7 +73,9 @@ Playwright receives `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-fixture:8 The current suite (`frontend/e2e/smoke.spec.ts`) checks that the SPA serves `/` with `lang="ru"` and its heading, that `/status` shows the technical page with a live API, that `/api/v1/healthz` returns 200 `{"status":"ok"}` through the frontend proxy, that an unknown SPA route shows the not-found page, and that `/api/v1/missing` returns 404 `application/problem+json` with code `not_found`. It needs no data. Business tests use synthetic data in each fresh stack: registration through the public API and the separately documented test fixture for consent scopes. No real data are used. -The ordinary technical suite does not cover candidate or employer workflows, sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, or screen readers. Its stubbed checks of the minimal path states, focus, and overflow are described in [Minimal path states and accessibility](#minimal-path-states-and-accessibility). CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. +`frontend/e2e/mail-unavailable.spec.ts` runs only in the ordinary `test-e2e`, whose stand sets `EMAIL_PROVIDER=disabled`, and skips when `E2E_MAIL_FIXTURE=1`. On the real backend it registers a candidate (202 `accepted`) and checks that the step waits for the message ("Запрос принят", "Письмо может прийти не сразу") and never says that a message was sent or delivered. A guessed code and a forged link answer 400 `verification_token_invalid`; the correct password answers 403 `email_not_verified` with the message in the form; afterwards `GET /api/v1/identity/sessions/current` and `GET /api/v1/me/profile` answer 401 and `/candidate` shows the sign-in page. The browser cannot see the delivery row: that it stays `pending` without an attempt while the transport is disabled is checked by the `EMAIL_PROVIDER=disabled` subtest of `TestServiceMailSending`. + +The ordinary technical suite does not cover candidate or employer workflows beyond the unconfirmed registration of `mail-unavailable.spec.ts`, a successful sign-in, mail delivery, dependency failures (deployment smoke covers those), browsers other than desktop Chromium, or screen readers. Its stubbed checks of the minimal path states, focus, and overflow are described in [Minimal path states and accessibility](#minimal-path-states-and-accessibility). CI runs the suite in the `e2e` job after `backend`, `frontend`, and `infrastructure` pass: `make -C frontend install`, then `make -C deploy test-e2e`. The job needs no repository secrets or root `.env`; each run uses its own generated env file and fresh stand. On failure CI uploads the `e2e-diagnostics-attempt-` artifact with `report/`, `results/` (traces and screenshots), and `stand.log` for 14 days. Hidden files and the env file are not uploaded. The `e2e` result is part of the required aggregate. 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. @@ -314,6 +316,8 @@ Unit tests (`make -C backend test`) cover: These tests prove the rights rules and the lane mechanics against the local fixture. They do not decide the product questions listed under [Sending product notifications](ARCHITECTURE.md#sending-product-notifications), such as whether a withdrawn publication should cancel a pending notice. +`TestInvitationNoticesSurviveRelayAndConsumerRestarts` in `backend/integration_test/notification_restart_test.go` uses `bootstrap(t, postgresService, kafkaService)` with the same fixture and follows two real invitation sends through the outbox, the relay, a one-partition Kafka topic, and the `notification_inbox` and `notification_delivery` consumers built as bootstrap builds them. The relay produces all four events and is killed before its mark commits; the consumers apply them. A restarted relay then publishes the same event IDs again, and restarted consumers in the same groups count each repeated record as a duplicate; consumers in new groups, as after lost offsets, replay the whole topic as duplicates too. After each stage every recipient has exactly one row in `notification_inbox_events` and one notification delivery, and no dead letter exists; the notification lane then sends one message to each recipient. + ## Scheduled job tests Unit tests (`make -C backend test`) cover the job runtime with an in-memory store that applies the claim, lease guard, and release rules of the PostgreSQL store and a fake clock from `backend/pkg/testutil/` (`internal/worker/jobrunner/`): only due jobs of registered kinds run, in due order, and a job due in two days runs exactly when the clock reaches it; a failing job is retried after the backoff by the clock, is not claimed again before it, and is dead after the last attempt with an error log and metrics; `ErrJobRejected` and a panic end a job after one attempt without logging the panic value; a handler that outlives its lease fails as `timeout`; a job reclaimed by another worker before it starts is skipped without calling the handler; a job whose last started lease expired becomes dead without running; a slow first job of a batch neither spends the next job's single attempt nor lets it die, and another worker runs a job that a busy worker claimed but did not start, on the same attempt; a database failure outside the handler releases the job and the rest of the batch without counting attempts; failed claims back off instead of looping; at shutdown the job in progress finishes within the grace, a job that outlasts it is canceled and released without an effect or a counted attempt, and claimed jobs that did not start are released; a panic during shutdown still makes the job dead; and the backlog of all kinds is reported. Further unit tests cover the job rules (`internal/domain/`: kind, key, flat payload, size limit, UTC microsecond due time), the settings (`config/`), the counters and gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), and in `internal/bootstrap/` the skip cases with their log lines, the empty kind registry, a duplicate kind, and an application that runs the worker against an unreachable database and still stops. diff --git a/docs/ru/TESTING.md b/docs/ru/TESTING.md index fdf4221..e59a8bf 100644 --- a/docs/ru/TESTING.md +++ b/docs/ru/TESTING.md @@ -73,7 +73,9 @@ Playwright получает `E2E_MAIL_FIXTURE=1`, `E2E_MAILBOX_URL=http://mail-f Текущий набор (`frontend/e2e/smoke.spec.ts`) проверяет, что SPA отдает `/` с `lang="ru"` и заголовком, что `/status` показывает техническую страницу с живым API, что `/api/v1/healthz` через прокси frontend возвращает 200 `{"status":"ok"}`, что неизвестный маршрут SPA показывает страницу "не найдено" и что `/api/v1/missing` возвращает 404 `application/problem+json` с кодом `not_found`. Данные ему не нужны. Бизнес-тесты используют синтетические данные в свежем стеке каждого прогона: регистрацию через публичный API и отдельно описанный тестовый fixture для scope согласий. Реальные данные не используются. -Обычный технический набор не проверяет сценарии кандидата и работодателя, вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium и программы чтения с экрана. Его проверки заглушками основного пути (состояния, фокус и переполнение) описаны в разделе [Состояния и доступность основного пути](#состояния-и-доступность-основного-пути). CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. +`frontend/e2e/mail-unavailable.spec.ts` выполняется только в обычном `test-e2e`, стенд которого задает `EMAIL_PROVIDER=disabled`, и пропускается при `E2E_MAIL_FIXTURE=1`. На настоящем backend он регистрирует кандидата (202 `accepted`) и проверяет, что шаг ждет письмо ("Запрос принят", "Письмо может прийти не сразу") и нигде не говорит, что письмо отправлено или доставлено. Подобранный код и поддельная ссылка получают 400 `verification_token_invalid`; верный пароль получает 403 `email_not_verified` с сообщением в форме; после этого `GET /api/v1/identity/sessions/current` и `GET /api/v1/me/profile` отвечают 401, а `/candidate` показывает страницу входа. Строку доставки браузер не видит: то, что она остается `pending` без попыток, пока транспорт выключен, проверяет подтест `EMAIL_PROVIDER=disabled` в `TestServiceMailSending`. + +Обычный технический набор не проверяет сценарии кандидата и работодателя, кроме неподтвержденной регистрации в `mail-unavailable.spec.ts`, успешный вход, доставку почты, отказы зависимостей (их проверяет deployment smoke), браузеры кроме desktop Chromium и программы чтения с экрана. Его проверки заглушками основного пути (состояния, фокус и переполнение) описаны в разделе [Состояния и доступность основного пути](#состояния-и-доступность-основного-пути). CI запускает набор в job `e2e` после успешных `backend`, `frontend` и `infrastructure`: `make -C frontend install`, затем `make -C deploy test-e2e`. Секреты репозитория и корневой `.env` не нужны; каждый прогон использует свой сгенерированный env-файл и свежий стенд. При ошибке CI загружает артефакт `e2e-diagnostics-attempt-` с `report/`, `results/` (трассы и снимки экрана) и `stand.log` на 14 дней. Скрытые файлы и env-файл не загружаются. Результат `e2e` входит в обязательный aggregate. Режим регистрации дополнительно запускает `frontend/e2e/auth-registration.spec.ts`: регистрацию кандидата и работодателя с видимым C1, реальную локальную повторную отправку с получением нового письма, замену ссылки подтверждения в той же вкладке, повтор после неверного пароля, подтверждение без автоматического входа, вход и восстановление серверного шага после обновления. Проверяются фокус клавиатуры и отсутствие переполнения на 360, 768 и 1280 px. Отображение просроченной ссылки использует управляемый problem-ответ; реальное истечение токена проверяют backend integration tests. Только изолированный overlay задает `VERIFICATION_MAIL_MIN_INTERVAL=1s`; обычная среда и выпуск сохраняют свой настроенный интервал. Для auth-тестов отключены трассы, снимки при ошибках и видео; явные снимки для проверки показывают состояния без токенов и синтетические адреса. Внешняя почта и рабочий edge-путь не проверялись. @@ -314,6 +316,8 @@ Unit-тесты (`make -C backend test`) покрывают: Эти тесты доказывают правила прав и механику полосы на локальной фикстуре. Они не решают продуктовые вопросы из раздела [Отправка продуктовых уведомлений](ARCHITECTURE.md#отправка-продуктовых-уведомлений), например, должна ли отозванная публикация отменять ожидающее уведомление. +`TestInvitationNoticesSurviveRelayAndConsumerRestarts` в `backend/integration_test/notification_restart_test.go` использует `bootstrap(t, postgresService, kafkaService)` с той же фикстурой и проводит две настоящие отправки приглашений через outbox, relay, топик Kafka с одной партицией и потребители `notification_inbox` и `notification_delivery`, собранные так же, как в bootstrap. Relay публикует все четыре события и погибает до фиксации отметки; потребители их применяют. Затем перезапущенный relay публикует те же event ID повторно, и перезапущенные потребители в тех же группах считают каждую повторную запись дубликатом; потребители в новых группах, как после потери offset, тоже перечитывают весь топик как дубликаты. После каждого этапа у каждого получателя ровно одна строка в `notification_inbox_events` и одна доставка уведомления, dead letter нет; после этого полоса уведомлений отправляет каждому получателю одно письмо. + ## Тесты заданий по сроку Unit-тесты (`make -C backend test`) проверяют runtime заданий с хранилищем в памяти, которое повторяет правила захвата, проверки lease и освобождения хранилища PostgreSQL, и с fake clock из `backend/pkg/testutil/` (`internal/worker/jobrunner/`): выполняются только наступившие задания зарегистрированных видов в порядке срока, а задание со сроком через два дня выполняется ровно тогда, когда часы его достигают; неудачное задание повторяется после backoff по часам, не захватывается раньше и после последней попытки становится dead с записью в журнал уровня error и метриками; `ErrJobRejected` и panic завершают задание после одной попытки, а значение panic не попадает в журнал; обработчик, переживший свой lease, падает как `timeout`; задание, которое другой worker захватил до начала, пропускается без вызова обработчика; задание с истекшим lease последней начатой попытки становится dead без выполнения; медленное первое задание пачки не тратит единственную попытку следующего и не убивает его, а другой worker выполняет задание, которое занятый worker захватил, но не начал, на той же попытке; сбой базы данных вне обработчика освобождает задание и остаток пачки без учета попыток; неудачные захваты ждут backoff, а не крутятся в цикле; при остановке задание в работе завершается внутри grace, задание, которое его переживает, отменяется и освобождается без эффекта и без учтенной попытки, а захваченные, но не начатые задания освобождаются; panic во время остановки все равно делает задание dead; backlog всех видов попадает в метрики. Остальные unit-тесты покрывают правила задания (`internal/domain/`: вид, ключ, плоский payload, лимит размера, срок в UTC с точностью до микросекунд), настройки (`config/`), счетчики и gauges (`internal/adapter/secondary/prometheus/`), `FakeClock` (`pkg/testutil/`), а в `internal/bootstrap/` - случаи без запуска с их строками журнала, пустой реестр видов, повторный вид и приложение, которое запускает worker против недоступной базы и все равно останавливается. diff --git a/frontend/e2e/mail-unavailable.spec.ts b/frontend/e2e/mail-unavailable.spec.ts new file mode 100644 index 0000000..b477c1a --- /dev/null +++ b/frontend/e2e/mail-unavailable.spec.ts @@ -0,0 +1,85 @@ +import { expect, test, type Page, type Response } from "@playwright/test"; + +// The ordinary E2E stand runs with EMAIL_PROVIDER=disabled, so no +// verification message is ever delivered. Registration on the real backend +// must then wait for the message without claiming that it went out, and the +// unconfirmed account must not sign in, read its cabinet, or be confirmed by +// a guessed code or a forged link. The mail-fixture stand delivers mail, so +// the spec does not run there. +const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1"; + +test.use({ trace: "off", screenshot: "off", video: "off" }); + +function apiResponse(page: Page, method: string, path: string): Promise { + return page.waitForResponse( + (response) => + response.request().method() === method && new URL(response.url()).pathname === path, + ); +} + +async function problemCode(response: Response): Promise { + return ((await response.json()) as { code?: string }).code; +} + +test.describe("registration while the mail channel is unavailable", () => { + test.skip(mailFixtureEnabled, "Runs on the stand whose mail provider is disabled."); + + test("waits for the message and keeps the unconfirmed account locked", async ({ page }) => { + const email = `mail-off-${crypto.randomUUID()}@example.test`; + const password = "correct horse battery staple 2026"; + + await page.goto("/register"); + await page.getByLabel("Электронная почта").fill(email); + await page.getByLabel("Пароль", { exact: true }).fill(password); + await page.getByRole("radio", { name: /Кандидат/ }).check(); + await page.getByRole("checkbox", { name: /принимаю его/ }).check(); + const registration = apiResponse(page, "POST", "/api/v1/identity/registrations"); + await page.getByRole("button", { name: "Создать аккаунт" }).click(); + const accepted = await registration; + expect(accepted.status()).toBe(202); + expect(await accepted.json()).toEqual({ status: "accepted" }); + + // The step waits for the message and never says it was sent or delivered. + await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible(); + await expect(page.getByText(/письмо с кодом и ссылкой придет на него/)).toBeVisible(); + await expect(page.getByText(/Письмо может прийти не сразу/)).toBeVisible(); + expect(await page.locator("main").innerText()).not.toMatch(/отправлен|доставлен/i); + + // A guessed code does not confirm the address. + await page.getByLabel("Код из письма", { exact: true }).fill("000000"); + const guessed = apiResponse(page, "POST", "/api/v1/identity/email-verifications/code"); + await page.getByRole("button", { name: "Подтвердить код" }).click(); + const guessedResult = await guessed; + expect(guessedResult.status()).toBe(400); + expect(await problemCode(guessedResult)).toBe("verification_token_invalid"); + await expect(page.getByRole("alert")).toContainText("Код не подошел"); + + // Neither does a forged link. + await page.goto(`/verify-email#token=${"A".repeat(43)}`); + const linkForm = page.getByRole("region", { name: "Подтвердить адрес" }); + await linkForm.getByLabel("Пароль, выбранный при регистрации").fill(password); + const forged = apiResponse(page, "POST", "/api/v1/identity/email-verifications"); + await linkForm.getByRole("button", { name: "Подтвердить почту" }).click(); + const forgedResult = await forged; + expect(forgedResult.status()).toBe(400); + expect(await problemCode(forgedResult)).toBe("verification_token_invalid"); + await expect(linkForm.getByRole("alert")).toContainText("Не удалось подтвердить почту"); + + // The correct password does not open a session while the address waits. + await page.goto("/login"); + const signIn = page.getByRole("region", { name: "Войти в аккаунт" }); + await signIn.getByLabel("Электронная почта").fill(email); + await signIn.getByLabel("Пароль", { exact: true }).fill(password); + const login = apiResponse(page, "POST", "/api/v1/identity/sessions"); + await signIn.getByRole("button", { name: "Войти" }).click(); + const loginResult = await login; + expect(loginResult.status()).toBe(403); + expect(await problemCode(loginResult)).toBe("email_not_verified"); + await expect(signIn.getByRole("alert")).toContainText("Почта не подтверждена"); + + expect((await page.request.get("/api/v1/identity/sessions/current")).status()).toBe(401); + expect((await page.request.get("/api/v1/me/profile")).status()).toBe(401); + await page.goto("/candidate"); + await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible(); + }); +}); 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 index e5d39bd..1e4a5c9 100644 --- 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 @@ -29,6 +29,21 @@ describe("verification code form after registration", () => { expect(html).not.toContain("correct horse battery staple"); }); + it("waits for the message instead of claiming it was sent", () => { + // The registration answer is neutral and mail is delivered later, or not + // at all while the mail channel is unavailable, so the form cannot know + // that a code went out. + const html = render({ + initialEmail: "candidate@example.com", + password: "correct horse battery staple", + messageJustSent: true, + }); + + expect(html).not.toMatch(/отправлен|доставлен/i); + expect(html).toContain("может прийти не сразу"); + expect(html).toContain("candidate@example.com"); + }); + it("presents the code input for one-time codes and numeric keyboards", () => { const html = render({ initialEmail: "candidate@example.com", password: "x" }); 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 index f837cec..0089fc8 100644 --- a/frontend/src/features/verify-email-code/ui/verification-code-form.tsx +++ b/frontend/src/features/verify-email-code/ui/verification-code-form.tsx @@ -197,9 +197,12 @@ export function VerificationCodeForm({ ) : ( + // The server answers registration neutrally and delivers mail later, + // so the form never claims that the code was sent.

- Код отправлен на адрес {email}. Введите его, - чтобы подтвердить почту. + Если адрес можно зарегистрировать, код придет на{" "} + {email}. Письмо может прийти не сразу. + Введите код из него, чтобы подтвердить почту.

)}