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
+24 -23
View File
@@ -6,7 +6,7 @@
Репозиторий содержит Go HTTP-сервис с проверкой PostgreSQL, Redis и SeaweedFS, адаптеры кеша и S3-хранилища, React-каркас интерфейса с публичными страницами и двумя оболочками кабинетов с экранами-заготовками, отдельный Python ML-сервис с health/readiness маршрутами, два OpenAPI-контракта, codegen, Compose и конфигурацию мониторинга. Публичный health endpoint API находится под /api/v1/healthz. /healthz используется для проверки веб-контейнера. Внутренний /readyz Go проверяет PostgreSQL, Redis и доступность bucket SeaweedFS; /readyz ML проверяет готовность модели; ML отвечает 503 на readiness, пока inference не готов. Метрики Go доступны по стандартному /metrics на внутреннем порту.
Это технический каркас. В нем нет регистрации, ролей, профилей, тестов, грейдов, поиска, приглашений, загрузки/анализа резюме, PDF или интеграции с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
Регистрация и подтверждение email работают через API backend. Экраны регистрации и подтверждения во frontend остаются заглушками; вход и остальные перечисленные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md).
@@ -56,7 +56,7 @@ SeaweedFS работает отдельным сервером в основно
Реализовано. Frontend Nginx - единственная публичная HTTP-точка входа. Он отдает SPA, проксирует `/api/v1/` в Go и ограниченный `/telemetry`; любой другой путь, включая `/metrics`, `/readyz` и административные пути других сервисов, отклоняется с 404. Там же заданы заголовки безопасности, строгий CSP только для того же origin, лимит тела по умолчанию 1 МБ с ответом 413 в формате problem из контракта и грубые `limit_req`/`limit_conn` на клиента (429 с `Retry-After`); значения намного выше обычного использования и не заменяют доменные квоты, которые остаются в backend. Подробности и проверки - в [DEPLOY.md](DEPLOY.md#публичный-периметр-и-адрес-клиента).
Адрес клиента определяется только через доверенные прокси. Edge заменяет `X-Forwarded-For`; app Nginx доверяет адресу туннеля edge и передает backend одну найденную запись; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) доверяет `X-Forwarded-For` только от `TRUSTED_PROXY_CIDRS` (по умолчанию только закрепленный адрес frontend контейнера) и читает его справа, поэтому запись, которую клиент поставил слева от первого недоверенного узла, не учитывается. Сценарии и обработчики, которым нужен адрес для лимитера, читают его через `middleware.ClientAddr(ctx)` и строят ключ лимитера через `middleware.LimiterKey` (IPv6 сводится к /64). Адрес не логируется и не хранится дольше окна лимитера; в журнале запросов и метриках для него нет поля. Первый потребитель - лимиты регистрации и повторной отправки (см. раздел о регистрации); роутер подключает `ClientIP`.
Адрес клиента определяется только через доверенные прокси. Edge заменяет `X-Forwarded-For`; app Nginx доверяет адресу туннеля edge и передает backend одну найденную запись; `middleware.ClientIP` (`backend/internal/adapter/primary/http/middleware/clientip.go`) доверяет `X-Forwarded-For` только от `TRUSTED_PROXY_CIDRS` (по умолчанию только закрепленный адрес frontend контейнера) и читает его справа, поэтому запись, которую клиент поставил слева от первого недоверенного узла, не учитывается. Сценарии и обработчики, которым нужен адрес для лимитера, читают его через `middleware.ClientAddr(ctx)` и строят ключ лимитера через `middleware.LimiterKey` (IPv6 сводится к /64). Адрес не логируется и не хранится дольше окна лимитера; в журнале запросов и метриках для него нет поля. Лимиты по адресу клиента используют регистрация, повторная отправка и подтверждение email (см. раздел о регистрации); роутер подключает `ClientIP`.
### Закрытое файловое хранилище
@@ -234,7 +234,7 @@ Offsets и партиции. Каждый обработчик - один уча
### Доставки писем
Реализовано: агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован; см. [Квоты почты](#квоты-почты). Реализовано: worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода и отправка продуктовых уведомлений с проверкой разрешений перед отправкой. Gauges состояний доставки реализованы; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Ни один продуктовый сценарий пока не вызывает `MailRequester`, и ни один сценарий identity пока не вызывает `ServiceMailer` (регистрация и сброс пароля - отдельные задачи), поэтому сохраненное уведомление ждет, а служебных писем вне тестов нет.
Реализовано: агрегат `domain.Delivery`, `domain.MailContent` и `domain.MailRequest` (`backend/internal/domain/delivery.go`, `mail_content.go`, `mail_request.go`), порты `outbound.DeliveryRepository` и `outbound.MailRequestRepository` (`port/outbound/delivery.go`) через `UnitOfWork.Deliveries()`, `UnitOfWork.MailRequests()` и `postgres.DeliveryStore`, миграция `00006_create_deliveries.sql` с таблицами `mail_requests`, `deliveries` и `delivery_attempts`, запросы в `backend/db/queries/delivery.sql`, а в `backend/internal/usecase/notification/` usecase запроса `MailRequester` и обработчик `DeliveryHandler`. Шлюз квот, который допускает или откладывает отправку, реализован; см. [Квоты почты](#квоты-почты). Реализовано: worker, который берет к отправке служебные письма, проверяет их токен и аккаунт, пропускает через шлюз квот и вызывает `MailSender`, вместе с миграцией `00012_add_delivery_sending.sql`; см. [Отправка служебной почты](#отправка-служебной-почты). Запланировано: повторы и политика неизвестного исхода и отправка продуктовых уведомлений с проверкой разрешений перед отправкой. Gauges состояний доставки реализованы; см. [Метрики, телеметрия и alerts](#метрики-телеметрия-и-alerts). Продуктовые сценарии пока не вызывают `MailRequester`, поэтому запросы уведомлений ждут отправки. Регистрация и повторная отправка создают письма подтверждения через `ServiceMailer`; сброс пароля не реализован.
Доставка - устойчивое состояние отправки одного письма одному получателю. Строка `deliveries` содержит:
@@ -254,7 +254,7 @@ Offsets и партиции. Каждый обработчик - один уча
Почему событие несет только ссылку. События хранятся в `outbox_events` и в Kafka в пределах retention топика, а правило доменных событий разрешает только идентификаторы и минимальные факты. FR19 также требует, чтобы очередь не сохраняла доступ к отозванным данным. Поэтому текст лежит в `mail_requests`, которые удаление аккаунта убирает каскадно, и только пока он нужен: обработчик удаляет строку в той же транзакции, где сохраняет сформированную доставку. После этого текст есть только в доставке, с ее правилами хранения и доступа. Адрес обработчик читает из аккаунта в своей транзакции, поэтому это адрес, актуальный на момент создания.
Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном создают сценарии identity прямо в транзакции, которая выпускает токен, через `ServiceMailer`: он использует `domain.NewDelivery` и `DeliveryRepository.Create` и привязывает доставку к токену; сами сценарии identity, которые его вызывают (регистрация, повторная отправка, сброс), - отдельные задачи.
Письма с токеном. Тела писем подтверждения почты и сброса пароля содержат одноразовый bearer-токен, который никогда не должен попадать в событие или строку запроса, а хранилище держит только его SHA-256. Поэтому `mail_requests` и версия схемы 1 допускают только вид `notification`. Доставки писем с токеном создают сценарии identity прямо в транзакции, которая выпускает токен, через `ServiceMailer`: он использует `domain.NewDelivery` и `DeliveryRepository.Create` и привязывает доставку к токену. Регистрация и повторная отправка создают письма подтверждения; сброс пароля относится к будущему сценарию.
Неизменяемое содержимое. Доставка хранит отрендеренное тело и никогда не рендерит его заново. Для рендеринга во время отправки нужен исходный токен, который существует только в памяти в момент выпуска, а повтор под тем же ключом идемпотентности должен повторить ровно то же тело: Resend считает измененное тело под старым ключом конфликтом. Domain пересчитывает hash содержимого при каждом чтении и при несовпадении возвращает `domain.ErrMailContentIntegrity`. Trigger `deliveries_refuse_content_change` отклоняет UPDATE, меняющий получателя, содержимое, ключ идемпотентности, исходное событие или время создания (SQLSTATE 23000, ограничение `deliveries_content_immutable`, адаптер переводит его в `outbound.ErrDeliveryContentImmutable`). Поэтому новая версия шаблона применяется только к новым доставкам, а для отправки сохраненной доставки старые файлы шаблона не нужны.
@@ -342,13 +342,13 @@ Offsets и партиции. Каждый обработчик - один уча
### Отправка служебной почты
Реализовано: usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Не реализовано: отправка продуктовых уведомлений, политика повторов и неизвестного исхода и сценарии identity, которые вызывают `ServiceMailer`.
Реализовано: usecase отправки `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), usecase постановки `ServiceMailer` (`service_mail.go`), минимальное расписание повторов `RetryPolicy` (`send_retry.go`), `Delivery.CheckServiceMail` и `Delivery.Cancel` с причинами отмены (`backend/internal/domain/delivery.go`, `delivery_guard.go`), цикл в `backend/internal/worker/mailsender/`, входящий порт `inbound.MailPass` (`port/inbound/mail_sender.go`), методы репозитория `ClaimDue`, `ReleaseClaim`, `Cancel` и `ServiceMailState`, миграция `00012_add_delivery_sending.sql`, gauge `lincodex_mail_sender_running` и подключение в `bootstrap/mail_sender.go`. Регистрация ставит письмо подтверждения в очередь, а `ConfirmEmail` погашает ссылку. Не реализованы: отправка продуктовых уведомлений и сценарий сброса пароля.
Область. Worker берет только виды `verification` и `password_reset`. Продуктовое уведомление он не берет никогда, в каком бы состоянии оно ни было. Служебной почте не нужна запись согласия ни для какого назначения: она часть сценария аккаунта, поэтому ничто не читает журнал согласий, а C2 (публикация карточки кандидата) и остальные продуктовые согласия не участвуют. Между аккаунтом и письмом стоит проверка ниже, а не согласие.
Постановка. `ServiceMailer.EnqueueVerification` и `EnqueuePasswordReset` выполняются в транзакции, которая вставляет токен, и получают запись токена, исходный токен, адрес получателя и срок действия в часах. Они проверяют, что назначение токена подходит письму, один раз рендерят письмо текущей версией шаблона и сохраняют доставку `pending`, привязанную к токену (`email_token_id`), с ID токена в роли ID доставки. Повторный вызов для того же токена ничего нового не сохраняет, а сохраненное тело остается прежним.
Ссылки. Токен передается только во фрагменте URL: `<APP_PUBLIC_URL>/verify-email#token=<token>` и `<APP_PUBLIC_URL>/reset-password#token=<token>`; ссылки строит `mailtemplate` (`tokenLink`). Браузер никогда не отправляет фрагмент серверу, поэтому токен не попадает в access log nginx, который пишет `$uri`, в заголовки Referer и в журнал запросов Go; его нет ни в пути, ни в query. Маршрут frontend читает фрагмент и отправляет токен в теле запроса API. Query понадобился бы, только если бы маршрут frontend не мог прочитать фрагмент, но тогда страница отправляла бы токен дальше, а access log его видел бы, поэтому выбран фрагмент. Renderer отклоняет токен в любом другом месте, golden-файлы и тесты фиксируют формат, а тесты доставок проверяют, что сохраненное тело содержит ссылку с фрагментом и не содержит `?token=`. Тело в `deliveries` хранит действующий токен, пока письмо не отправлено или не отменено; см. "Персональные данные в хранилище".
Ссылки. Токен передается только во фрагменте URL: `<APP_PUBLIC_URL>/verify-email#token=<token>` и `<APP_PUBLIC_URL>/reset-password#token=<token>`; ссылки строит `mailtemplate` (`tokenLink`). Браузер никогда не отправляет фрагмент серверу, поэтому токен не попадает в access log nginx, который пишет `$uri`, в заголовки Referer и в журнал запросов Go; его нет ни в пути, ни в query. Экран подтверждения frontend пока остается заглушкой. Клиент должен прочитать токен из фрагмента, удалить его и после явного действия пользователя отправить токен вместе с паролем регистрации. Маршрут и API сброса пароля не реализованы. Renderer отклоняет токен в любом другом месте, golden-файлы и тесты фиксируют формат, а тесты доставок проверяют, что сохраненное тело содержит ссылку с фрагментом и не содержит `?token=`. Тело в `deliveries` хранит действующий токен, пока письмо не отправлено или не отменено; см. "Персональные данные в хранилище".
Один проход `ServiceMailSender.ProcessNext` проводит одну доставку через три шага:
@@ -534,11 +534,11 @@ backend/
Доменные типы лежат непосредственно в `backend/internal/domain/`: `user.go`, `candidate.go` и другие файлы по мере определения моделей. Вложенных каталогов по сущностям или модулям здесь нет. Первый тип - `DomainEvent` в `domain_event.go`: проверенное событие, которое транзакция записывает в outbox. Типы хранения identity лежат в `email_address.go`, `secret_token.go`, `user.go`, `email_token.go` и `session.go`; нормализованный пароль - в `password.go`. Типы журнала согласий лежат в `consent.go`. Типы организации, проверки и членства лежат в `organization.go` и `membership.go`. Продуктовая политика и ее версии лежат в `policy.go`, `policy_document.go`, `policy_version.go` и `policy_demo.go`.
`domain/`, продуктовые `usecase/`, адаптеры SMTP и FSP, а также продуктовые задания worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
За пределами реализованных потоков identity и согласий доменные типы и usecase других продуктовых сценариев пока не реализованы. Адаптеры SMTP и FSP, а также продуктовые задания worker остаются планом. `main.go` запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend renderer шаблонов писем и worker отправки служебной почты identity, который пока не питает ни один сценарий аккаунта. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, relay outbox, который публикует зафиксированные события в Kafka через адаптер franz-go, runtime обработчиков событий с обработчиком `notification_delivery`, runtime заданий по сроку (`worker/jobrunner`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки и подтверждения identity, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверкой пароля в регистрации и подтверждении, Redis cache adapter, S3-адаптер SeaweedFS с общим закрытым файловым слоем поверх него, порт `MailSender` с транспортами `disabled` и Resend, renderer шаблонов писем и worker отправки служебной почты identity для регистрации и повторной отправки. Вход и сессии, резюме, оценивание, приглашения, продуктовые виды заданий, файловые сценарии, отправка продуктовых уведомлений, транспорт SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; `ServiceMailer` рендерит им письма подтверждения и сброса пароля, когда usecase identity выпускают токен, а сами эти usecase (регистрация, повторная отправка, сброс) - отдельные задачи. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. В `pkg/testutil/` находится `FakeClock` - потокобезопасные ручные часы, которые тесты worker, интеграционные тесты и будущие тесты usecase подставляют везде, где production-код принимает часы `func() time.Time`, и `FindPersonalIdentifiers`, которым тесты метрик ищут в выдаче значения, похожие на email и UUID. Пакет `mailer` остается кандидатом. Шаблоны писем находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования. Обработчик доставки в `internal/usecase/notification/` рендерит им уведомления; `ServiceMailer` создает письма подтверждения при регистрации и повторной отправке. Письма сброса пароля относятся к будущему потоку сброса. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`api/` хранит контракты и инструменты и не является runtime hop в пути запроса. `api/core/` и `api/ml/` владеют исходным OpenAPI, fragments маршрутов и компонентов, а также коммитируемыми bundles. Схемы объединяет корневой `scripts/`. Сгенерированный Go-код лежит у потребителя: публичный handler - в `backend/internal/adapter/primary/http/api/`, внутренний ML client - в `backend/internal/adapter/secondary/ml/api/`, sqlc output - в `backend/internal/adapter/secondary/postgres/sqlc/`. Первый пакет монтируется в chi; два последних реализуют outbound adapters. `backend/cmd/app/main.go` остается точкой входа, а bootstrap отвечает за wiring и graceful shutdown.
@@ -646,16 +646,16 @@ contact_grant относится к паре кандидат-компания
### Хранение identity
Реализовано только хранение: миграция `backend/db/migrations/00002_create_identity_tables.sql`, запросы в `backend/db/queries/identity.sql`, доменные типы в `backend/internal/domain/`, порты в `backend/internal/port/outbound/identity.go` и адаптер на sqlc в `backend/internal/adapter/secondary/postgres/identity.go`. Регистрация, подтверждение, вход и сессии из [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf) запланированы; ни один usecase или обработчик это хранение пока не использует.
Хранение identity реализовано миграцией `backend/db/migrations/00002_create_identity_tables.sql`, запросами `backend/db/queries/identity.sql`, доменными типами, outbound-портами и адаптером Postgres. Backend API реализует регистрацию, повторную отправку подтверждения и `ConfirmEmail`. Экраны регистрации и подтверждения во frontend остаются заглушками; вход и сессии пока не реализованы; см. [контракт API](../../api/README.md#identity-сессии-cookie-и-csrf).
- `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр.
- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. CHECK допускает не больше одного из consumed и invalidated.
- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. Миграция 00014 добавляет `pending_password_hash`, `pending_scenario` и `pending_onboarding_step`, чтобы каждый токен нес данные своей регистрации. CHECK допускает не больше одного из consumed и invalidated.
- `sessions`: UUIDv7 `id`, который не покидает сервер, `token_hash` (SHA-256 значения cookie, уникальный), `user_id`, `created_at`, `last_seen_at`, абсолютный `expires_at` и `revoked_at`. IP-адрес и user agent не хранятся.
- Токены и сессии ссылаются на `users` с `ON DELETE CASCADE`. Записи согласий ссылаются на него с `ON DELETE RESTRICT`; см. [Журнал согласий](#журнал-согласий). CHECK-ограничения дублируют доменные правила как последнюю защиту: ASCII-адрес и его ключ, формат PHC и времена (подтверждения, погашения, аннулирования и отзыва) не раньше `created_at`.
Решения:
- Email-адреса принимаются только в ASCII, потому что отправка почты не поддерживает SMTPUTF8. `domain.NewEmailAddress` отклоняет любой символ вне ASCII, включая гомоглифы и полноширинные формы, с `ErrInvalidEmailAddress`; обработчик регистрации должен отвечать на это 400 `validation_failed` независимо от того, существует ли аккаунт. Интернационализированные домены принимаются только в punycode (`xn--...`). Ключ переводит в нижний регистр только A-Z; база проверяет его через `translate()`, который, в отличие от `lower()`, не зависит от collation. Поддержка Unicode-адресов - будущая работа: нужны IDNA ToASCII для домена, правило для Unicode в local part и доставка через SMTPUTF8. Строки читаются через `domain.RestoreEmailAddress`, который проверяет только соответствие адреса и ключа, поэтому более строгое правило в будущем не сделает существующие аккаунты нечитаемыми.
- Email-адреса принимаются только в ASCII, потому что отправка почты не поддерживает SMTPUTF8. `domain.NewEmailAddress` отклоняет любой символ вне ASCII, включая гомоглифы и полноширинные формы, с `ErrInvalidEmailAddress`; обработчик регистрации отвечает на это 400 `validation_failed` независимо от того, существует ли аккаунт. Интернационализированные домены принимаются только в punycode (`xn--...`). Ключ переводит в нижний регистр только A-Z; база проверяет его через `translate()`, который, в отличие от `lower()`, не зависит от collation. Поддержка Unicode-адресов - будущая работа: нужны IDNA ToASCII для домена, правило для Unicode в local part и доставка через SMTPUTF8. Строки читаются через `domain.RestoreEmailAddress`, который проверяет только соответствие адреса и ключа, поэтому более строгое правило в будущем не сделает существующие аккаунты нечитаемыми.
- База хранит хеши, а не пароли и исходные токены. Токен несет 256 бит из crypto/rand, поэтому SHA-256 без соли нельзя обратить перебором, а поиск остается одним обращением к индексу; для паролей нужен медленный KDF Argon2id. `bytea` вдвое компактнее hex-текста, допускает точную проверку длины и не имеет вариантов регистра. `domain.SecretToken`, `domain.PasswordHash` и `domain.EmailAddress` скрывают значение в выводе `fmt` (для любого verb) и `slog`, поэтому при печати `domain.User` не видны ни адрес, ни хеш; настоящие значения возвращают явные методы доступа. Неотображенные ошибки PostgreSQL из репозиториев identity сохраняют только SQLSTATE и имя ограничения, потому что текст и detail ошибки могут содержать значения строки.
- Колонки с перечислимыми значениями - text с CHECK, а не enum-типы PostgreSQL. Новый сценарий, шаг или назначение заменяет одно ограничение в обратимой миграции; значение enum нельзя удалить и нельзя использовать в транзакции, которая его добавила.
- Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, поэтому сроки и проверки по ним используют одни часы. Репозитории отклоняют нулевое время.
@@ -682,18 +682,18 @@ contact_grant относится к паре кандидат-компания
- `Verify` строго разбирает сохраненную строку PHC, заново вычисляет ключ с сохраненными параметрами, солью и длиной ключа и сравнивает за постоянное время. Неверный пароль возвращает `outbound.ErrPasswordMismatch`. Некорректный хеш или хеш вне границ для сохраненных значений (память от 8 KiB на lane до 128 MiB и в пределах бюджета хеширования, от 1 до 16 проходов, от 1 до 16 lanes, соль 8-64 байта, digest 16-64 байта) возвращает `outbound.ErrPasswordHashCorrupt` без вычисления, поэтому подделанная строка не может потребовать неограниченную память или время. `ErrPasswordHashCorrupt` оборачивает `domain.ErrInvalidPasswordHash`, который репозиторий возвращает для сохраненного хеша, не прошедшего `domain.NewPasswordHash`. При совпадении `needsRehash` сообщает, что параметры, соль или длина ключа отличаются от текущих, и вход может сохранить новый хеш.
- `VerifyDummy` выполняет `Verify` для хеша с текущими параметрами, случайной солью и случайным digest и возвращает `ErrPasswordMismatch` (или ошибку контекста). Вход будет вызывать его для неизвестного email, поэтому обе ветки одинаково разбирают хеш, ждут память, вычисляют и сравнивают.
- Вход должен отвечать `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также должен записать ошибку в лог и вызвать `VerifyDummy`. Оставшиеся различия во времени: поврежденный хеш отклоняется без вычисления, что компенсирует `VerifyDummy`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует.
- `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация будет вызывать его в каждой ветке до поиска email.
- `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация вызывает его во всех ветках до поиска email.
- Ошибки и логи никогда не содержат пароль или хеш. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken` и `domain.EmailAddress` скрывают значение в выводе `fmt`, `slog` и JSON и хранят его за указателем, поэтому при печати внешней структуры, даже через неэкспортируемое поле, виден только адрес.
### Журнал согласий
Реализованы хранение, порты и контракт чтения: миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Выдача C1-C3 и C5 с проверкой актуальной версии реализована как usecase `consent.Service` (см. [Usecase согласий](#usecase-согласий)). Отзыв с последствиями и HTTP-обработчик, C1 в транзакции регистрации и C4 при принятии приглашения запланированы; ни один продуктовый поток пока не вызывает usecase.
Реализованы хранение, порты, контракт чтения и выдача согласий через `consent.Service`: миграция `backend/db/migrations/00009_create_consent_ledger.sql`, запросы в `backend/db/queries/consents.sql`, доменные типы в `backend/internal/domain/consent.go`, порты в `backend/internal/port/outbound/consents.go`, адаптер на sqlc в `backend/internal/adapter/secondary/postgres/consents.go` и `ListMyConsents` в публичном контракте ([api/README.md](../../api/README.md#согласия)). Регистрация записывает C1 через `GrantAtRegistration` в транзакции создания или повторной регистрации; подтверждение проверяет C1 той же версии регистрации, что и токен. HTTP выдача и отзыв согласий, последствия отзыва и C4 при принятии приглашения пока не реализованы.
Согласия C1-C5 из PRD FR01 - независимые цели: выдача или отзыв одной цели никогда не меняет другую.
`consent_texts` хранит опубликованные тексты: `purpose`, `version` (`ConsentTextVersion` контракта), точный `body`, `body_sha256`, который CHECK сверяет с текстом, `kind` (`demo` - синтетический текст без юридической проверки, `operator` - текст фактического оператора) и `published_at`. Актуальный текст цели - последняя публикация не позже времени выдачи. Тексты неизменяемы: триггер запрещает UPDATE, DELETE и TRUNCATE (`consent_texts_immutable`), а измененный текст - новая версия. Миграция публикует демо-версию `cN-2026-10-01` каждой цели; тексты оператора появятся новыми версиями в следующей миграции до приема реальных данных (PRD 7.3). Плейсхолдер `{organization}` есть только в тексте C4; его заполняет `ConsentText.RenderForOrganization`.
`consent_records` - журнал только на добавление. Одна строка на выдачу: UUIDv7 `id`, `subject_id`, `purpose`, `text_version`, `text_hash` (SHA-256 ровно того текста, который видел субъект, 32 байта), `source` (`registration` только для C1, `consent_settings` для C1-C3 и C5, `invitation_acceptance` только для C4), `granted_at` и однократная отметка отзыва `revoked_at` с `revocation_source` (`consent_settings` или `support_request`). У строки C4 есть еще `organization_id`, `organization_name` (название, которое было в показанном тексте, снимок длиной 1-200 символов), канонический `field_set` (от одного до четырех разных значений `ContactFieldKind` по возрастанию байтов), `invitation_id` и `invitation_terms_version`; у остальных целей они обязаны быть NULL (`consent_records_c4_scope`). Метаданные запроса, например IP-адрес или user agent, не хранятся: PRD требует версию, хэш, время, субъекта и событие отзыва, а лишние данные были бы персональными данными без цели.
`consent_records` - журнал только на добавление. Одна строка на выдачу: UUIDv7 `id`, `subject_id`, `purpose`, `text_version`, `text_hash` (SHA-256 ровно того текста, который видел субъект, 32 байта), `source` (`registration` только для C1, `consent_settings` для C1-C3 и C5, `invitation_acceptance` только для C4), `registration_version` только для C1 с источником `registration`, `granted_at` и однократная отметка отзыва `revoked_at` с `revocation_source` (`consent_settings` или `support_request`). У строки C4 есть еще `organization_id`, `organization_name` (название, которое было в показанном тексте, снимок длиной 1-200 символов), канонический `field_set` (от одного до четырех разных значений `ContactFieldKind` по возрастанию байтов), `invitation_id` и `invitation_terms_version`; у остальных целей они обязаны быть NULL (`consent_records_c4_scope`). Метаданные запроса, например IP-адрес или user agent, не хранятся: PRD требует версию, хэш, время, субъекта и событие отзыва, а лишние данные были бы персональными данными без цели.
Решения:
@@ -702,6 +702,7 @@ contact_grant относится к паре кандидат-компания
- Отзыв. `ConsentLedger.Revoke` ставит отметку на все неотозванные строки цели, включая `superseded`, а для C4 - только на строки одной организации. Повтор ничего не находит и сохраняет первую отметку. Время отзыва раньше времени выдачи строки, из-за расхождения часов между экземплярами, записывается временем выдачи (`greatest`), поэтому CHECK `consent_records_revocation_stamp` остается последней защитой. Последствия отзыва (запрос удаления для C1, закрытие публикации и grants для C2 и C4, ручной путь для C3, остановка импорта для C5) относятся к отзыву согласий и не реализованы.
- Хранение и удаление. PRD 7.3 планирует хранить согласия три года, и это может быть дольше жизни аккаунта, поэтому `subject_id` ссылается на `users` с `ON DELETE RESTRICT`, а триггер BEFORE DELETE запрещает удалять строку подтвержденного аккаунта (`consent_records_retained`). Строки неподтвержденного аккаунта удалять можно, потому что регистрация, которую владелец адреса не подтвердил, не доказывает чье-либо согласие: очистка неподтвержденных аккаунтов удаляет строки удаляемых аккаунтов в том же запросе, а `UpdateRegistration` удаляет регистрационное C1 повторно регистрируемого аккаунта (см. ниже). TRUNCATE не вызывает строковый триггер и остается разрешенным для изоляции тестов. Оставит ли удаленный аккаунт журнал, tombstone или ничего, решают запрос удаления по C1 и процедура удаления аккаунта, которая его исполняет и пока не имеет задачи в MVP; правило хранения расширит условие удаления своей миграцией.
- Повторная регистрация. Неподтвержденный аккаунт сохраняет `users.id`, когда тот же email регистрируется снова, поэтому иначе C1 прежнего регистранта стояло бы за новым. Запрос `UpdateUserRegistration` удаляет строки C1 с источником `registration` обновляемого аккаунта, и только если обновление применилось. Это обязательное требование для регистрации: usecase регистрации вызывает `UpdateRegistration` и записывает новое C1 через `consent.Service.GrantAtRegistration` строго после `UpdateRegistration` в той же транзакции (см. [Usecase согласий](#usecase-согласий)).
- Версия регистрации для C1. Миграция `00016_bind_registration_consent.sql` добавляет `registration_version` только к C1 с источником `registration`; другие согласия обязаны оставить поле NULL. Она заполняет старые C1 текущей версией аккаунта, не используя токены. Предыдущая регистрационная C1 удаляется при повторной регистрации, поэтому более старая дата выдачи или несколько активных регистрационных C1 на аккаунт считаются несогласованными данными и останавливают миграцию. Частичный уникальный индекс `consent_records_registration_version_key` разрешает не более одной неотозванной регистрационной C1 для аккаунта и версии. Триггер вставки подставляет текущую версию, если старый backend не передал поле, и отклоняет несовпадение у нового; триггер неизменяемости защищает версию и при отзыве.
- C2 и набор публикуемых полей. Строка C2 доказывает согласие с текстом публикации, а не то, какие поля опубликованы. Набор опубликованных полей и его изменения хранятся со временем и записью C2 за каждым в истории видимости кандидата (`candidate_publications` и `candidate_privacy_events`, см. [Видимость кандидата](#видимость-кандидата)). Добавить scope полей в строки C2 позже - аддитивное изменение миграции и контракта.
- C4 в бизнес-транзакции. `UnitOfWork.ConsentLedger().GrantContact` принимает `domain.ContactConsentGrant`, который строит только `domain.NewContactConsentGrant` и который требует текст C4, организацию и ее название, непустой набор полей, приглашение и его версию условий; `domain.NewConsentGrant` отклоняет C4. Принятие приглашения вызывает его в транзакции, которая переводит приглашение в `accepted`, создает grant и пишет событие аудита, поэтому все это фиксируется или откатывается вместе. Повторное принятие получает существующую запись с `created` false и сравнивает ее scope; для приглашения, чье C4 принадлежит другому субъекту, возвращается `ErrConsentInvitationTaken`.
- Гонка очистки. Очистка проверяет строки согласий в снимке своего запроса. Согласие, зафиксированное для аккаунта-кандидата после этого снимка, но до блокировки аккаунта, нарушает ограничивающий внешний ключ в конце запроса (SQLSTATE 23001); адаптер возвращает его как `ErrTransactionConflict`, ничего не удаляется, а следующий запуск видит согласие.
@@ -717,9 +718,9 @@ contact_grant относится к паре кандидат-компания
### Usecase согласий
Реализовано: `consent.Service` в `backend/internal/usecase/consent/`. В bootstrap он пока не подключен, потому что его не вызывает ни обработчик, ни регистрация; первый вызывающий код создаст его через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании, поэтому ошибка сборки видна при старте, а не при первой выдаче.
`consent.Service` в `backend/internal/usecase/consent/` подключен через bootstrap и используется регистрацией для проверки версии текста и выдачи C1 в транзакции создания или повторной регистрации. Экземпляр создается через `consent.NewService(transactor, clock)` с `Transactor` и часами приложения, которые получают остальные usecase. Нулевой transactor или часы вызывают панику при создании.
- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, version)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста.
- Точки входа фиксируют источник. `GrantAtRegistration(ctx, repositories, subjectID, registrationVersion, textVersion)` записывает C1 с источником `registration`; `GrantInSettings(ctx, repositories, SettingsGrantInput)` записывает C1, C2, C3 или C5 с источником `consent_settings`. Ни одна не принимает источник или время, поэтому обработчик не может взять их от клиента. `repositories` - это `outbound.ConsentRepositories`: если передать `UnitOfWork` бизнес-операции, выдача фиксируется или откатывается вместе с ней. Регистрация создает аккаунт и записывает C1 в одной транзакции только по ID субъекта, поэтому сессия не нужна. `GrantInSettingsInNewTransaction` открывает собственную транзакцию для выдачи вне другой операции и повторяет `ErrTransactionConflict` до трех попыток всего с короткой случайной паузой (10 мс плюс до 10 мс) между ними; это безопасно, потому что повтор идемпотентен, а пауза прерывается сразу при отмене контекста.
- Порядок при повторной регистрации. Для неподтвержденного аккаунта, который регистрируется снова, вызывайте `GrantAtRegistration` строго после `UserRepository.UpdateRegistration` в той же транзакции. `UpdateRegistration` удаляет регистрационное C1 прежнего регистранта, а выдача, выполненная до него, нашла бы эту запись, вернула ее с `Created` false и после удаления оставила бы аккаунт без C1. Интеграционный тест показывает оба порядка.
- Проверка версии до ветвления по email. `CheckTextVersion(ctx, repositories, purpose, version)` возвращает актуальный текст, если `version` актуальна, а иначе завершается как выдача, ничего не записывая. Регистрация обязана вызвать ее с C1 и присланной версией до ветвления на новый или существующий email; иначе устаревшая версия отклонялась бы только для новых адресов, и разница выдала бы, какие аккаунты существуют.
- Только актуальный текст. Выдача читает `ConsentTexts().Current` на время приложения и отклоняет любую другую версию ошибкой `*StaleConsentTextError`, которая совпадает с `ErrStaleConsentText` и содержит цель, запрошенную и актуальную версии, поэтому обработчик может сопоставить ее одному коду problem и показать новый текст. Устаревшая версия, версия, которая запланирована, но еще не опубликована, и версия, которой никогда не было, считаются устаревшими. Журнал принимает любую опубликованную версию, поэтому именно эта проверка не пускает выдачу устаревшего текста. Проверка и вставка не блокируются от публикации между ними: тексты публикуют миграции, а выдача, назвавшая актуальный текст на момент проверки, допустима.
@@ -731,23 +732,23 @@ contact_grant относится к паре кандидат-компания
- Ошибки сохраняют идентичность: устаревшая версия, `ErrScopedConsentRequired`, `ErrUserNotFound`, `ErrConsentTextNotFound` (у цели нет опубликованного текста), `ErrConsentInvitationTaken`, `domain.ErrInvalidConsent` и `domain.ErrInvalidConsentText`. Действия требует `outbound.ErrTransactionConflict`: журнал возвращает его, не прерывая транзакцию, когда запись повтора была отозвана между вставкой и выборкой. Вызывающий код внутри `UnitOfWork` обязан вернуть эту ошибку, откатить транзакцию и повторить всю операцию; `GrantInSettingsInNewTransaction` делает это сам. Сопоставление остальных ошибок с кодами problem - дело обработчиков.
- Демо-тексты требуют проверки перед выпуском. Тексты, которые публикует миграция, имеют вид `demo`: синтетические, без юридической проверки. Usecase не отличает их от текстов оператора, поэтому установка, принимающая реальные данные, записала бы согласие на демо-текст. До приема реальных данных (PRD 7.3) проверка перед выпуском должна убедиться, что актуальный текст каждой цели имеет вид `operator`; владелец - проверка перед выпуском или отзыв согласий, и ни той, ни другой пока нет.
### Регистрация и повторная отправка подтверждения
### Регистрация, подтверждение и повторная отправка
Реализовано: `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/identity.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`.
Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт.
Отложенные учетные данные (защита от pre-hijack). Каждая регистрация, первая и каждая повторная, хранит хеш пароля, сценарий и первый шаг онбординга на своем токене подтверждения (столбцы `pending_*` таблицы `email_tokens`, миграция 00014). Повторная регистрация неподтвержденного адреса никогда не меняет учетные данные, сценарий и шаг онбординга строки `users`: `UserRepository.AdvanceRegistration` только увеличивает версию регистрации и время регистрации (и удаляет C1 прежней регистрации), а новый токен несет новые отложенные данные. Повторная отправка копирует отложенные данные новейшего токена регистрации. `password_hash`, `scenario` и `onboarding_step` строки неподтвержденного аккаунта не авторитетны, пока подтверждение не применит отложенные данные нажатого токена: в них значения первого регистранта лишь потому, что столбцы обязательны, и никакой код не вправе по ним аутентифицировать или им доверять (см. комментарий к `domain.User`). Аннулирование токена (`InvalidateActive`) очищает его столбцы `pending_*`, а CHECK не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает. Требования для передачи следующим задачам:
Отложенные учетные данные (защита от pre-hijack). Каждая регистрация, первая и каждая повторная, хранит хеш пароля, сценарий и первый шаг онбординга на своем токене подтверждения (столбцы `pending_*` таблицы `email_tokens`, миграция 00014). Повторная регистрация неподтвержденного адреса никогда не меняет учетные данные, сценарий и шаг онбординга строки `users`: `UserRepository.AdvanceRegistration` только увеличивает версию регистрации и время регистрации (и удаляет C1 прежней регистрации), а новый токен несет новые отложенные данные. Повторная отправка копирует отложенные данные новейшего токена регистрации. `password_hash`, `scenario` и `onboarding_step` строки неподтвержденного аккаунта не авторитетны, пока подтверждение не применит отложенные данные нажатого токена: в них значения первого регистранта лишь потому, что столбцы обязательны, и никакой код не вправе по ним аутентифицировать или им доверять (см. комментарий к `domain.User`). Аннулирование токена (`InvalidateActive`) очищает его столбцы `pending_*`, а CHECK не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает.
- Подтверждение почты (`ConfirmEmail`): подтверждение токена применяет отложенные данные нажатого токена, и только их, к строке аккаунта в транзакции подтверждения (хеш пароля, сценарий, шаг онбординга) и обязано требовать пароль этой регистрации, чтобы подтвердить токен с отложенными данными, проверяя его по отложенному хешу токена. Тогда жертва, перешедшая по ссылке злоумышленника, не может принять его пароль, а злоумышленник не может подтвердить токен жертвы. Поля пароля в `EmailVerificationRequest` сегодня нет; его добавление - изменение контракта подтверждения почты, здесь не делается. Описание `RegisterAccount` в контракте по-прежнему говорит, что повторная регистрация заменяет хеш пароля аккаунта; при реализации подтверждения почты нужно исправить его вместе с этим изменением.
- Для подтверждения почты также нужны: тесты обоих порядков (злоумышленник регистрируется первым, жертва вторым, и наоборот), показывающие, что владелец никогда не получает пароль, который не выбирал; требовать, чтобы запись C1 существовала и относилась к версии регистрации подтверждаемого токена; отклонять токен без отложенных данных, без устаревшего пути в обход пароля; обнулять столбцы `pending_*` токена при его расходовании.
- Вход: неподтвержденный аккаунт никогда не входит. Вход отвечает как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не сравнивает пароль со строкой неподтвержденного аккаунта или с отложенными данными.
Подтверждение почты (`ConfirmEmail`) реализовано. Оно требует пароль, сохраненный для регистрации этого токена, и проверяет его по отложенному хешу. В одной транзакции backend проверяет текущую версию регистрации и запись C1, погашает токен, подтверждает адрес, переносит с токена на аккаунт хеш пароля, сценарий и шаг онбординга, очищает `pending_*` и записывает ровно одно событие `identity.email_verified` без секретов. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный, устаревший токен, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`; истекший токен дает `verification_token_expired`. Origin должен точно совпадать с `APP_PUBLIC_URL`. Подтверждение не создает сессию. Экран подтверждения во frontend пока остается заглушкой; вход и восстановление сессии еще не реализованы.
Планируемое поведение входа: неподтвержденный аккаунт не сможет войти. Вход будет отвечать как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не будет сравнивать пароль со строкой неподтвержденного аккаунта или с отложенными данными.
Порядок проверок регистрации: валидация всего тела и версии текста C1, проверка воспроизведения, лимит, хеш пароля (в каждой ветке, до чтения аккаунта), транзакция. Ошибка валидации (400) не зависит от хранимых аккаунтов и не расходует лимит.
Идемпотентность. Ключ ограничен `HMAC(secret, операция | ключ | нормализованный email)`, отпечаток запроса - `HMAC(secret, канонное тело)` (`identity.Keyring`, секрет `IDENTITY_KEY_SECRET`; обязателен; стенд разработки может задать `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, чтобы взять случайный на процесс, и тогда записи и счетчики теряются при перезапуске). Запись хранится в `idempotency_records` (миграция 00014) 24 часа и пишется в транзакции регистрации, поэтому видимая запись всегда относится к зафиксированной регистрации. Повтор с тем же ключом и телом воспроизводит нейтральный 202 и не расходует лимит; тот же ключ с другим телом дает 422 `idempotency_key_reused`. Параллельный одинаковый запрос ждет строку первого и затем воспроизводится, поэтому эта реализация никогда не отвечает 409 `idempotency_in_progress`. Каждая регистрация удаляет до 10 просроченных записей, поэтому таблица остается ограниченной без отдельного задания.
Лимиты (Redis, фиксированные окна, `outbound.RateLimiter`, `redis.Cache.Take`, один атомарный Lua-скрипт на вызов). Счетчики ключуются HMAC нормализованного адреса и считают каждый запрос независимо от того, есть ли аккаунт, поэтому 429 ничего не раскрывает об аккаунте. Регистрация и каждая повторная отправка делят счетчики адреса: не меньше `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между двумя письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за окно 24 часа, которое начинается с первого. Счетчик клиента `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час) ключуется `middleware.LimiterKey` от `ClientAddr`, хешируется секретом и пропускается, когда адрес неизвестен (общий бакет позволил бы одному клиенту заблокировать всех). Отклоненный запрос ничего не считает, отвечает 429 `rate_limited` с `Retry-After` в целых секундах с округлением вверх и не выпускает токен. Счетчики эфемерны: перезапуск Redis их сбрасывает, а квота почтового провайдера остается последней границей. Сбой Redis дает 500 и никогда не пропускает запрос. Ни адрес, ни токен не логируются.
Лимиты (Redis, фиксированные окна, `outbound.RateLimiter`, `redis.Cache.Take`, один атомарный Lua-скрипт на вызов). Счетчики ключуются HMAC нормализованного адреса и считают каждый запрос независимо от того, есть ли аккаунт, поэтому 429 ничего не раскрывает об аккаунте. Регистрация и каждая повторная отправка делят счетчики адреса: не меньше `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию 60 с) между двумя письмами и не больше `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию 5) за окно 24 часа, которое начинается с первого. Подтверждение ограничивает каждый токен пятью попытками в час. Счетчик клиента `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию 30 в час) ключуется `middleware.LimiterKey` от `ClientAddr`, хешируется секретом и пропускается, когда адрес неизвестен (общий бакет позволил бы одному клиенту заблокировать всех). Отклоненный вызов `Take` не увеличивает свой счетчик; если предыдущая проверка лимита прошла, ее счетчик уже учел попытку, даже когда следующая проверка отказала. Отказ отвечает 429 `rate_limited` с `Retry-After` в целых секундах с округлением вверх и не выпускает токен. Счетчики эфемерны: перезапуск Redis их сбрасывает, а квота почтового провайдера остается последней границей. Сбой Redis дает 500 и никогда не пропускает запрос. Ни адрес, ни токен не логируются.
Политика замены токена. Каждый выпуск токена подтверждения (регистрация, повторная регистрация, повторная отправка) сначала аннулирует все неиспользованные токены подтверждения аккаунта и затем сохраняет новый, поэтому одновременно работает не больше одной ссылки. Повторная отправка не меняет пароль, сценарий, запись согласия и версию регистрации, меняется только токен. Письмо аннулированного токена воркер отправки отменяет, поэтому доставляется только текущая ссылка. Срок жизни токена берется из продуктовой политики (`identity.verification_token_lifetime_hours`, 24 в демонстрационной версии), а не из конфигурации.
+8 -6
View File
@@ -74,7 +74,7 @@ Backend получает `KAFKA_BROKERS` - список адресов bootstrap
`PASSWORD_HASH_CONCURRENCY` задает бюджет памяти Argon2id в вычислениях по 64 MiB и четыре lanes каждое (от 1 до 4). Compose передает значение из `.env`, по умолчанию 1, потому что у backend-контейнера 1 CPU и 768 MB: второе вычисление только добавило бы 64 MiB, деля тот же CPU. Backend, запущенный напрямую без переменной, берет меньшее из 2 и GOMAXPROCS. Следующие регистрации и входы ждут память, пока не завершится контекст запроса. Compose также задает `GOMEMLIMIT=600MiB`, примерно 78% лимита контейнера, чтобы сборщик Go освобождал память завершенных вычислений раньше, чем контейнеру ее не хватит; меняйте его вместе с лимитом памяти. Значение читается и проверяется при старте; регистрация и вход начнут его использовать, когда будут реализованы. См. [ARCHITECTURE.md](ARCHITECTURE.md#хеширование-паролей).
`IDENTITY_KEY_SECRET` обязателен в production `.env` (не меньше 32 байт; сгенерируйте `openssl rand -base64 48` и храните неизменным между перезапусками и на всех экземплярах). Он ключует записи идемпотентности регистрации и счетчики лимитов; Compose не стартует без него, а backend не стартует без него, если не задан `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, который нужен только стендам разработки. Смена секрета забывает записи идемпотентности и счетчики за последние 24 часа. `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию `1m`), `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию `5`) и `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию `30`) ограничивают письма подтверждения на адрес и регистрации на клиента; пустое значение означает значение по умолчанию. Метрика `lincodex_identity_rate_limit_refusals_total{scope}` считает отказы; большая доля `scope="client"` намекает на сломанную цепочку прокси (см. `TRUSTED_PROXY_CIDRS`). См. [ARCHITECTURE.md](ARCHITECTURE.md#регистрация-и-повторная-отправка-подтверждения).
`IDENTITY_KEY_SECRET` обязателен в production `.env` (не меньше 32 байт; сгенерируйте `openssl rand -base64 48` и храните неизменным между перезапусками и на всех экземплярах). Он ключует записи идемпотентности регистрации и счетчики лимитов; Compose не стартует без него, а backend не стартует без него, если не задан `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, который нужен только стендам разработки. Смена секрета забывает записи идемпотентности и счетчики за последние 24 часа. `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию `1m`), `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию `5`) и `IDENTITY_CLIENT_HOURLY_LIMIT` (по умолчанию `30`) ограничивают письма подтверждения на адрес и запросы на клиента; пустое значение означает значение по умолчанию. Подтверждение также ограничено 5 попытками на токен в час. Метрика `lincodex_identity_rate_limit_refusals_total{scope}` считает отказы; большая доля `scope="client"` намекает на сломанную цепочку прокси (см. `TRUSTED_PROXY_CIDRS`). См. [ARCHITECTURE.md](ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка).
down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова.
@@ -235,7 +235,9 @@ Worker захватит его в течение одного интервала
Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются.
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. Процесс backend запускает worker отправки служебной почты identity (подтверждение почты и сброс пароля), когда `EMAIL_PROVIDER` равен `resend`; см. [Отправка служебной почты](#отправка-служебной-почты). Ни один сценарий аккаунта пока не создает такие письма, а продуктовые уведомления сохраняются как доставки, но не отправляются до реализации отправки продуктовых уведомлений, так что боевой стенд сегодня не отправляет ни одного письма.
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. При `EMAIL_PROVIDER=resend` backend запускает worker служебной почты identity (подтверждение почты и сброс пароля); регистрация ставит письмо подтверждения в очередь. Сброс пароля не реализован, а продуктовые уведомления сохраняются как доставки, но не отправляются до реализации их отправки. См. [Отправка служебной почты](#отправка-служебной-почты).
Совместимость выпуска: `ConfirmEmail` требует `token` и пароль, выбранный при соответствующей регистрации. Клиенты, которые отправляли только токен, нужно обновить. Миграция `00016_bind_registration_consent.sql` добавляет версию регистрации к C1 и заполняет ее для прежних записей по текущей версии аккаунта, без требования живого токена. Она проверяет, что регистрационная C1 не старше последней регистрации и что у аккаунта нет нескольких активных регистрационных C1; при несоответствии миграция останавливается без частичных изменений. Триггер заполняет версию, если старый backend не передал ее, и отклоняет несовпадающую версию от нового backend. Частичный уникальный индекс допускает не больше одной неотозванной регистрационной C1 на аккаунт и версию регистрации. Миграцию можно применить до обновления backend. При откате сначала верните старый backend, затем отмените миграцию. Новые переменные окружения не нужны. `APP_PUBLIC_URL` также задает Origin, который должен передавать запрос подтверждения.
`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов относятся к запланированному слою доставки, а ожидание сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт).
@@ -249,7 +251,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
| `EMAIL_TIMEOUT` | `10s` | Go duration от `1s` до `1m`; ограничивает одну попытку транспорта |
| `EMAIL_QUOTA_DAILY` | `100` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за UTC-сутки через настроенный аккаунт провайдера: целое от 1 до 1000000000. Пустое значение считается незаданным. Значения, которое отключает квоту, нет. |
| `EMAIL_QUOTA_MONTHLY` | `3000` для `resend` и `disabled`; для `smtp` значения по умолчанию нет, и там переменная обязательна | Получатели за календарный месяц UTC: целое от 1 до 1000000000, не меньше `EMAIL_QUOTA_DAILY`. Пустое значение считается незаданным. |
| `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. |
| `APP_PUBLIC_URL` | нет, обязательна | Публичный origin для ссылок в письмах и Origin запроса подтверждения: `https://host[:port]`, а `http` только для `localhost`, `127.0.0.1` или `[::1]`. Без учетных данных, пути, query и fragment; один завершающий `/` отбрасывается. |
| `RESEND_API_KEY` | пусто | Читается только для `resend` и там обязательна. Печатные ASCII символы без пробелов. Префикс `re_` из примеров Resend не проверяется. |
| `SMTP_HOST` | пусто | Читается только для `smtp` и там обязательна. Имя хоста или IP адрес без порта. |
| `SMTP_PORT` | пусто | Обязательна для `smtp`. Целое число от 1 до 65535. |
@@ -301,10 +303,10 @@ Compose передает эти переменные из корневого `.e
### Шаблоны писем
Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления, когда сохраняет доставку, а `ServiceMailer` рендерит письма подтверждения и сброса пароля, когда сценарий identity выпускает токен; сами сценарии (регистрация, подтверждение, сброс пароля) запланированы, поэтому ни один аккаунт пока не вызывает письмо.
Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Обработчик доставки рендерит им уведомления при сохранении доставки, а `ServiceMailer` создает письмо подтверждения при регистрации. Подтверждение email реализовано в API; экран подтверждения во frontend остается заглушкой. Сценарий сброса пароля еще запланирован.
- Шаблоны встроены в бинарник через `go:embed` и разбираются один раз при создании renderer; сломанный шаблон останавливает создание. У каждой версии три файла: `<kind>.v<N>.subject.tmpl`, `<kind>.v<N>.txt.tmpl` и `<kind>.v<N>.html.tmpl`. HTML часть использует `html/template`, текстовая часть и тема используют `text/template`. Любой транспорт отправляет один и тот же результат; в шаблонах нет настроек провайдера, ключей и адреса отправителя.
- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `<APP_PUBLIC_URL>/verify-email#token=<token>`; сброс пароля: `<APP_PUBLIC_URL>/reset-password#token=<token>` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда ни в пути, ни в query: браузер не отправляет fragment серверу, поэтому access log nginx (он пишет `$uri`) и заголовки Referer его никогда не содержат, а маршрут frontend читает его в браузере и отправляет в теле запроса API. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются.
- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `<APP_PUBLIC_URL>/verify-email#token=<token>`; сброс пароля: `<APP_PUBLIC_URL>/reset-password#token=<token>` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда ни в пути, ни в query: браузер не отправляет fragment серверу, поэтому access log nginx (он пишет `$uri`) и заголовки Referer его никогда не содержат. Экран подтверждения во frontend пока остается заглушкой; клиент должен прочитать и удалить fragment, дождаться явного действия пользователя и отправить в API токен вместе с паролем регистрации. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются.
- В письмах нет имени, email или других контактов. Текст вызывающего кода в уведомлении экранируется в HTML части; управляющие и bidi символы удаляются из текстовой части, а тема сводится к одной строке, поэтому CR и LF не могут добавить строки заголовка. Тема уведомления ограничена 100 символами, текст 2000.
- Тексты на русском языке. Выпущенная версия неизменяема: изменение текста добавляет следующую версию, например `verification.v2`, и переключает текущую версию в коде. Версии не делят файлы, поэтому одна версия не может изменить тело другой. Каждый результат содержит свою версию и SHA-256 content hash по версии, теме и обеим частям; одна и та же версия с теми же данными всегда дает то же тело. Доставка хранит сформированное тело вместе с hash, а повтор отправляет сохраненное тело, а не формирует его заново, поэтому новая версия применяется только к новым доставкам, а файлы старой версии для отправки сохраненной доставки не нужны.
- Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются.
@@ -380,7 +382,7 @@ Edge-хост общий с другими сервисами. Здесь все
Браузер видит только `https://<EDGE_DOMAIN>`. SPA и `/api` приходят с одного origin: edge пересылает каждый путь без изменений, а frontend контейнер отдает SPA с запасным вариантом `try_files ... /index.html`, поэтому глубокая ссылка вроде `/some/deep/link` возвращает SPA, и проксирует `/api/` в Go. Планируемая cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict`. Браузер принимает ее только со страницы HTTPS, с `Path=/` и без `Domain`; один HTTPS origin это обеспечивает. Edge сохраняет `Host` как публичное имя и ставит `X-Forwarded-Proto: https`; Nginx frontend контейнера сохраняет это значение для backend (`$forwarded_proto` в `deploy/nginx/conf.d/app.conf`), а иначе сообщает собственную схему. `APP_PUBLIC_URL` в `.env` app-хоста должен быть `https://<EDGE_DOMAIN>`: это единственное значение origin, которое читает backend.
Регистрация и вход еще не реализованы (операции отвечают 501), и backend не читает `X-Forwarded-Proto`. Поэтому вход через edge целиком не проверен; проверен транспорт, который нужен cookie (HTTPS, один origin, переданные исходные хост и схема).
Регистрация, повторная отправка подтверждения и подтверждение email доступны через API, но вход не реализован. Экраны регистрации и подтверждения во frontend остаются заглушками, а backend не читает `X-Forwarded-Proto`. Поэтому браузерный путь подтверждения и вход через edge не проверены end to end; проверен транспорт cookie (HTTPS, один origin, переданные исходные хост и схема).
### Обработка запросов на edge
+5 -5
View File
@@ -49,15 +49,15 @@ Frontend зависимости выбираются из актуальных s
Что есть сейчас:
- Маршруты health и readiness. Nginx сам отвечает на `GET /healthz` и проксирует в Go только `/api/` (deploy/nginx/conf.d/app.conf). Go обслуживает `GET /healthz` (`ok`) и `GET /readyz` (`ready` или 503 `not_ready` после проверки PostgreSQL, Redis и SeaweedFS) на внутреннем порту 8080 вне OpenAPI контракта, а также `GET /api/v1/healthz` из api/core/routes/healthz.yml через ogen handler (backend/internal/adapter/primary/http). Метрики Go отдаются на порту 9090 (`METRICS_ADDR`), Prometheus читает `/metrics`. ML обслуживает `GET /healthz`, `GET /readyz` (всегда 503 `not_ready`, потому что модель не подключена) и `/metrics` (ml/src/lincodex_ml, api/ml/routes). deploy/scripts/smoke.sh проверяет `/healthz` Nginx, `/api/v1/healthz`, `/readyz` Go изнутри сети Compose, 404 для неизвестного API маршрута и то, что backend запустился с `EMAIL_PROVIDER=disabled`; ML он не запускает и писем не отправляет.
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и проверка пароля `identity.Credentials` есть и покрыты тестами, но в bootstrap не подключены. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но пока ничто не отправляет уведомления. С `resend` backend запускает worker отправки служебной почты identity (подтверждение и сброс пароля, привязанные к своим токенам, с проверкой перед отправкой, шлюзом квот и стабильным ключом идемпотентности); ни один сценарий аккаунта пока не создает такие письма. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
- Адаптеры: PostgreSQL через pgxpool и generated запрос `SELECT 1`, runner миграций goose, применяемый при старте, transactor с записью transactional outbox, репозитории identity на sqlc для аккаунтов, email-токенов и сессий, а также версионированный репозиторий политики, который при старте заполняет демонстрационную политику; Redis через go-cachekit, SeaweedFS через S3 API. Hasher паролей Argon2id и `identity.Credentials` подключены для регистрации и подтверждения email. Generated Go client для ML контракта есть, но в bootstrap не подключен.
- Почта: outbound порт `MailSender`, транспорты `disabled` и `resend` и выбор `EMAIL_PROVIDER` в bootstrap; `smtp` после проверки своих настроек останавливает запуск. Запросы продуктовых уведомлений (`mail_requests`) превращаются в доставки (`deliveries`, `delivery_attempts`) обработчиком `notification_delivery`, но отправка уведомлений еще не реализована. При `resend` backend запускает worker служебной почты identity: регистрация и повторная отправка создают письма подтверждения, привязанные к токенам; worker проверяет токен и аккаунт перед отправкой и использует шлюз квот и стабильный ключ идемпотентности. Сброс пароля пока не реализован. См. [DEPLOY.md](DEPLOY.md#почта) и [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем).
- OpenAPI контракты api/core/ и api/ml/ с объединением схем, bundles, lint и генерацией для Go (ogen), TypeScript (Orval) и Python (datamodel-code-generator). В SPA есть каркас интерфейса с экранами-заготовками, generated API client и MSW handlers.
- Compose проекты: core (`deploy/docker/docker-compose.yml`: PostgreSQL, Redis, SeaweedFS, Kafka, backend, frontend), ML (`docker-compose.ml.yml`) и monitoring (`docker-compose.monitoring.yml`).
- Kafka: один узел KRaft в core Compose проекте с listener только во внутренней сети, именованным volume, healthcheck и лимитом памяти. Backend запускает relay outbox, который создает топик `lincodex.domain.events` и публикует в него зафиксированные события outbox через producer на franz-go; см. [Relay outbox](#relay-outbox). Readiness не проверяет Kafka. Runtime обработчиков событий запускает один продуктовый обработчик - обработчик доставки писем, а продуктовые сценарии пока не создают его событие; см. [Обработчики событий](#обработчики-событий).
- CI jobs в .github/workflows/ci.yml: `api`, `backend`, `integration` (matrix из двух шардов), `frontend`, `ml`, `codegen`, `infrastructure`, `security`, `security-images`, `smoke`, `e2e` (набор Playwright на изолированном стенде) и обязательный итог `aggregate`, который падает, если любой из них упал, отменен или пропущен. Шардирование и браузерный набор описаны в [TESTING.md](TESTING.md).
- Observability: Prometheus, Loki, Alloy, Grafana с provisioned datasources и dashboards, exporters для PostgreSQL, Redis и node. React-приложение пока не отправляет телеметрию.
Еще не реализованы: регистрация и вход (их контракт объявлен; операции отвечают 501 или 401), согласия, профили, анкета и тестирование, кабинет компании, потребности и подбор, приглашения и контакты, транспорт SMTP и worker, который отправляет сохраненные доставки, продуктовые источники событий, уведомления, поддержка и бизнес-E2E suite. В backend/db/migrations/ есть таблица outbox с индексом для relay, таблицы хранения identity (`users`, `email_tokens`, `sessions`), таблица `policy_versions` таблицы обработчиков событий (`consumer_processed_events`, `consumer_dead_letters`) таблицы доставок писем (`deliveries`, `delivery_attempts`) и таблицы квот почты (`mail_quota_usage`, `mail_quota_reservations`) и таблица заданий по сроку (`scheduled_jobs`, продуктовый вид задания пока не зарегистрирован), другой бизнес-схемы нет; ни одно продуктовое правило пока не читает политику; регистрация, подтверждение и сессии поверх этого хранения появятся в следующих задачах, каталоги продуктовых usecase и адаптеров, кроме частей для хеширования паролей и политики, содержат только заглушки, а `make -C deploy test-e2e` запускает только технический smoke на Playwright для SPA, health API и маршрутов ошибок на одноразовом стеке, а не бизнес-сценарий (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)). Целевая архитектура описана в [ARCHITECTURE.md](ARCHITECTURE.md).
Backend API реализует регистрацию, повторную отправку подтверждения и подтверждение email. Экраны регистрации и подтверждения во frontend, а также вход остаются заглушками. Другие бизнес-сценарии, включая HTTP управление согласиями, профили, анкету и тестирование, кабинет компании, потребности, подбор, приглашения, контакты, продуктовые уведомления и поддержку, не реализованы. Worker отправляет служебную почту identity через Resend; SMTP и отправка продуктовых уведомлений не реализованы. `make -C deploy test-e2e` проверяет оболочку SPA, API health и маршруты ошибок на одноразовом стеке, но не проверяет регистрацию или подтверждение email (см. [TESTING.md](TESTING.md#браузерный-e2e-набор)).
## Установка и цикл работы
@@ -88,7 +88,7 @@ make check не является бизнес-E2E проверкой. make verif
Запланированная cookie сессии - `__Host-lincodex_session` с `Secure`, `HttpOnly` и `SameSite=Strict` (см. [api/README.md](../../api/README.md#identity-сессии-cookie-и-csrf)). Локальный стек отдает обычный HTTP. Chromium и Firefox считают `http://localhost` и `http://127.0.0.1` безопасным контекстом и сохраняют там `Secure` cookie; WebKit и Safari могут ее отклонить. Для локального входа используйте Chromium или Firefox либо локальный TLS-прокси. Проект не добавляет флаг, отключающий `Secure` или префикс `__Host-`, поэтому локальная cookie не отличается от production.
Запланированное правило Origin: любой небезопасный запрос (POST, PUT, PATCH, DELETE), включая публичные, например вход, должен нести `Origin` из allowlist в конфигурации backend, например origin Nginx и origin dev-сервера Vite. Сервер не сравнивает `Origin` с `Host`. Небезопасный запрос без `Origin` или с другим значением получает 403 `csrf_check_failed`.
`ConfirmEmail` требует, чтобы Origin точно совпадал с `APP_PUBLIC_URL`; отсутствующий Origin, буквальное значение `null` или другое значение дают 403 `csrf_check_failed`. Общая проверка Origin для остальных небезопасных запросов остается частью еще не реализованного потока сессий. Сервер не использует Host для определения разрешенного Origin.
## Структура
@@ -165,7 +165,7 @@ goose выполняет каждую миграцию в отдельной т
### Хранение identity
Миграция `00002_create_identity_tables.sql` создает `users`, `email_tokens` и `sessions`; запросы лежат в `backend/db/queries/identity.sql`. Порты `outbound.UserRepository`, `EmailTokenRepository` и `SessionRepository` доступны через `UnitOfWork` внутри `Transactor.WithinTransaction` и через `postgres.IdentityStore` вне транзакции. Bootstrap и HTTP-обработчики их пока не используют; регистрация, подтверждение, вход и principal сессии появятся в следующих задачах.
Миграция `00002_create_identity_tables.sql` создает `users`, `email_tokens` и `sessions`; запросы лежат в `backend/db/queries/identity.sql`. Миграция 00014 добавляет к токенам хеш пароля, сценарий и шаг онбординга конкретной регистрации. Миграция 00016 связывает регистрационную C1 с версией регистрации аккаунта и заполняет прежние записи без использования живых токенов. Порты identity используются при регистрации, повторной отправке и подтверждении email; вход и principal сессии пока не реализованы.
База данных никогда не получает пароль, исходный email-токен или исходный токен сессии. Репозитории принимают `domain.PasswordHash` (строку PHC Argon2id v19) и `domain.SecretTokenHash` (SHA-256 от `domain.SecretToken`). Email-адреса пока принимаются только в ASCII; поддержка IDN и SMTPUTF8 - будущая работа, для которой нужен IDNA ToASCII для домена. `SecretToken`, `PasswordHash` и `EmailAddress` скрывают значение в выводе `fmt` и `slog`; `SecretToken.Reveal` и `EmailAddress.Address` возвращают настоящие значения там, где они нужны. Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, а PostgreSQL хранит микросекунды. Взаимная блокировка или ошибка сериализации сообщается как `outbound.ErrTransactionConflict`, и вызывающий код может повторить всю операцию. Схема и принятые решения описаны в [ARCHITECTURE.md](ARCHITECTURE.md#хранение-identity).
+5 -3
View File
@@ -18,15 +18,15 @@ make -C security images
| Цель | Область проверки |
| --- | --- |
| `filesystem` | Trivy проверяет зависимости и конфигурацию репозитория по `trivy/filesystem.yml` |
| `secrets` | Gitleaks проверяет текущие файлы и всю доступную историю Git по `gitleaks/gitleaks.toml` |
| `secrets` | Gitleaks проверяет отслеживаемые и неигнорируемые файлы, а также всю доступную историю Git по `gitleaks/gitleaks.toml` |
| `go` | govulncheck анализирует использование известного уязвимого Go-кода в backend |
| `semgrep` | Локальные правила `semgrep/frontend.yml` и `semgrep/python.yml` проверяют исходники frontend и ML |
| `rule-test` | Фикстуры Semgrep проверяют ожидаемые срабатывания и допустимые примеры локальных правил |
| `test` | Запускает фикстуры правил Semgrep и тесты целостности установки, сохранения кода ошибки govulncheck и удаления устаревших отчетов |
| `test` | Запускает фикстуры правил Semgrep и тесты установки, входов и отчетов Gitleaks, кода ошибки govulncheck и устаревших отчетов |
| `check` | Запускает проверки файлов, секретов, Go и Semgrep; выполняет каждую и возвращает ошибку, если хотя бы одна не прошла |
| `images` | Собирает образы backend, frontend и ML, затем проверяет каждый точный локальный ID образа через Trivy |
Gitleaks требует полный Git checkout. Отсутствие репозитория или неполная история завершают проверку ошибкой; история не пропускается молча. Значения найденных секретов скрываются в отчетах. Кеши инструментов и результаты сборки исключаются согласно конфигурации; lock-файлы зависимостей приложения остаются входами проверок. Trivy также распознает `requirements-*.txt`, включая `backend/requirements-quality.txt` и `scripts/requirements-codegen.txt`.
Gitleaks требует полный Git checkout. Отсутствие репозитория или неполная история завершают проверку ошибкой; история не пропускается молча. Текущая проверка файлов берет отслеживаемые Git файлы и неигнорируемые незакоммиченные файлы. Отслеживаемые файлы остаются во входах, даже если Git игнорирует их; игнорируемый локальный `.env` не включается. Удаленные отслеживаемые пути и символические ссылки не входят в текущую проверку; цели ссылок не открываются и не читаются. Проверка истории по-прежнему охватывает все ссылки и находит значения, закоммиченные до игнорирования или удаления файла. Gitleaks копирует текущие входы во временную директорию с доступом только для владельца и завершает проверку ошибкой, если сканер падает или JSON-отчет отсутствует либо поврежден. Значения найденных секретов скрываются в отчетах. Кеши инструментов и результаты сборки исключаются согласно конфигурации; lock-файлы зависимостей приложения остаются входами проверок. Trivy также распознает `requirements-*.txt`, включая `backend/requirements-quality.txt` и `scripts/requirements-codegen.txt`.
Для проверки образов нужен Docker. Контекст сборки backend - `backend/`, frontend и ML - корень репозитория. Образы получают теги `lincodex-security-<service>:local`; перед сканированием определяется ID каждого образа. Команда не запускает контейнеры и не публикует образы. Проверка зависимостей исходников frontend остается необходимой: итоговый Nginx-образ содержит собранные ресурсы, а не дерево зависимостей разработки.
@@ -38,6 +38,8 @@ Gitleaks требует полный Git checkout. Отсутствие репо
В [security/trivy/ignore.yml](../../security/trivy/ignore.yml) есть одно временное исключение, согласованное владельцем проекта 2026-10-05: `CVE-2026-93687` для `pkg:npm/braces@3.0.3` в `frontend/pnpm-lock.yaml`. На момент согласования исправленной версии не было; исключение разблокирует CI зависимостей до истечения срока 2026-10-19. Ответственные - сопровождающие проекта: исключение нужно удалить после появления исправления или пересмотреть до истечения срока. Trivy автоматически учитывает дату окончания. Файл исключений применяется только к проверке файлов; скрытые из блокирующего результата находки остаются видимыми в JSON-отчете. Проверка образов не изменяется.
Восемь исключений Gitleaks относятся только к точным примерам API, тестовым фикстурам, фикстуре release manifest и статическому префиксу ключа Redis rate limit. Для каждого должны совпасть правило, путь в репозитории и полный текст находки. Ответственные - сопровождающие проекта. Вручную пересмотрите исключения или удалите их до 2026-11-07; Gitleaks не проверяет эту дату пересмотра. Описание работы allowlist приведено в официальной [документации Gitleaks](https://github.com/gitleaks/gitleaks#configuration).
Любое следующее исключение ограничивайте конкретной находкой и входными данными, указывайте причину, ответственного и срок действия, затем отдавайте изменение на ревью. Текущая интеграция не обеспечивает автоматический контроль срока одинаково для всех инструментов; там, где его нет, проверяйте срок вручную. Не отключайте сканер целиком и не скрывайте все уязвимости без исправлений ради успешной проверки.
## CI и границы проверок
+7 -3
View File
@@ -40,7 +40,9 @@ make -C ml check-generated использует datamodel-code-generator --check
## Что покрывает текущий каркас
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, закрытому файловому слою и контролю доступа SeaweedFS (см. [Тесты закрытого файлового хранилища](#тесты-закрытого-файлового-хранилища)), тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), доставкам писем (см. [Тесты доставки писем](#тесты-доставки-писем)), метрикам, API client, ML schema и доступности текущих endpoint. В каркасе нет сценариев регистрации, входа, тестирования, поиска, приглашений или работы с файлами, нет продуктовых источников событий в Kafka (обработчик доставки писем проверяется только тестами) и нет реального model inference, которые можно было бы проверить как бизнес-результат.
Существующие проверки относятся к health/readiness, проверке соединения backend с PostgreSQL, Redis и SeaweedFS, миграциям up, down до нуля и повторному up на изолированной базе, конкурентным runner миграций, которые применяют каждую миграцию один раз, transactional outbox (атомарная фиксация, откат при ошибке, panic и отмене контекста, отказ во вложенной транзакции, наблюдаемое ожидание блокировки строки между параллельными транзакциями, граничные payload и ограничения), хранению identity (уникальный нормализованный email, хранение только хешей email-токенов и токенов сессий, ровно одно успешное погашение токена при параллельных подтверждениях и наблюдаемое ожидание блокировки между двумя погашениями, отказ для истекших, аннулированных и замененных токенов, в том числе при повторной регистрации во время подтверждения, пределы простоя, абсолютного срока и отзыва сессии и ограничение частоты записи активности, пакетная очистка неподтвержденных аккаунтов, которая пропускает заблокированные аккаунты без ожидания, взаимная блокировка как повторяемый конфликт, каскадное удаление, откат вместе с внешней транзакцией и ограничения), операциям кеша и TTL, S3-операциям и сохранению объектов, закрытому файловому слою и контролю доступа SeaweedFS (см. [Тесты закрытого файлового хранилища](#тесты-закрытого-файлового-хранилища)), тестовой обвязке Kafka (записи с ключом и заголовками и порядок внутри партиции, отказ создавать отсутствующий топик по запросу и очистка топиков), relay outbox (см. [Тесты relay outbox](#тесты-relay-outbox)), runtime обработчиков событий (см. [Тесты обработчиков событий](#тесты-обработчиков-событий)), доставкам писем (см. [Тесты доставки писем](#тесты-доставки-писем)), метрикам, API client, ML schema и доступности текущих endpoint. Регистрация и подтверждение email проверяются API integration-тестами; вход, тестирование, поиск, приглашения и работа с файлами пока не реализованы. Подтверждение записывает событие в transactional outbox, но для него нет зарегистрированного продуктового обработчика; обработчик доставки писем проверяется отдельно. Реального model inference как бизнес-результата нет.
TestEmailVerificationOverHTTP получает токен из Resend fixture после регистрации. Тест проверяет подтверждение candidate и employer, отсутствие сессии и cookie, неизменность состояния при неизвестном, истекшем, замененном или погашенном токене, неверном пароле и отсутствии отложенных данных. Он также проверяет привязку C1 к версии регистрации, отсутствующий, null и чужой Origin, а также лимиты, истечение срока после ожидания блокировки, откат после сбоя outbox и одно событие при параллельном подтверждении. Тест охватывает только API; экраны регистрации и подтверждения во frontend остаются заглушками, внешний почтовый провайдер не вызывается.
API verify проверяет выбранный OpenAPI subset через pinned toolchain; его результат относится только к реально запущенным fixture и контрактам. CI YAML в репозитории не означает, что workflow уже выполнился на GitHub.
@@ -82,6 +84,8 @@ Deployment smoke проверяет инфраструктурные маршр
Вызывайте bootstrap один раз в родительском тесте и используйте окружение в его подтестах. Каждый вызов создает отдельные контейнеры с динамическими портами; для SeaweedFS также создается отдельный volume. Очистка зарегистрирована через `t.Cleanup`, включая частично запущенное окружение. Сценарии остановки Redis и пересоздания SeaweedFS управляют ресурсами через helpers этого окружения и не затрагивают другие тесты. При отсутствии Docker тесты завершаются ошибкой. Если `DOCKER_HOST` недоступен, Testcontainers пробует также Docker context и стандартные сокеты, поэтому одного неверного `DOCKER_HOST` недостаточно, чтобы смоделировать отсутствие Docker.
Bootstrap делает максимум три попытки запуска контейнера всего и только при точной ошибке настройки сети rootless Docker для host-порта, оканчивающейся на `bind: address already in use` (`EADDRINUSE`). Перед повтором он завершает частичный контейнер, возвращенный неудачным запуском; ошибка очистки прекращает повторы. Прочие ошибки запуска или готовности, а также ошибки проверок самого теста не повторяются. Повтор касается только подготовки тестов и не меняет настройки Docker или сети хоста.
Bootstrap поднимает инфраструктуру и клиенты. Если выбран PostgreSQL, он применяет все встроенные миграции тем же runner, что и старт сервиса. `postgres_helpers_test.go` добавляет `env.newPool` для пула к этой базе, `env.createIsolatedDatabase` для отдельной базы в том же контейнере, когда тест меняет всю схему (например up, down и повторный up), `env.newPoolWithMaxConns` для тестов конкурентности, которым нужно одно соединение на транзакцию, и `truncateTables` для сброса общих таблиц между последовательными подтестами. Тесты получают транзакцию из unit of work только через `postgres.TransactionForIntegrationTest`, который компилируется только с build tag `integration`. Тестовые агрегаты живут в собственной схеме, которую создает тест, а не в продуктовых миграциях. HTTP-сервер приложения, ML и продуктовые фикстуры пока не входят в него. Проверка полного окружения использует общий readiness PostgreSQL, Redis и SeaweedFS.
Kafka не входит в `bootstrap(t)` и запускается только для тестов, которые выбирают `bootstrap(t, kafkaService)`. Используется тот же образ `apache/kafka:latest`, что и в Compose, с теми же настройками KRaft, включая `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false`. Клиентский listener объявляется на динамическом порту хоста, трафик между брокерами и контроллером остается на loopback контейнера, а данные и объявленные в образе volume размещаются в tmpfs, поэтому тестовый брокер не оставляет volume. Bootstrap заполняет `env.Config.KafkaBrokers` и создает `env.KafkaAdmin` на основе `kadm` из franz-go.
@@ -163,7 +167,7 @@ Unit-тесты (`make -C backend test`) покрывают модель дос
- Запрос, аккаунт которого удален, теряет строку запроса вместе с аккаунтом; затем обработчик не сохраняет доставку и записывает в лог ID доставки.
- Очистка неподтвержденных аккаунтов пропускает аккаунт, строку доставки которого держит другая транзакция, удаляет его после снятия блокировки, и вместе с ним удаляются его ожидающий запрос и доставка, созданная прямо через репозиторий, как будут создаваться письма с токеном.
Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. Набор не отправляет писем: worker отправки, повторы и проверка разрешений относятся к следующим задачам, у квот свои [тесты квот почты](#тесты-квот-почты), и нет теста доставки подтверждения почты или сброса пароля, которые создадут сценарии identity.
Каждый случай проверяет, что собранные логи обработчика и runtime не содержат ни адреса, ни темы, ни тела, а события запросов проверяются на отсутствие адреса и текста запроса. `TestPostgresMigrations` дополнительно проверяет, что миграция 00006 создает и удаляет три свои таблицы и обе trigger-функции, а `TestIdentityRepositories` выполняет запрос очистки с блокировкой запросов писем и доставок. `TestMailDelivery` не отправляет почту и проверяет обработчик продуктовых уведомлений. `TestEmailVerificationOverHTTP` проверяет письмо подтверждения и подтверждение адреса через Resend fixture, но не обращается к внешнему провайдеру. Для сброса пароля нет теста доставки, потому что этот сценарий пока не реализован.
## Тесты квот почты
@@ -325,7 +329,7 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
- C4: общий путь отклоняет его и ничего не записывает; `GrantContact` в транзакции сохраняет организацию, название, поля, приглашение и источник `invitation_acceptance`; повтор возвращает ту же запись, устаревшая версия C4 отклоняется, а C4 не создает C2.
- Перезапуск: после закрытия pool новый pool, хранилище и usecase перечисляют те же четыре записи по порядку с их состояниями, отметкой и источником отзыва и исходными временами выдачи, а повторная выдача через новый экземпляр ничего не записывает.
`TestPostgresMigrations` откатывает миграцию 00009 вместе с остальными и проверяет, что таблиц и функций не осталось. Интеграционные тесты identity, доставки и квот почты называют `consent_records` в своем TRUNCATE таблицы `users`. Набор не покрывает usecase отзыва, HTTP-обработчик и вызов usecase согласий из регистрации и принятия приглашения, а гонку очистки с SQLSTATE 23001 покрывает только unit-тест ее преобразования, потому что ее окно нельзя воспроизвести детерминированно.
`TestRegistrationConsentMigration` применяет миграцию 00016 в изолированной базе, проверяет привязку старой C1, отсутствие привязки у согласий из настроек, вставку C1 через старую форму записи, отказ для переданной несовпадающей версии, защиту версии от изменения при отзыве и повторный down/up. Отдельный случай проверяет, что устаревшая регистрационная C1 останавливает миграцию без частичных изменений. `TestPostgresMigrations` продолжает проверять миграцию 00009. Интеграционные тесты регистрации и подтверждения email проверяют вызов consent service в API потоке; `TestConsentGrants` проверяет usecase отдельно от HTTP. Отзыв и принятие приглашения с C4 пока не покрыты как бизнес-потоки. Гонка очистки с SQLSTATE 23001 покрыта только unit-тестом преобразования, потому что ее окно нельзя воспроизвести детерминированно.
## Тесты организаций