feat(identity): confirm registration email atomically

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 09:12:15 +03:00
1 parent 8e7ce8d71c
commit fade4e76e4
75 files changed
+4188 -403

No files matched your search

+5 -5
View File
@@ -49,15 +49,15 @@ The repository contains a verifiable technical scaffold, not a product. Values b
What exists now:
- Health and readiness routes. Nginx answers `GET /healthz` itself and proxies only `/api/` to Go (deploy/nginx/conf.d/app.conf). Go serves `GET /healthz` (`ok`) and `GET /readyz` (`ready` or 503 `not_ready` after checking PostgreSQL, Redis, and SeaweedFS) on its internal port 8080 outside the OpenAPI contract, plus `GET /api/v1/healthz` from api/core/routes/healthz.yml through the ogen handler (backend/internal/adapter/primary/http). The Go metrics listener uses port 9090 (`METRICS_ADDR`) and Prometheus scrapes `/metrics`. ML serves `GET /healthz`, `GET /readyz` (always 503 `not_ready` because no model is connected), and `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh checks Nginx `/healthz`, `/api/v1/healthz`, Go `/readyz` from inside the Compose network, a 404 for an unknown API route, and that the backend started with `EMAIL_PROVIDER=disabled`; it does not start ML or send mail.
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and the `identity.Credentials` password check exist and are tested but are not wired into bootstrap. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but nothing sends notifications yet. With `resend` the backend runs a sending worker for service identity mail (verification and password reset, bound to their tokens, checked before the send, with a quota gate and a stable idempotency key); no account flow creates such mail yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
- Adapters: PostgreSQL through pgxpool with a generated `SELECT 1` query, a goose migration runner applied at startup, a transactor with the transactional outbox writer, sqlc-backed identity repositories for accounts, email tokens, and sessions, and the versioned policy repository with the demo policy seed at startup; Redis through go-cachekit, and SeaweedFS through the S3 API. The Argon2id password hasher and `identity.Credentials` are wired for registration and email confirmation. A generated Go client for the ML contract exists but is not wired into bootstrap.
- Mail: the outbound `MailSender` port, the `disabled` and `resend` transports, and the `EMAIL_PROVIDER` selection in bootstrap; `smtp` stops startup after its settings are validated. Product notification requests (`mail_requests`) are turned into deliveries (`deliveries`, `delivery_attempts`) by the `notification_delivery` consumer, but notification sending is not implemented. With `resend`, the backend runs a worker for identity service mail: registration and resend queue verification messages bound to their tokens; the worker checks the token and account before sending and uses a quota gate and stable idempotency key. Password reset is not implemented yet. See [DEPLOY.md](DEPLOY.md#mail) and [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries).
- OpenAPI contracts api/core/ and api/ml/ with schema merge, bundles, lint, and generation for Go (ogen), TypeScript (Orval), and Python (datamodel-code-generator). The SPA has an interface scaffold with placeholder screens, a generated API client, and MSW handlers.
- Compose projects: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`), and monitoring (`docker-compose.monitoring.yml`).
- Kafka: one KRaft node in the core Compose project with an internal-only listener, a named volume, a health check, and a memory limit. The backend runs the outbox relay, which creates the `lincodex.domain.events` topic and publishes committed outbox events to it through a franz-go producer; see [Outbox relay](#outbox-relay). Readiness does not check Kafka. The event consumer runtime runs one product handler, the mail delivery consumer, and no product flow emits its event yet; see [Event consumers](#event-consumers).
- CI jobs in .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix of two shards), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (Playwright suite on an isolated stand), and the required `aggregate` result, which fails when any of them fails, is cancelled, or is skipped. See [TESTING.md](TESTING.md) for sharding and the browser suite.
- Observability: Prometheus, Loki, Alloy, Grafana with provisioned datasources and dashboards, and PostgreSQL, Redis, and node exporters. The React app does not send telemetry yet.
Not implemented yet: registration and login (their contract is declared; the operations answer 501 or 401), consents, profiles, the questionnaire and assessment, the company cabinet, needs and matching, invitations and contacts, the SMTP transport and the worker that sends stored deliveries, product event producers, notifications, support, and an end-to-end business suite. backend/db/migrations/ contains the outbox table with its relay index, the identity storage tables (`users`, `email_tokens`, `sessions`), the `policy_versions` table, the event consumer tables (`consumer_processed_events`, `consumer_dead_letters`), the mail delivery tables (`deliveries`, `delivery_attempts`), the mail quota tables (`mail_quota_usage`, `mail_quota_reservations`), and the scheduled job table (`scheduled_jobs`, with no product job kind registered yet) and no other business schema; no product rule reads the policy yet; registration, verification, and session behavior on top of that storage comes in later tasks, product usecase and adapter directories other than the password hashing and policy pieces contain only placeholders, and `make -C deploy test-e2e` runs only a technical Playwright smoke of the SPA, API health, and error routes on a throwaway stack, not a business flow (see [TESTING.md](TESTING.md#browser-e2e-suite)). The target design is in [ARCHITECTURE.md](ARCHITECTURE.md).
The backend API implements registration, verification resend, and email confirmation. Frontend registration and confirmation screens, as well as login, remain placeholders. Other business flows, including HTTP consent management, profiles, the questionnaire and assessment, the company cabinet, needs, matching, invitations, contacts, product notifications, and support, are not implemented. The worker sends identity service mail through Resend; SMTP and product notification delivery are not implemented. `make -C deploy test-e2e` checks the SPA shell, API health, and error routes on a disposable stack, but not registration or email confirmation (see [TESTING.md](TESTING.md#browser-e2e-suite)).
## Install and work loop
@@ -88,7 +88,7 @@ Security tools have a separate install and work loop: `make -C security install`
The planned session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict` (see [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). The local stack serves plain HTTP. Chromium and Firefox treat `http://localhost` and `http://127.0.0.1` as secure contexts and keep a `Secure` cookie there; WebKit and Safari may reject it. Use Chromium or Firefox for local sign-in, or put a local TLS proxy in front. The project adds no flag that drops `Secure` or the `__Host-` prefix, so the local cookie never differs from production.
Planned Origin rule: every unsafe request (POST, PUT, PATCH, DELETE), including public ones such as login, must carry an `Origin` from an allowlist in the backend configuration, for example the Nginx origin and the Vite dev origin. The server does not compare `Origin` with `Host`. An unsafe request without `Origin` or with another value answers 403 `csrf_check_failed`.
`ConfirmEmail` requires Origin to match `APP_PUBLIC_URL` exactly; a missing Origin, the literal value `null`, or any other value answers 403 `csrf_check_failed`. A broader Origin check for other unsafe requests remains part of the session flow and is not implemented. The server does not use Host to derive an allowed Origin.
## Layout
@@ -165,7 +165,7 @@ The targets run `backend/cmd/migrate` with the same runner, lock, and timeouts a
### Identity storage
Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, and `sessions`; the queries are in `backend/db/queries/identity.sql`. The `outbound.UserRepository`, `EmailTokenRepository`, and `SessionRepository` ports are available through `UnitOfWork` inside `Transactor.WithinTransaction` and through `postgres.IdentityStore` outside a transaction. Nothing in bootstrap or the HTTP handlers uses them yet; registration, verification, login, and the session principal come in later tasks.
Migration `00002_create_identity_tables.sql` creates `users`, `email_tokens`, and `sessions`; the queries are in `backend/db/queries/identity.sql`. Migration 00014 adds the password hash, scenario, and onboarding step for each registration to its token. Migration 00016 binds registration C1 to the account registration version and backfills existing records without using live tokens. The identity ports are used by registration, verification resend, and email confirmation; login and the session principal are not implemented.
The database never receives a password, a raw email token, or a raw session token. Repositories take a `domain.PasswordHash` (an Argon2id v19 PHC string) and a `domain.SecretTokenHash` (the SHA-256 of a `domain.SecretToken`). Email addresses are ASCII only for now; IDN and SMTPUTF8 support is future work that needs IDNA ToASCII for the domain. `SecretToken`, `PasswordHash`, and `EmailAddress` redact themselves in `fmt` and `slog` output; `SecretToken.Reveal` and `EmailAddress.Address` return the real values where they are needed. Every stored time comes from the application clock that the caller passes, and PostgreSQL keeps microseconds. A deadlock or serialization failure is reported as `outbound.ErrTransactionConflict`, and the caller may retry the whole operation. The schema and its decisions are described in [ARCHITECTURE.md](ARCHITECTURE.md#identity-storage).