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

+25 -24
View File
@@ -6,7 +6,7 @@ This document separates the target product architecture from the technical scaff
The repository contains a Go HTTP service with PostgreSQL, Redis, and SeaweedFS checks, cache and S3 storage adapters, a React interface scaffold with public pages and two cabinet shells of placeholder screens, a separate Python ML service with health and readiness routes, two OpenAPI contracts, code generation, Compose files, and monitoring configuration. The public API health route is under /api/v1/healthz. The web container uses /healthz. The internal Go /readyz checks PostgreSQL, Redis, and the SeaweedFS bucket. ML uses /healthz and /readyz; readiness returns 503 while inference is unavailable. Go exposes the standard /metrics endpoint on an internal port.
This is an operational scaffold. It has no registration, roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, or FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
Registration and email confirmation work through the backend API. Frontend registration and confirmation screens remain placeholders; login and the other listed product workflows are not implemented: roles, profiles, assessments, grades, candidate search, invitations, resume processing, PDF generation, and FSP integration. ML does not return invented results. Health checks and the technical smoke do not verify a product workflow.
See [development](DEVELOPMENT.md), [deployment](DEPLOY.md), and [testing](TESTING.md) for source layout, commands, and current check coverage.
@@ -56,7 +56,7 @@ The MVP does not add a separate vector database, Kubernetes, or a search microse
Implemented. The frontend Nginx is the only public HTTP entry. It serves the SPA, proxies `/api/v1/` to Go, and proxies the restricted `/telemetry`; every other path, including `/metrics`, `/readyz`, and administration paths of other services, is refused with 404. Security headers, a strict same-origin CSP, a 1 MB default body limit that answers 413 in the contract's problem format, and coarse per-client `limit_req`/`limit_conn` (429 with `Retry-After`) are set there; the limits are far above normal use and do not replace the domain quotas, which stay in the backend. The details and the checks are in [DEPLOY.md](DEPLOY.md#public-perimeter-and-client-address).
The client address is derived only through trusted proxies. The edge replaces `X-Forwarded-For`; the app Nginx trusts the edge tunnel address and passes the backend one resolved entry; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS` (by default only the pinned frontend container address) and reads it from the right, so an entry a client puts to the left of the first untrusted hop never counts. Usecases and handlers that need the address for a limiter read it with `middleware.ClientAddr(ctx)` and key the limiter with `middleware.LimiterKey` (IPv6 reduced to /64). The address is never logged or stored beyond the limiter window; the request log and metrics have no field for it. The first consumer is the registration and resend limits (see Registration and verification resend); the router mounts `ClientIP`.
The client address is derived only through trusted proxies. The edge replaces `X-Forwarded-For`; the app Nginx trusts the edge tunnel address and passes the backend one resolved entry; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) trusts `X-Forwarded-For` only from `TRUSTED_PROXY_CIDRS` (by default only the pinned frontend container address) and reads it from the right, so an entry a client puts to the left of the first untrusted hop never counts. Usecases and handlers that need the address for a limiter read it with `middleware.ClientAddr(ctx)` and key the limiter with `middleware.LimiterKey` (IPv6 reduced to /64). The address is never logged or stored beyond the limiter window; the request log and metrics have no field for it. Registration, resend, and confirmation use client-address limits (see Registration, email verification, and resend); the router mounts `ClientIP`.
### Private file storage
@@ -234,7 +234,7 @@ Every `rejected` or `unknown` answer with a known error name sets `ProviderCode`
### Mail deliveries
Implemented: the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented; see [Mail quotas](#mail-quotas). Implemented: the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy, and sending product notifications with the permission check before a send. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). No product flow calls `MailRequester` yet, and no identity flow calls `ServiceMailer` yet (registration and reset are separate tasks), so a stored notification waits and no service mail exists outside the tests.
Implemented: the `domain.Delivery` aggregate, `domain.MailContent`, and `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), the `outbound.DeliveryRepository` and `outbound.MailRequestRepository` ports (`port/outbound/delivery.go`) through `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()`, and `postgres.DeliveryStore`, migration `00006_create_deliveries.sql` with the `mail_requests`, `deliveries`, and `delivery_attempts` tables, the queries in `backend/db/queries/delivery.sql`, and in `backend/internal/usecase/notification/` the request usecase `MailRequester` and the consumer `DeliveryHandler`. The quota gate that admits or defers a send is implemented; see [Mail quotas](#mail-quotas). Implemented: the worker that claims due service mail, checks its token and account, passes it through the quota gate, and calls `MailSender`, with migration `00012_add_delivery_sending.sql`; see [Sending service mail](#sending-service-mail). Planned: retries and the unknown outcome policy, and sending product notifications with the permission check before a send. The delivery state gauges are implemented; see [Metrics, telemetry, and alerts](#metrics-telemetry-and-alerts). Product flows do not call `MailRequester` yet, so notification requests remain queued. Registration and resend create verification mail through `ServiceMailer`; password reset is not implemented.
A delivery is the durable state of sending one message to one recipient. A `deliveries` row holds:
@@ -254,7 +254,7 @@ Creation path:
Why the event carries only a reference. Events stay in `outbox_events` and in Kafka for the topic retention, and the domain event rule allows only identifiers and minimal facts. FR19 also requires that a queue does not keep revoked data available. The text therefore lives in `mail_requests`, which the account's deletion removes by cascade, and only as long as needed: the handler deletes the row in the transaction that stores the rendered delivery. After that the text exists only in the delivery, under the same retention and access rules. The address is read from the account in the handler transaction, so it is the address current at creation.
Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through `ServiceMailer`, which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token; the identity flows that call it (registration, resend, reset) are separate tasks.
Token mail. Verification and password reset bodies carry a one-time bearer token, which must never enter an event or a request row, and storage keeps only its SHA-256. `mail_requests` and schema version 1 therefore allow only kind `notification`. Token mail deliveries are created by the identity flows directly in the transaction that issues the token, through `ServiceMailer`, which uses `domain.NewDelivery` and `DeliveryRepository.Create` and binds the delivery to the token. Registration and resend create verification mail; password reset is a future flow.
Immutable content. A delivery stores the rendered body and never renders it again. Rendering at send time would need the raw token, which exists only in memory when it is issued, and a retry under the same idempotency key must repeat exactly the same body: Resend treats a changed body under an old key as a conflict. The domain recomputes the content hash on every read and fails with `domain.ErrMailContentIntegrity` on a mismatch. The trigger `deliveries_refuse_content_change` refuses an UPDATE that changes the recipient, content, idempotency key, source event, or creation time (SQLSTATE 23000, constraint `deliveries_content_immutable`, mapped to `outbound.ErrDeliveryContentImmutable`). A new template version therefore applies to new deliveries only; old template files are not needed to send a stored delivery.
@@ -342,13 +342,13 @@ Operators read the same rows with the queries in [DEPLOY.md](DEPLOY.md#mail-quot
### Sending service mail
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Not implemented: sending product notifications, the retry and unknown outcome policy, and the identity flows that call `ServiceMailer`.
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the minimum retry schedule `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` and `Delivery.Cancel` with the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop in `backend/internal/worker/mailsender/`, the inbound port `inbound.MailPass` (`port/inbound/mail_sender.go`), the repository methods `ClaimDue`, `ReleaseClaim`, `Cancel`, and `ServiceMailState`, migration `00012_add_delivery_sending.sql`, the gauge `lincodex_mail_sender_running`, and the wiring in `bootstrap/mail_sender.go`. Registration queues a verification email, and `ConfirmEmail` consumes its link. Product notification sending and the password reset flow are not implemented.
Scope. The worker claims only the kinds `verification` and `password_reset`. A product notification is never claimed here, whatever its state. Service mail needs no consent record of any purpose: it is part of the account flow, so nothing reads the consent ledger, and C2 (publication of the candidate card) and the other product consents play no part. What stands between the account and the mail is the check below, not a consent.
Enqueue. `ServiceMailer.EnqueueVerification` and `EnqueuePasswordReset` run in the transaction that inserts the token, with the token record, the raw token, the recipient address, and the lifetime in hours. They check that the token purpose fits the message, render the message once with the current template version, and store a `pending` delivery bound to the token (`email_token_id`) under the token's ID as the delivery ID. A repeated call for the same token stores nothing new, and the stored body stays as it was.
Links. The token travels only in the URL fragment: `<APP_PUBLIC_URL>/verify-email#token=<token>` and `<APP_PUBLIC_URL>/reset-password#token=<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 route reads the fragment and sends the token in the body of an API request. A query would be needed only if a frontend route could not read the fragment, and then the page would have to send the token onward and the access log would see it, so the fragment is the choice. 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.
Links. The token travels only in the URL fragment: `<APP_PUBLIC_URL>/verify-email#token=<token>` and `<APP_PUBLIC_URL>/reset-password#token=<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 confirmation screen is still a placeholder. A client must read and remove the fragment, wait for explicit confirmation, then send the token and registration password in the API 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.
One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps:
@@ -534,11 +534,11 @@ backend/
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The consent ledger types live in `consent.go`. The organization, verification, and membership types live in `organization.go` and `membership.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
Product domain types and usecase modules, the SMTP and FSP adapters, and product worker jobs are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
Outside the implemented identity and consent flows, domain types and usecases for other product workflows are not implemented. SMTP and FSP adapters, and product worker jobs, remain planned. `main.go` starts bootstrap and handles process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the sending worker of service identity mail, which no account flow feeds yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, the outbox relay that publishes committed events to Kafka through the franz-go adapter, the event consumer runtime with the `notification_delivery` handler, the scheduled job runtime (`worker/jobrunner`) with no registered product job kind, identity usecases for registration, resend, and confirmation, the consent usecase that records C1 during registration, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and checks used by registration and confirmation, a Redis cache adapter, a SeaweedFS S3 adapter with the shared private file layer over it, the `MailSender` port with the `disabled` and Resend transports, the mail template renderer, and the identity mail worker used for registration and resend. Login and sessions, resumes, assessments, invitations, product job kinds, file workflows, sending product notifications, the SMTP transport, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` renders verification and password reset mail with it when the identity usecases issue a token, and those usecases (registration, resend, reset) are separate tasks. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. `pkg/testutil/` holds `FakeClock`, a concurrency-safe manual clock that the worker, integration, and future usecase tests inject wherever production code takes a `func() time.Time` clock, and `FindPersonalIdentifiers`, which the metrics tests use to find email-like and UUID-like values in an exposition. A `mailer` package remains a candidate. Mail templates live in `internal/usecase/notification/mailtemplate/`: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging. The delivery consumer in `internal/usecase/notification/` renders notifications with it; `ServiceMailer` creates verification mail during registration and resend. Password reset mail belongs to the planned reset flow. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
@@ -646,16 +646,16 @@ The brief references Russian Federal Law 152-FZ. The system design calls for sep
### Identity storage
Implemented as storage only: migration `backend/db/migrations/00002_create_identity_tables.sql`, queries in `backend/db/queries/identity.sql`, domain types in `backend/internal/domain/`, ports in `backend/internal/port/outbound/identity.go`, and the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/identity.go`. The registration, verification, login, and session behavior described in [api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf) is planned; no usecase or handler uses this storage yet.
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, and `ConfirmEmail`. The frontend registration and confirmation screens are placeholders; login and sessions are not 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 the allowed purposes, so a 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`. 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.
- `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`.
Decisions:
- Email addresses are ASCII only, because the mailer has no SMTPUTF8 support. `domain.NewEmailAddress` rejects any non-ASCII character, including homoglyphs and fullwidth forms, with `ErrInvalidEmailAddress`, which the registration handler is expected to answer with 400 `validation_failed` whether or not an account exists. Internationalized domains are accepted only in their punycode form (`xn--...`). The key lowercases A-Z only; the database checks it with `translate()`, which does not depend on the collation, unlike `lower()`. Unicode addresses are future work: they need IDNA ToASCII for the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. Rows are read back with `domain.RestoreEmailAddress`, which checks only that the address and key match, so a stricter rule later does not make existing accounts unreadable.
- Email addresses are ASCII only, because the mailer has no SMTPUTF8 support. `domain.NewEmailAddress` rejects any non-ASCII character, including homoglyphs and fullwidth forms, with `ErrInvalidEmailAddress`, which the registration handler answers with 400 `validation_failed` whether or not an account exists. Internationalized domains are accepted only in their punycode form (`xn--...`). The key lowercases A-Z only; the database checks it with `translate()`, which does not depend on the collation, unlike `lower()`. Unicode addresses are future work: they need IDNA ToASCII for the domain, a rule for Unicode local parts, and SMTPUTF8 delivery. Rows are read back with `domain.RestoreEmailAddress`, which checks only that the address and key match, so a stricter rule later does not make existing accounts unreadable.
- The database stores hashes, never passwords or raw tokens. A token carries 256 bits from crypto/rand, so an unsalted SHA-256 cannot be reversed by guessing and a lookup stays one index probe; passwords need the slow Argon2id KDF instead. `bytea` keeps the digest at half the size of hex text, with an exact length CHECK and no letter-case variants. `domain.SecretToken`, `domain.PasswordHash`, and `domain.EmailAddress` redact themselves in `fmt` (every verb) and `slog` output, so printing a `domain.User` shows neither the address nor the hash; explicit accessors return the real values. Unmapped PostgreSQL errors from the identity repositories keep only the SQLSTATE and the constraint name, because the message and detail can quote row values.
- Enum-like columns are text with CHECK constraints rather than PostgreSQL enum types. A new scenario, step, or purpose replaces one constraint in a reversible migration; an enum value cannot be removed and cannot be used in the transaction that adds it.
- Every stored time comes from the application clock that the caller passes, so deadlines and the checks against them use one clock. Repositories reject the zero time.
@@ -682,22 +682,22 @@ Implemented and tested: registration creates the hasher from configuration and c
- `Verify` parses the stored PHC string strictly and recomputes the key with the stored parameters, salt, and key length, then compares in constant time. A wrong password returns `outbound.ErrPasswordMismatch`. A malformed hash, or one outside the stored-hash bounds (memory from 8 KiB per lane to 128 MiB and within the hashing budget, 1 to 16 passes, 1 to 16 lanes, a salt of 8 to 64 bytes, a digest of 16 to 64 bytes), returns `outbound.ErrPasswordHashCorrupt` without any derivation, so a crafted row cannot demand unbounded memory or time. `ErrPasswordHashCorrupt` wraps `domain.ErrInvalidPasswordHash`, which the repository returns for a stored hash that fails `domain.NewPasswordHash`. On a match `needsRehash` reports parameters, salt, or key length that differ from the current ones, so a login can store a new hash.
- `VerifyDummy` runs `Verify` against a hash with the current parameters, a random salt, and a random digest, and returns `ErrPasswordMismatch` (or the context error). Login will call it for an unknown email, so both branches parse, wait for memory, derive, and compare alike.
- Login must answer `invalid_credentials` for an unknown email, a wrong password, and an invalid stored hash (`errors.Is(err, domain.ErrInvalidPasswordHash)`, from the repository or from `Verify`); for an invalid hash it must also log an error and call `VerifyDummy`. Remaining timing differences: a corrupt hash is refused without a derivation, which `VerifyDummy` compensates, and a hash with older parameters costs what its own parameters cost until the next successful login rehashes it.
- `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration will call it on every branch before it looks up the email.
- `identity.Credentials.HashNewPassword` validates a new password and only then hashes it; registration calls it on every branch before looking up the email.
- Errors and logs never contain the password or the hash. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken`, and `domain.EmailAddress` redact themselves in `fmt`, `slog`, and JSON output, and keep their value behind a pointer, so printing an enclosing struct, even through an unexported field, shows only an address.
### Consent ledger
Implemented as storage, ports, and a read contract: migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, the ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Granting C1-C3 and C5 with a current-version check is implemented as the usecase `consent.Service` (see [Consent usecase](#consent-usecase)). Revocation with its downstream effects and the HTTP handler, C1 in the registration transaction, and C4 in the invitation acceptance are planned; no product flow calls the usecase yet.
Consent storage, ports, the read contract, and grants through `consent.Service` are implemented: migration `backend/db/migrations/00009_create_consent_ledger.sql`, queries in `backend/db/queries/consents.sql`, domain types in `backend/internal/domain/consent.go`, ports in `backend/internal/port/outbound/consents.go`, the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/consents.go`, and `ListMyConsents` in the public contract ([api/README.en.md](../../api/README.en.md#consents)). Registration records C1 through `GrantAtRegistration` in the account creation or re-registration transaction; confirmation checks the C1 record for the same registration version as the token. HTTP consent grants and revocation, revocation effects, and C4 at invitation acceptance are not implemented.
The consents C1-C5 of PRD FR01 are independent purposes: a grant or a revocation of one never changes another.
`consent_texts` holds the published texts: `purpose`, `version` (the contract's `ConsentTextVersion`), the exact `body`, `body_sha256` checked against the body by a CHECK, `kind` (`demo` for synthetic texts without a legal review, `operator` for texts of the actual operator), and `published_at`. The current text of a purpose is the latest publication not after the grant time. Texts are immutable: a trigger refuses UPDATE, DELETE, and TRUNCATE (`consent_texts_immutable`), and a changed text is a new version. The migration publishes demo version `cN-2026-10-01` of every purpose; the operator's texts arrive as new versions in a later migration before real data are accepted (PRD 7.3). Only the C4 text contains the placeholder `{organization}`; `ConsentText.RenderForOrganization` fills it in.
`consent_records` is the append-only ledger. One row per grant: UUIDv7 `id`, `subject_id`, `purpose`, `text_version`, `text_hash` (SHA-256 of exactly the text the subject saw, 32 bytes), `source` (`registration` for C1 only, `consent_settings` for C1-C3 and C5, `invitation_acceptance` for C4 only), `granted_at`, and the one-time revocation stamp `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A C4 row also has `organization_id`, `organization_name` (the name the shown text carried, a snapshot of 1-200 characters), the canonical `field_set` (one to four distinct `ContactFieldKind` values in ascending byte order), `invitation_id`, and `invitation_terms_version`; every other purpose must leave them NULL (`consent_records_c4_scope`). Request metadata such as IP addresses or user agents is not stored: the PRD asks for the version, hash, time, subject, and revocation event, and the extra data would be personal data without a purpose.
`consent_records` is the append-only ledger. One row per grant: UUIDv7 `id`, `subject_id`, `purpose`, `text_version`, `text_hash` (SHA-256 of exactly the text the subject saw, 32 bytes), `source` (`registration` for C1 only, `consent_settings` for C1-C3 and C5, `invitation_acceptance` for C4 only), `registration_version` for registration-source C1 only, `granted_at`, and the one-time revocation stamp `revoked_at` with `revocation_source` (`consent_settings` or `support_request`). A C4 row also has `organization_id`, `organization_name` (the name the shown text carried, a snapshot of 1-200 characters), the canonical `field_set` (one to four distinct `ContactFieldKind` values in ascending byte order), `invitation_id`, and `invitation_terms_version`; every other purpose must leave them NULL (`consent_records_c4_scope`). Request metadata such as IP addresses or user agents is not stored: the PRD asks for the version, hash, time, subject, and revocation event, and the extra data would be personal data without a purpose.
Decisions:
- Text binding. A foreign key on (`purpose`, `text_version`) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (`consent_records_text_published`). For C1-C3 and C5 a second foreign key over a generated column requires `text_hash` to equal the hash of the published text. For C4 the same trigger requires `text_hash` to equal the SHA-256 of the published text with `organization_name` filled in (`consent_records_c4_text_hash`). The domain computes that hash itself in `domain.NewContactConsentGrant` from the published `ConsentText` and the name, so no caller supplies hash bytes, and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it as `ConsentOrganization.name`.
- Text binding. A foreign key on (`purpose`, `text_version`) refuses a version that was never published for the purpose, and a BEFORE INSERT trigger refuses a version published after the grant time (`consent_records_text_published`). For C1-C3 and C5 a second foreign key over a generated column requires `text_hash` to equal the hash of the published text. For C4 the same trigger requires `text_hash` to equal the SHA-256 of the published text with `organization_name` filled in (`consent_records_c4_text_hash`). The domain computes that hash itself in `domain.NewContactConsentGrant` from the published `ConsentText` and the name, so no caller supplies hash bytes and a client can invent neither a version nor a hash. The stored name is the snapshot that proves the shown text; a later rename of the organization does not change it, and the read model returns it as `ConsentOrganization.name`.
- History. The only UPDATE a trigger allows is the revocation stamp on an unrevoked row with every other column unchanged (`consent_records_immutable`). A newer text version is a new row next to the older one; a grant after a revocation is a new row. The state (`active`, `superseded`, `revoked`) is computed by the queries, never stored: among the unrevoked rows of a subject and purpose other than C4, the row granted last (by `granted_at`, then ID) is `active` and the others are `superseded`, whatever their versions. The ledger therefore accepts any published version, and the grant usecase `consent.Service` checks that the version is the current text before it calls `Grant`. A partial unique index keeps one unrevoked row per subject, purpose, and version, so a repeated or concurrent grant returns the existing record; a unique index on `invitation_id` keeps one C4 row per invitation, revoked or not, so a revoked C4 never comes back.
- Revocation. `ConsentLedger.Revoke` stamps every unrevoked row of the purpose, superseded rows included, and for C4 only those of one organization. A repeat finds nothing and keeps the first stamp. A revocation time before the grant time of a row, from clock skew between instances, is stamped at the grant time (`greatest`), so the `consent_records_revocation_stamp` CHECK stays a backstop. The downstream effects of a revocation (deletion request for C1, closing publication and grants for C2 and C4, the manual path for C3, stopping the import for C5) belong to consent revocation and are not implemented.
- Retention and deletion. PRD 7.3 plans to keep consents for three years, which can outlive the account, so `subject_id` references `users` with `ON DELETE RESTRICT`, and a BEFORE DELETE trigger refuses deleting a row whose subject is a confirmed account (`consent_records_retained`). Rows of an unconfirmed account may be deleted, because a registration that the email owner never confirmed is not evidence of anyone's consent: the unverified account cleanup deletes the rows of the accounts it removes in the same statement, and `UpdateRegistration` deletes the registration C1 of the account it re-registers (see below). TRUNCATE fires no row trigger and stays allowed for test isolation. Whether a deleted account leaves its ledger, a tombstone, or nothing is decided by the C1 deletion request and the account deletion procedure that executes it, which has no MVP task yet; the retention rule extends the delete condition in its own migration.
@@ -717,10 +717,11 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo
### Consent usecase
Implemented: `consent.Service` in `backend/internal/usecase/consent/`. It is not wired into bootstrap yet, because no handler or registration flow calls it; the first caller builds it with `consent.NewService(transactor, clock)`, the `Transactor` and the application clock that the other usecases already receive. A nil transactor or clock panics at construction, so a wiring mistake shows at startup and not at the first grant.
`consent.Service` in `backend/internal/usecase/consent/` is wired through bootstrap and used by registration to check the text version and grant C1 in the create or re-registration transaction. It is built with `consent.NewService(transactor, clock)`, the `Transactor` and application clock the other usecases receive. A nil transactor or clock panics at construction.
- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, version)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled.
- Entry points fix the source. `GrantAtRegistration(ctx, repositories, subjectID, registrationVersion, textVersion)` records C1 with the source `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` records C1, C2, C3, or C5 with the source `consent_settings`. Neither takes a source or a time, so a handler cannot read either from the client. `repositories` is an `outbound.ConsentRepositories`: pass the `UnitOfWork` of a business operation and the grant commits or rolls back with it. The registration creates the account and records C1 in one transaction on the subject ID alone, so no session is needed. `GrantInSettingsInNewTransaction` opens its own transaction for a grant that is not part of another operation, and retries an `ErrTransactionConflict` up to three attempts in total with a short jittered wait (10 ms plus up to 10 ms) between them, which is safe because a repeat is idempotent; the wait ends at once when the context is canceled.
- Re-registration order. For an unverified account that registers again, call `GrantAtRegistration` strictly after `UserRepository.UpdateRegistration` in the same transaction. `UpdateRegistration` deletes the registration C1 of the earlier registrant, and a grant that ran before it would find that record, return it with `Created` false, and leave the account without any C1 once it is deleted. The integration test shows both orders.
- C1 registration version. Migration `00016_bind_registration_consent.sql` adds `registration_version` only to registration-source C1; other grants must leave it NULL. It backfills old C1 rows from the current account version without using tokens. Re-registration deletes the prior registration C1, so an older grant time or multiple active registration C1 rows for one account are inconsistent and stop the migration. The partial unique index `consent_records_registration_version_key` allows at most one unrevoked registration C1 for an account and version. The insert trigger fills the current version when an old backend omits it and rejects a mismatch from the new backend; the immutability trigger also protects the version during revocation.
- Version check before the email branch. `CheckTextVersion(ctx, repositories, purpose, version)` returns the current text when `version` is current and fails like a grant otherwise, without writing anything. The registration must call it with C1 and the submitted version before it branches on a new or an existing email; otherwise a stale version would be refused only for new addresses, and the difference would reveal which accounts exist.
- Current text only. A grant reads `ConsentTexts().Current` at the application time and refuses any other version with `*StaleConsentTextError`, which matches `ErrStaleConsentText` and carries the purpose, the requested version, and the current one, so a handler can map it to one problem code and show the new text. An older version, a version that is scheduled but not yet published, and a version that never existed are all stale. The ledger accepts any published version, so this check is what keeps a grant of an outdated text out. The check and the insert are not locked against a publication between them: texts are published by migrations, and a grant that named the current text when it was checked is valid.
- Server time. The input has no time field. The grant uses one reading of the injected clock for the check and for the record time; a client cannot choose the time. The database still refuses a version published after that time.
@@ -731,23 +732,23 @@ Implemented: `consent.Service` in `backend/internal/usecase/consent/`. It is not
- Errors keep their identity: a stale version, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (the purpose has no published text), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent`, and `domain.ErrInvalidConsentText`. `outbound.ErrTransactionConflict` is the one that needs action: the ledger returns it, without aborting the transaction, when the record of a repeat was revoked between its insert and its select. A caller inside a `UnitOfWork` must return it, roll the transaction back, and retry the whole operation; `GrantInSettingsInNewTransaction` does so itself. Mapping the other errors to problem codes belongs to the handlers.
- Demo texts need a release gate. The texts that the migration publishes have the kind `demo`: synthetic, without a legal review. Nothing in the usecase distinguishes them from texts of the operator, so a deployment that accepts real data would record consent to a demo text. Before real data are accepted (PRD 7.3), a release gate must check that the current text of every purpose has the kind `operator`; the owner is the release gate or consent revocation, and neither exists yet.
### Registration and verification resend
### Registration, email verification, and resend
Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/identity.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`.
One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account.
Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns `pending_*` of `email_tokens`, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the `users` row: `UserRepository.AdvanceRegistration` only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The `password_hash`, `scenario`, and `onboarding_step` of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on `domain.User`). Invalidating a token (`InvalidateActive`) clears its `pending_*` columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing. Requirements for the hand-off:
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`): confirming a token applies the pending credentials of the clicked token, and only those, to the account row in the confirmation transaction (password hash, scenario, onboarding step), and must require the password of that registration to confirm a token that carries pending credentials, verified against the token's pending hash. Then a victim who clicks an attacker's link cannot adopt the attacker's password, and an attacker cannot confirm the victim's token. `EmailVerificationRequest` has no password field today; adding it is an email confirmation contract change, not made here. The description of `RegisterAccount` in the contract still says a repeat registration replaces the password hash on the account; email confirmation must correct it with that change.
- Email confirmation also requires: test both orderings (the attacker registers first and the victim second, and the reverse) and show that the owner never ends up with a password they did not choose; require that a C1 record exists and belongs to the registration version of the confirmed token; refuse a token that carries no pending credentials, with no legacy path that skips the password; null the `pending_*` columns of the token when it is consumed.
- Login: an unverified account never signs in. Login answers as for a wrong password (or `email_not_verified` only where the contract allows it) without comparing the password with the row of an unverified account or with pending credentials.
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 still a placeholder; login and session recovery are not implemented.
Planned login behavior: an unverified account will not be able to sign in. Login will answer as for a wrong password (or `email_not_verified` only where the contract allows it) without comparing the password with the row of an unverified account or with pending credentials.
Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit.
Idempotency. The key is scoped by `HMAC(secret, operation | key | normalized email)` and the request is fingerprinted by `HMAC(secret, canonical body)` (`identity.Keyring`, secret `IDENTITY_KEY_SECRET`; required; a development stand may set `IDENTITY_ALLOW_EPHEMERAL_KEY=true` to draw a random one per process, which loses records and counters on restart). The record lives in `idempotency_records` (migration 00014) for 24 hours and is written in the registration transaction, so a visible record always belongs to a committed registration. A retry with the same key and body replays the neutral 202 and consumes no limit; the same key with another body answers 422 `idempotency_key_reused`. A concurrent identical request waits on the row of the first and is then replayed, so this implementation never answers 409 `idempotency_in_progress`. Each registration purges up to 10 expired records, which keeps the table bounded without a job.
Rate limits (Redis, fixed windows, `outbound.RateLimiter`, `redis.Cache.Take`, one atomic Lua script per take). The counters are keyed by the HMAC of the normalized address and count every request whether or not an account exists, so a 429 reveals nothing about the account. The registration and every resend share the per-address counters: at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between two messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per window of 24 hours that starts with the first. A per-client counter, `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour), is keyed by `middleware.LimiterKey` of `ClientAddr`, hashed with the secret, and is skipped when the address is unknown (a shared bucket would let one client lock out everyone). A refused request counts nothing, answers 429 `rate_limited` with `Retry-After` in whole seconds rounded up, and issues no token. Counters are ephemeral: a Redis restart resets them, and the mail provider quota remains the last bound. A Redis failure answers 500 and never lets the request through. Neither address nor token is logged.
Rate limits (Redis, fixed windows, `outbound.RateLimiter`, `redis.Cache.Take`, one atomic Lua script per take). The counters are keyed by the HMAC of the normalized address and count every request whether or not an account exists, so a 429 reveals nothing about the account. Registration and every resend share the per-address counters: at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between two messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per window of 24 hours that starts with the first. Confirmation allows five attempts per token per hour. A per-client counter, `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour), is keyed by `middleware.LimiterKey` of `ClientAddr`, hashed with the secret, and is skipped when the address is unknown (a shared bucket would let one client lock out everyone). A rejected `Take` does not increase its own counter; if an earlier limit check passed, its counter already records the attempt even when the next check refuses it. A refusal answers 429 `rate_limited` with `Retry-After` in whole seconds rounded up and issues no token. Counters are ephemeral: a Redis restart resets them, and the mail provider quota remains the last bound. A Redis failure answers 500 and never lets the request through. Neither address nor token is logged.
Token replacement policy. Every issue of a verification token (registration, re-registration, resend) first invalidates all unused verification tokens of the account and then stores the new one, so at most one link works at a time. A resend keeps the password, the scenario, the consent record, and the registration version; only the token changes. The message of an invalidated token is cancelled by the sending worker, so only the current link is delivered. The token lifetime comes from the product policy (`identity.verification_token_lifetime_hours`, 24 in the demo version), not from configuration.
+8 -6
View File
@@ -72,7 +72,7 @@ The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` boot
`PASSWORD_HASH_CONCURRENCY` sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from `.env`, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets `GOMEMLIMIT=600MiB`, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login will use it once they are implemented. See [ARCHITECTURE.md](ARCHITECTURE.md#password-hashing).
`IDENTITY_KEY_SECRET` is required in the production `.env` (at least 32 bytes; generate it with `openssl rand -base64 48` and keep it between restarts and across instances). It keys the registration idempotency records and the rate limit counters; Compose refuses to start without it, and the backend refuses to start without it unless `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, which is for development stands only. Changing it forgets the idempotency records and counters of the last 24 hours. `VERIFICATION_MAIL_MIN_INTERVAL` (default `1m`), `VERIFICATION_MAIL_DAILY_LIMIT` (default `5`), and `IDENTITY_CLIENT_HOURLY_LIMIT` (default `30`) bound the verification mail per address and the registrations per client; an empty value means the default. The metric `lincodex_identity_rate_limit_refusals_total{scope}` counts refusals; a large share of `scope="client"` hints at a broken proxy chain (see `TRUSTED_PROXY_CIDRS`). See [ARCHITECTURE.md](ARCHITECTURE.md#registration-and-verification-resend).
`IDENTITY_KEY_SECRET` is required in the production `.env` (at least 32 bytes; generate it with `openssl rand -base64 48` and keep it between restarts and across instances). It keys the registration idempotency records and the rate limit counters; Compose refuses to start without it, and the backend refuses to start without it unless `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, which is for development stands only. Changing it forgets the idempotency records and counters of the last 24 hours. `VERIFICATION_MAIL_MIN_INTERVAL` (default `1m`), `VERIFICATION_MAIL_DAILY_LIMIT` (default `5`), and `IDENTITY_CLIENT_HOURLY_LIMIT` (default `30`) bound verification mail per address and requests per client; an empty value means the default. Confirmation is also limited to 5 attempts per token per hour. The metric `lincodex_identity_rate_limit_refusals_total{scope}` counts refusals; a large share of `scope="client"` hints at a broken proxy chain (see `TRUSTED_PROXY_CIDRS`). See [ARCHITECTURE.md](ARCHITECTURE.md#registration-email-verification-and-resend).
down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop.
@@ -233,7 +233,9 @@ A worker claims it within one poll interval and runs it with fresh attempts. To
The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read.
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. The backend process runs a sending worker for service identity mail (email verification and password reset) whenever `EMAIL_PROVIDER` is `resend`; see [Sending service mail](#sending-service-mail). No account flow creates such mail yet, and product notifications are stored as deliveries but not sent until product notification sending is implemented, so a production stand sends no message today.
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.
`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; retries, backoff, rate-limit pacing, and outcome records belong to the planned delivery layer, and the wait for a daily or monthly quota reset is decided by the quota gate (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).
@@ -247,7 +249,7 @@ Current state: this build contains the `disabled` and `resend` transports. With
| `EMAIL_TIMEOUT` | `10s` | Go duration from `1s` to `1m`; limits one transport attempt |
| `EMAIL_QUOTA_DAILY` | `100` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC day through the configured provider account: an integer from 1 to 1000000000. Empty counts as unset. No value turns the quota off. |
| `EMAIL_QUOTA_MONTHLY` | `3000` for `resend` and `disabled`; none for `smtp`, where it is required | Recipients per UTC calendar month: an integer from 1 to 1000000000, not below `EMAIL_QUOTA_DAILY`. Empty counts as unset. |
| `APP_PUBLIC_URL` | none, required | Public origin for links in mail: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. |
| `APP_PUBLIC_URL` | none, required | Public origin for mail links and the Origin of confirmation requests: `https://host[:port]`, or `http` only for `localhost`, `127.0.0.1`, or `[::1]`. No credentials, path, query, or fragment; one trailing `/` is dropped. |
| `RESEND_API_KEY` | empty | Read only for `resend`, where it is required. Printable ASCII without whitespace. The `re_` prefix shown in Resend examples is not enforced. |
| `SMTP_HOST` | empty | Read only for `smtp`, where it is required. Hostname or IP address without a port. |
| `SMTP_PORT` | empty | Required for `smtp`. Integer from 1 to 65535. |
@@ -299,10 +301,10 @@ The backend process runs one sending loop for service identity mail (email verif
### Mail templates
Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications with it when it stores a delivery, and `ServiceMailer` renders verification and password reset mail when an identity flow issues a token; the flows themselves (registration, verification, password reset) are planned, so no account triggers a message yet.
Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications when it stores a delivery, and `ServiceMailer` creates verification mail during registration. Email confirmation is implemented in the API; the frontend confirmation screen remains a placeholder. The password reset flow is still planned.
- Templates are embedded in the binary with `go:embed` and parsed once when the renderer is created; a broken template fails its creation. Each version has three files: `<kind>.v<N>.subject.tmpl`, `<kind>.v<N>.txt.tmpl`, and `<kind>.v<N>.html.tmpl`. The HTML part uses `html/template`, the plain-text part and the subject use `text/template`. Every transport sends the same rendering; templates hold no provider settings, keys, or sender address.
- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `<APP_PUBLIC_URL>/verify-email#token=<token>`; password reset: `<APP_PUBLIC_URL>/reset-password#token=<token>` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it, and the frontend route reads it in the browser and sends it in an API request body. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected.
- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `<APP_PUBLIC_URL>/verify-email#token=<token>`; password reset: `<APP_PUBLIC_URL>/reset-password#token=<token>` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it. The frontend confirmation screen remains a placeholder; a client must read and remove the fragment, wait for explicit user action, then send the token and registration password to the API. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected.
- Messages contain no name, email address, or other contact. Caller text in a notification is escaped in the HTML part; control and bidirectional characters are removed from the plain-text part, and the subject becomes one line, so CR and LF cannot add header lines. The notification subject is limited to 100 characters and the body to 2000.
- Copy is in Russian. A released version is immutable: changing copy adds the next version, for example `verification.v2`, and switches the current version in code. Versions share no files, so one version cannot change the body of another. Each rendering carries its version and a SHA-256 content hash over the version, subject, and both parts; the same version and data always give the same body. A delivery stores the rendered body with the hash, and a retry sends the stored body instead of rendering again, so a new version applies to new deliveries only and an old version's files are not needed to send a stored delivery.
- The renderer does not log. A rendering and notification data print only the kind, version, and content hash in `fmt` and `slog` output; tokens, links, and bodies are never printed.
@@ -378,7 +380,7 @@ All names and addresses come from `deploy/edge/edge.env` (copy `deploy/edge/edge
The browser sees only `https://<EDGE_DOMAIN>`. The SPA and `/api` come from the same origin: the edge forwards every path unchanged, and the frontend container serves the SPA with its `try_files ... /index.html` fallback, so a deep link such as `/some/deep/link` returns the SPA, and proxies `/api/` to Go. The planned session cookie is `__Host-lincodex_session` with `Secure`, `HttpOnly`, and `SameSite=Strict`. Browsers accept it only from an HTTPS page, with `Path=/` and no `Domain`, which the single HTTPS origin gives. The edge keeps `Host` as the public name and sets `X-Forwarded-Proto: https`; the frontend container's Nginx keeps that value for the backend (`$forwarded_proto` in `deploy/nginx/conf.d/app.conf`) and otherwise reports its own scheme. `APP_PUBLIC_URL` in the app host `.env` must be `https://<EDGE_DOMAIN>`, which is the only origin value the backend reads.
Registration and login are not implemented yet (the operations answer 501), and the backend does not read `X-Forwarded-Proto`. Sign-in through the edge is therefore not verified end to end; what is verified is the transport the cookie needs (HTTPS, one origin, the original host and scheme forwarded).
Registration, verification resend, and email confirmation are available through the API, but login is not implemented. Frontend registration and confirmation screens remain placeholders, and the backend does not read `X-Forwarded-Proto`. The browser confirmation and sign-in paths through the edge are not verified end to end; the cookie transport is checked (HTTPS, one origin, and the forwarded original host and scheme).
### Request handling at the edge
+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).
+5 -3
View File
@@ -18,15 +18,15 @@ Installation requires Python, uv, Go, and network access. The Trivy/Gitleaks bin
| Target | Scope |
| --- | --- |
| `filesystem` | Trivy scans repository dependencies and configuration with `trivy/filesystem.yml` |
| `secrets` | Gitleaks scans current files and all available Git history with `gitleaks/gitleaks.toml` |
| `secrets` | Gitleaks scans tracked and non-ignored untracked files, plus all available Git history with `gitleaks/gitleaks.toml` |
| `go` | govulncheck analyzes the backend's use of known vulnerable Go code |
| `semgrep` | Local rules in `semgrep/frontend.yml` and `semgrep/python.yml` inspect frontend and ML source |
| `rule-test` | Semgrep fixtures check expected matches and non-matches for the local rules |
| `test` | Runs Semgrep rule fixtures and tests for installer integrity, preservation of govulncheck failure status, and removal of stale reports |
| `test` | Runs Semgrep rule fixtures and tests for installer integrity, Gitleaks input and report handling, govulncheck failure status, and stale reports |
| `check` | Runs filesystem, secrets, Go, and Semgrep checks; attempts every check and returns failure if any fails |
| `images` | Builds backend, frontend, and ML images, then scans each exact local image ID with Trivy |
Gitleaks requires a full Git checkout. A missing repository or shallow history fails the check rather than silently omitting history. Reports redact detected secret values. Developer tool caches and build output are excluded where configured; application lockfiles remain scan inputs. Trivy also recognizes `requirements-*.txt`, including `backend/requirements-quality.txt` and `scripts/requirements-codegen.txt`.
Gitleaks requires a full Git checkout. A missing repository or shallow history fails the check rather than silently omitting history. Its current-file scan uses tracked files and untracked files that Git does not ignore. Tracked ignored files remain in the scan, while ignored local files such as `.env` stay out of it. Deleted tracked paths and symlinks are omitted from the current scan; symlink targets are never followed or read. The history scan still covers every ref, including values committed before a file was ignored or removed. Gitleaks copies the current input set to an owner-only temporary directory and fails if either scanner fails or its JSON report is missing or invalid. Reports redact detected secret values. Developer tool caches and build output are excluded where configured; application lockfiles remain scan inputs. Trivy also recognizes `requirements-*.txt`, including `backend/requirements-quality.txt` and `scripts/requirements-codegen.txt`.
Image checks require Docker. The backend build context is `backend/`; frontend and ML use the repository root. Images are tagged `lincodex-security-<service>:local` and resolved to image IDs before scanning. This command does not start containers or publish images. Scanning frontend source dependencies remains necessary because the final Nginx image contains compiled assets rather than the development dependency tree.
@@ -38,6 +38,8 @@ Review the reported package, installed version, affected path, and available rem
One temporary exception in [security/trivy/ignore.yml](../../security/trivy/ignore.yml) was approved by the project owner on 2026-10-05: `CVE-2026-93687` for `pkg:npm/braces@3.0.3` in `frontend/pnpm-lock.yaml`. At approval, no fixed release was available; the exception unblocks dependency CI until its expiry on 2026-10-19. Project maintainers own the exception and must remove it when a fix becomes available or review it before expiry. Trivy enforces the expiry date. Only filesystem scanning uses this exception file; suppressed findings remain visible in its JSON report. Image scanning is unaffected.
Eight Gitleaks exceptions cover exact public API examples, test fixtures, a release-manifest fixture, and a fixed Redis rate-limit key prefix. Each requires the matching rule ID, repository path, and complete finding text. Project maintainers own them. Manually review or remove them by 2026-11-07; Gitleaks does not enforce that review date. See the official [Gitleaks configuration reference](https://github.com/gitleaks/gitleaks#configuration) for allowlist behavior.
For any further exception, scope it to the specific finding and affected input, record the reason, owner, and expiry, and have the change reviewed. The current integration does not enforce expiry uniformly across every tool, so review expiry explicitly where needed. Do not disable an entire scanner or globally suppress unfixed vulnerabilities to obtain a passing result.
## CI and limits
+7 -3
View File
@@ -40,7 +40,9 @@ Security checks run separately: `make -C security check` scans source/dependenci
## Current scaffold coverage
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the private file layer and SeaweedFS access controls (see [Private file storage tests](#private-file-storage-tests)), the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. There are no registration, login, assessment, search, invitation, or file workflows, no product event producer in Kafka (the mail delivery consumer is exercised only by tests), and no real model inference to validate as product behavior.
Existing checks cover health/readiness, backend PostgreSQL, Redis, and SeaweedFS connectivity, migration up, down to zero, and up again on an isolated database, concurrent migration runners that apply each migration once, the transactional outbox (atomic commit, rollback on error, panic, and context cancellation, nested-transaction rejection, an observed row-lock wait between concurrent transactions, edge payloads, and constraints), identity storage (a unique normalized email, hash-only storage of email and session tokens, exactly one successful consumption of a token under parallel confirmations and an observed lock wait between two consumes, rejection of expired, invalidated, and superseded tokens, including a re-registration that commits during a confirmation, session idle, absolute, and revocation limits and touch throttling, batch cleanup of unverified accounts that skips locked accounts without waiting, a deadlock reported as a retryable conflict, cascade deletes, rollback with the surrounding transaction, and constraints), cache operations and TTL, S3 operations and object persistence, the private file layer and SeaweedFS access controls (see [Private file storage tests](#private-file-storage-tests)), the Kafka test harness (keyed records with headers and per-partition order, refusal to create a missing topic on demand, and topic cleanup), the outbox relay (see [Outbox relay tests](#outbox-relay-tests)), the event consumer runtime (see [Event consumer tests](#event-consumer-tests)), mail deliveries (see [Mail delivery tests](#mail-delivery-tests)), metrics, the API client, ML schemas, and current endpoint availability. Registration and email confirmation have API integration coverage; login, assessment, search, invitation, and file workflows are not implemented. Confirmation writes an event to the transactional outbox, with no registered product consumer for that event; mail delivery is tested separately. There is no real model inference to validate as product behavior.
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; frontend registration and confirmation screens remain placeholders, and the test does not send through an external mail provider.
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.
@@ -82,6 +84,8 @@ The shared helper lives in `backend/integration_test/bootstrap_test.go`. Calling
Call bootstrap once in the parent test and share its environment with its subtests. Each call creates separate containers with dynamic ports and a separate SeaweedFS volume when needed. Cleanup is registered through `t.Cleanup`, including partial startup. Redis outage and SeaweedFS recreation scenarios manage resources through environment helpers without affecting other tests. Tests fail when Docker is unavailable. Testcontainers also tries the Docker context and default sockets when `DOCKER_HOST` is unreachable, so an invalid `DOCKER_HOST` alone does not simulate a missing Docker.
Container startup makes at most three attempts, and only when rootless Docker returns the exact host-port networking error ending in `bind: address already in use` (`EADDRINUSE`). Before retrying, bootstrap terminates any partial container returned by the failed attempt; a cleanup error stops retries. Other startup and readiness errors, and test assertion failures, are not retried. This changes test setup behavior only and does not modify Docker or host networking configuration.
Bootstrap starts infrastructure and clients. When PostgreSQL is selected, it applies every embedded migration with the startup runner. `postgres_helpers_test.go` adds `env.newPool` for a pool to that database, `env.createIsolatedDatabase` for a separate database in the same container when a test changes the whole schema (for example up, down, and up again), `env.newPoolWithMaxConns` for concurrency tests that need one connection per transaction, and `truncateTables` for resetting shared tables between sequential subtests. Tests reach the transaction behind a unit of work only through `postgres.TransactionForIntegrationTest`, which is compiled only with the `integration` build tag. Test-only aggregates live in their own schema created by the test, not in production migrations. The application HTTP server, ML, and product fixtures are not included yet. The full-environment test exercises combined PostgreSQL, Redis, and SeaweedFS readiness.
Kafka is not part of `bootstrap(t)` and starts only for tests that select `bootstrap(t, kafkaService)`. It runs the same `apache/kafka:latest` image as Compose with the same KRaft settings, including `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. The client listener is advertised on the dynamic host port, inter-broker and controller traffic stay on container loopback, and the data and declared image volumes use tmpfs, so a test broker leaves no volumes. Bootstrap sets `env.Config.KafkaBrokers` and creates `env.KafkaAdmin` from franz-go `kadm`.
@@ -163,7 +167,7 @@ Unit tests (`make -C backend test`) cover the delivery model and its creation pa
- A request whose account is deleted loses its request row with the account; the handler then stores no delivery and logs the delivery ID.
- The unverified account cleanup skips an account whose delivery row another transaction holds, deletes it once the lock is gone, and its pending request and its delivery, created directly through the repository as token mail will be, go with it.
Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. The suite does not send mail: the sending worker, retries, and the permission check are later tasks, quotas have their own [Mail quota tests](#mail-quota-tests), and there is no test of a verification or password reset delivery, which the identity flows will create.
Every case checks that the captured handler and consumer logs hold neither the address nor the subject or body, and the request events are checked to carry no address and no request text. `TestPostgresMigrations` also checks that migration 00006 creates and drops its three tables and both trigger functions, and `TestIdentityRepositories` runs the cleanup query with the mail request and delivery locks. `TestMailDelivery` does not send mail; it covers the product notification consumer. `TestEmailVerificationOverHTTP` exercises verification mail and confirmation through the Resend fixture but does not call an external provider. The password reset flow has no delivery test because it is not implemented.
## Mail quota tests
@@ -325,7 +329,7 @@ Unit tests (`make -C backend test`) cover the ledger rules without a database:
- C4: the generic path refuses it and stores nothing; `GrantContact` in a transaction stores the organization, the name, the fields, the invitation, and the source `invitation_acceptance`; a repeat returns the same record, an outdated C4 version is stale, and the C4 does not create a C2.
- Restart: after the pool is closed, a new pool, store, and usecase list the same four records in order with their states, the revocation stamp and source, and the original grant times, and a repeat grant through the new instance stores nothing.
`TestPostgresMigrations` rolls migration 00009 back with the others and checks that no table or function remains. The integration tests of identity, mail delivery, and mail quotas name `consent_records` in their TRUNCATE of `users`. The suite does not cover the revocation usecase, the HTTP handler, or the call of the consent usecase from registration and the invitation acceptance, and the cleanup race that ends in SQLSTATE 23001 is covered only by the unit test of its mapping, because its window cannot be reproduced deterministically.
`TestRegistrationConsentMigration` applies migration 00016 in an isolated database and checks legacy C1 binding, no binding for settings grants, inserts through the old row shape, rejection of a supplied mismatched version, protection against changing the version during revocation, and down/up. A separate case confirms that stale registration C1 stops the migration without partial changes. `TestPostgresMigrations` continues to cover migration 00009. Registration and email confirmation integration tests exercise the consent service through the API flow; `TestConsentGrants` covers the usecase separately from HTTP. Revocation and C4 invitation acceptance are not covered as business flows. The cleanup race with SQLSTATE 23001 is covered only by its mapping unit test because its window cannot be reproduced deterministically.
## Organization tests