feat(identity): add server sessions and audited mail recovery
This commit is contained in:
1 parent
20c03288d6
commit
4ee53d9a74
58 files changed
+5359
-567
No files matched your search
+38
-30
@@ -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.
|
||||
|
||||
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.
|
||||
Registration, email confirmation, login, and basic current-session operations work through the backend API. Frontend registration and confirmation screens remain placeholders; 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.
|
||||
|
||||
@@ -202,11 +202,11 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai
|
||||
|
||||
- `accepted`: the provider accepted the request and returned `ProviderMessageID`. This is not delivery or reading.
|
||||
- `rejected`: the provider did not take the message. Either it answered and refused, or the transport failed before the request was completely written (DNS, connect, or TLS), so no complete request reached the provider; the second case is always `temporary`, and a retry cannot duplicate the message. `Rejection` is `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted`, or `temporary`.
|
||||
- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Provider deduplication has a window (24 hours for Resend); after it a retry may send the message twice, so the delivery layer must stop retrying and escalate to an operator.
|
||||
- `unknown`: the request may have reached the provider but no conclusive answer came back (`delivery_uncertain`), for example a timeout, a connection lost after the request was written, or a provider error raised while handling it. It is not "not sent": a retry reuses the idempotency key and the same content. Resend keeps an idempotency key for 24 hours. The worker stops automatic retries at 23 hours, leaving a one-hour safety margin; after that an operator must decide whether to retry because the old key may no longer prevent a duplicate.
|
||||
|
||||
`rejected` and `unknown` may carry `RetryAfter`, the provider's wait hint or a wait the transport derived from documented provider rules, and `ProviderCode`, the provider's error name. A `quota_exhausted` rejection also names the exhausted window in `QuotaPeriod` (`day` or `month`) when the provider said which; it is empty otherwise. A transport sets `ProviderCode` only from its fixed list of documented names and leaves it empty otherwise, so it never carries provider text and is safe to log and store.
|
||||
|
||||
A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses.
|
||||
A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error when the caller's context ended before the request was written. A failure before the request was written while the context is still active is `rejected`/`temporary`, not an error. The transport makes one request; the worker owns retries, backoff, and outcome storage. The verification flows must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses.
|
||||
|
||||
The Resend transport uses `net/http` without an SDK. One `Send` is one `POST https://api.resend.com/emails` with `from` (`EMAIL_FROM`), `to` (one recipient), `subject`, `text`, and `html` (a blank part is omitted), an `Authorization: Bearer` key, a `User-Agent`, and `Idempotency-Key` set to the message's key. Resend keeps a key for 24 hours and answers the same key and body with the original result without sending again, so a retry must repeat the stored body under the same key; a changed body under an old key is a conflict, not a reason to make a new key. `EMAIL_TIMEOUT` bounds the whole attempt. The client follows no redirects, uses HTTP/1.1, and opens a fresh connection for every send: a kept-alive connection that the server closed while idle would fail after the request was handed to it and turn a message Resend never saw into a false `unknown`. The request also has no `GetBody`, because `net/http` treats a POST with `Idempotency-Key` as replayable on a broken reused connection. The adapter has no retry loop and does not log. An answer is read up to 64 KiB; only the message ID and the error `name` are parsed, and the provider's message and body are not kept.
|
||||
|
||||
@@ -230,11 +230,11 @@ The Resend transport uses `net/http` without an SDK. One `Send` is one `POST htt
|
||||
| Failure before the request was written: DNS, connect, TLS, or the attempt timeout | `rejected`, `temporary`: no complete request reached Resend |
|
||||
| The caller's context ended before the request was written | the context error; nothing was sent |
|
||||
|
||||
Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy, the sending worker applies only the minimum schedule described in [Sending service mail](#sending-service-mail), and the stop at the end of the 24-hour key window is the sending worker's rule for an attempt whose worker was lost; waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas).
|
||||
Every `rejected` or `unknown` answer with a known error name sets `ProviderCode` to that name, for example `invalid_idempotent_request`, `invalid_api_key`, or `daily_quota_exceeded`. Known names are those on the Resend errors page plus the older names that the official Node SDK still lists (`invalid_api_key`, `invalid_from_address`, `invalid_access`, `invalid_region`, `security_error`, `internal_server_error`); any other name counts as no name. `RetryAfter` is capped at 24 hours. Rate-limit pacing and the attempt limit belong to the retry policy, the sending worker applies the minimum schedule described in [Sending service mail](#sending-service-mail), and automatic retries of uncertain sends stop at 23 hours, one hour before Resend's 24-hour key window ends. Waiting for a quota reset is decided by the quota gate described in [Mail quotas](#mail-quotas).
|
||||
|
||||
### 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). 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.
|
||||
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 service-mail worker, bounded retries, the unknown-outcome cutoff, and the audited local operator command, with migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql`; see [Sending service mail](#sending-service-mail). Sending product notifications with the permission check before a send is not implemented. 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:
|
||||
|
||||
@@ -272,7 +272,7 @@ Statuses. The values follow the `MailSender` outcomes:
|
||||
| `pending` | Waits for its first attempt, or for a retry after a `temporary` or `rate_limited` rejection | Required: when it is due |
|
||||
| `accepted` | The provider accepted the message and returned `provider_message_id`: "accepted by the provider". Not delivery to or reading by a person; no status claims that | None; terminal |
|
||||
| `rejected` | A `permanent` or `invalid_request` rejection; the cause must be fixed | None; terminal |
|
||||
| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": a retry reuses the key and the stored body | Optional; none means no automatic retry |
|
||||
| `unknown` | The attempt may have reached the provider (`delivery_uncertain`). Never "not sent": an eligible automatic or operator-approved retry uses the pinned key and stored body | Optional; none means operator review is required |
|
||||
| `cancelled` | The message was deliberately not sent and never will be: the token or the account no longer matches, or the stored message is unsendable. `cancel_reason` says why; no attempt is recorded | None; terminal |
|
||||
| `waiting_quota` | A provider quota or the local quota is used up | Optional: the expected reset (see [Mail quotas](#mail-quotas)); none when the reset is unknown, for example after a provider quota answer that names neither a window nor a wait, and an operator decides |
|
||||
|
||||
@@ -285,7 +285,7 @@ Transitions:
|
||||
|
||||
Every change advances `version`, and the store applies it only over the previous version. The next attempt time comes from the caller's retry policy and must fit the target status; the CHECK `deliveries_next_attempt_matches_status` repeats the rule, and `deliveries_provider_message_id_when_accepted` requires the provider ID exactly for `accepted`.
|
||||
|
||||
Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The history is what an operator needs to judge an unknown outcome, what the end of the 24-hour key window counts from (the first attempt), and what an audit of a manual decision refers to. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt.
|
||||
Attempts. The current state sits in counters on `deliveries`, so a worker reads one row, and every attempt is a row in `delivery_attempts`: number, time, outcome, rejection, provider code, provider message ID, wait hint, resulting status, and next attempt time. The first provider-call start is recorded by the database clock and is the age source for the automatic cutoff. Operator decisions are kept separately in `delivery_retry_decisions`, including the delivery ID, current attempt count, actor handle, explicit duplicate-risk acknowledgement, whether an expired lease was recovered, and decision time. It has no foreign key, so deleting the account does not erase the audit; row-level UPDATE/DELETE and statement-level TRUNCATE are refused. The wait hint is stored exactly as the Go `time.Duration` in nanoseconds (`retry_after_ns`), so a round trip never changes it. `RecordAttempt` stores the delivery and the attempt in one statement: a data-modifying CTE updates the delivery only while its version is still the one before the attempt and appends the attempt only if that update matched. A second writer of the same attempt gets `outbound.ErrDeliveryVersionConflict` and writes nothing. A trigger refuses an UPDATE of an attempt.
|
||||
|
||||
Quota accounting is not derived from this history: the cascade from an account deletes its deliveries and attempts, so counting sends from `delivery_attempts` would lose sends of deleted accounts and let the provider quota be exceeded. The quota therefore has its own counter that does not cascade, keyed by provider, provider account, and UTC day or month; see [Mail quotas](#mail-quotas).
|
||||
|
||||
@@ -293,7 +293,7 @@ Provider account. Each delivery is pinned to the transport and account configure
|
||||
|
||||
Migration `00012_add_delivery_sending.sql` is additive; existing rows stay valid. It adds to `deliveries`: `email_token_id` (a nullable foreign key to `email_tokens.id` for token mail, immutable like the rest of the content, NULL for notifications), `cancel_reason` (set exactly when the status is `cancelled`, CHECK-limited to the reasons above), the lease columns `claim_owner` and `claimed_until` (both or neither; only a delivery the worker may still send holds one), `first_send_started_at` (when the first request started, by the database clock), `failure_count` (consecutive failures of the worker on the row), `body_redacted_at` (the bodies of a token mail were cleared), the status `cancelled` with its CHECKs, and two partial indexes: `deliveries_due_idx` on `(next_attempt_at, id)` whose predicate names the service kinds and the statuses that are picked up again, so notification rows never enter it and an idle poll does not scan them, and one on `email_token_id`. The trigger `deliveries_refuse_content_change` also allows exactly one change of the bodies: a terminal token mail may have both set to empty together with `body_redacted_at`, once. It adds the `password_reset` token purpose to `email_tokens`. The down migration turns cancelled deliveries into rejected ones and deletes reset tokens. Planned: a cancelled delivery for a revoked permission.
|
||||
|
||||
The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`.
|
||||
The store provides `Get`, `ListAttempts`, the version-checked `RecordAttempt`, `WaitForQuota`, `Cancel`, and `Rebind`, and for the sending worker `ClaimDue`, `ReleaseClaim`, and `ServiceMailState`. Migration `00017_retry_unknown_mail.sql` adds the manual-cycle markers, the append-only decision journal, and `unknown` to the due index predicate. It drops and recreates the partial due index, which takes a table lock while it rebuilds. Rolling this migration back drops the decision journal and its audit data; preserve an export first if rollback is required.
|
||||
|
||||
### Mail quotas
|
||||
|
||||
@@ -342,7 +342,7 @@ 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`. Registration queues a verification email, and `ConfirmEmail` consumes its link. Product notification sending and the password reset flow are not implemented.
|
||||
Implemented: the sending usecase `ServiceMailSender` (`backend/internal/usecase/notification/service_sender.go`), the enqueue usecase `ServiceMailer` (`service_mail.go`), the retry schedule `RetryPolicy` (`send_retry.go`), bounded retries of unknown Resend outcomes, audited operator decisions through `DeliveryRetryOperator`, and the local command `backend/cmd/mail-retry/`. `Delivery.CheckServiceMail` and `Delivery.Cancel` hold the cancel reasons (`backend/internal/domain/delivery.go`, `delivery_guard.go`), the loop is in `backend/internal/worker/mailsender/`, and the inbound port is `inbound.MailPass` (`port/inbound/mail_sender.go`). The repository and migrations `00012_add_delivery_sending.sql` and `00017_retry_unknown_mail.sql` store attempts, leases, retry cutoffs, and operator decisions. 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.
|
||||
|
||||
@@ -352,8 +352,8 @@ Links. The token travels only in the URL fragment: `<APP_PUBLIC_URL>/verify-emai
|
||||
|
||||
One pass of `ServiceMailSender.ProcessNext` takes one delivery through three steps:
|
||||
|
||||
1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending` or `waiting_quota`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. A delivery in `unknown`, or in `waiting_quota` without a time, has no due time and waits for an operator. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows.
|
||||
2. Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with `ServiceMailState`, so a revocation after the claim committed is honored, and notes `first_send_started_at` the first time. A mail that is no longer valid is cancelled and its reservation given back. Then one call to `MailSender.Send` with the stored content and the stable idempotency key `delivery/<id>`. The sender never retries. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace.
|
||||
1. Claim transaction. `DeliveryRepository.ClaimDue` takes the most overdue due delivery with `FOR UPDATE SKIP LOCKED`: kind `verification` or `password_reset` (literals that match the predicate of `deliveries_due_idx`, so the poll reads only that small index), status `pending`, `waiting_quota`, or a scheduled `unknown`, `next_attempt_at` passed, pinned to the configured provider account, and held by no live lease. An initial uncertain result is scheduled only while the delivery is inside the automatic cutoff; terminal unknown rows and unknown rows without a due time wait for an operator. A single-use manual authorization also makes an unknown row due. It sets `claim_owner` and `claimed_until` (the lease) without changing the version or the update time, so several processes never take one delivery. The lease is measured by the database clock (`clock_timestamp()` plus the lease length, and live while `claimed_until` is later than `clock_timestamp()`), never by the clock of an application instance, so instances whose clocks differ cannot take over a live lease or hold a dead one; due times stay on the application clock that wrote them. In the same transaction the sender rebinds mail stored while `EMAIL_PROVIDER=disabled` to the configured account (allowed before the first attempt only, so no provider holds its key), runs the check below, and then `QuotaGate.PrepareSend`, which reserves the recipient or parks the delivery in `waiting_quota`. The transaction commits before the transport is called, so a slow provider never holds a row lock. A failure inside it (a deterministic one, such as a row that cannot be restored) rolls the lease back too, so the failure is then recorded for the row in a transaction of its own; see Failing rows.
|
||||
2. Check right before the send, one short transaction: it locks the delivery row (only for the lease holder), reads the token and the account again with `ServiceMailState`, so a revocation after the claim committed is honored, and records `first_send_started_at` by the database clock. For an uncertain retry, it rechecks the age against the 23-hour cutoff here, after quota and lease waits, immediately before any network call. A manual authorization is consumed only when this send-start is recorded. A mail that is no longer valid is cancelled and its reservation given back. Then one call to `MailSender.Send` with the stored content and the stable idempotency key `delivery/<id>`. The transport never retries internally. The call is bounded by what is left of the lease after the claim and the settlement budget, and by the shutdown grace.
|
||||
3. Settlement transaction. It locks the delivery row first (only while this worker still holds the lease), then `QuotaGate.SettleSend` and `DeliveryRepository.RecordClaimedAttempt` commit together, and the lease ends with the attempt. `RecordClaimedAttempt` applies only over the delivery's version and only for the lease owner, so a worker whose lease was taken over cannot record, and if two workers reach this step for one delivery only the first is kept; the other rolls back, including its quota settlement, and reports `lease_lost`. A database failure while storing the answer is repeated up to three times inside a settlement budget, because the answer exists only in memory until it is stored.
|
||||
|
||||
Time budget. The lease is `EMAIL_TIMEOUT` plus one minute. The claim and the check come first; the call gets what remains of the lease minus the settlement budget (20 seconds), so claim, call, and the whole settlement fit inside the lease. When shutdown has begun the settlement budget is the shorter of 5 seconds and `SHUTDOWN_TIMEOUT` minus the 3-second shutdown grace (at least 1 second), so the process stops within its shutdown timeout, which is 10 seconds by default (the Compose stop grace period is 30 seconds). A result that cannot be stored in time is covered by the takeover below.
|
||||
@@ -385,22 +385,22 @@ What a provider answer becomes. The delivery state machine of `domain.Delivery`
|
||||
| `rejected` `permanent` or `invalid_request` | `rejected` | none | released |
|
||||
| `rejected` `temporary` or `rate_limited` | `pending` | now plus `RetryPolicy`: 1 minute, doubling to at most 30 minutes, never shorter than the provider's `Retry-After` | released |
|
||||
| `rejected` `quota_exhausted` | `waiting_quota` | the reset the gate returns (next 00:00 UTC for a day, the first of the next month for a month); none when the provider named no window | window marked full |
|
||||
| `unknown` | `unknown` | none: no automatic retry | counted |
|
||||
| `unknown` | `unknown` | minimum retry schedule until the 23-hour cutoff; after that, none until an operator decision | counted |
|
||||
| `Send` error: no transport (`ErrMailChannelUnavailable`) or the context ended | unchanged, lease released | still due | released |
|
||||
| `Send` error: invalid message (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | none | released |
|
||||
| `Send` error: anything else without an answer | not counted against the row; it moves back by `RetryPolicy` and the worker backs off | now plus `RetryPolicy` | released |
|
||||
|
||||
The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with `token_expired`. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. `unknown` is never read as not sent and is never repeated by the worker; an operator decides, and the alert `LincodexMailDeliveryUnknownOutcome` fires.
|
||||
The retry schedule has no attempt limit on purpose: the token expires, and the check then cancels the delivery with `token_expired`. Each delay gets bounded jitter, up to a fifth over the schedule, from an injectable source (nil in tests, so times are exact), so deliveries refused together do not return together. Confirmed `temporary` and `rate_limited` refusals are retried with the same pinned account, key, and body; the `Retry-After` value is a lower bound. A confirmed refusal proves that request was not accepted, but it does not clear uncertainty from an earlier unknown attempt. Automatic retries of uncertain Resend outcomes use the same key and exact body only until 23 hours after the database-recorded first send, one hour before Resend's documented 24-hour key expiry. The last storage check repeats this cutoff immediately before the provider call. An unknown answer or a lost lease after send-start ends automatic retries and requires operator review. A pending manual decision permits a potential send; confirmed temporary or 429 refusals may continue under that decision, but an unknown result or lost lease after send-start requires another explicit decision. Recovery records a lost send as an unknown attempt before it schedules the new decision, and does not call the provider. A manual decision does not restart Resend's key window. The local `mail-retry` command uses the database credential as its operator boundary: `make -C backend mail-retry ARGS='inspect --delivery <uuid>'` shows metadata and the duplicate warning, while `make -C backend mail-retry ARGS='retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk'` prints the warning before atomically scheduling and auditing a single-use decision. It never calls a provider. The actor is an audit handle, not an authentication mechanism; there is no HTTP operator endpoint. Reusing an expired key may send a duplicate despite the acknowledgement. The alert `LincodexMailDeliveryUnknownOutcome` fires while an outcome needs review.
|
||||
|
||||
A worker lost after the call. If a worker stops after it called the provider but before it stored the answer, its lease expires and another worker claims the delivery on the same attempt and repeats the request with the same idempotency key. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from `first_send_started_at` (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an `unknown` attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt.
|
||||
Automatic retry after a lost worker. If a worker stops after a provider call but before storing the answer, another worker may claim that attempt and repeat the request with the same key while the 23-hour cutoff has not passed. A lost result after a manual send-start is recorded as unknown and waits for another operator decision; recovery does not call the provider. Resend answers a repeated key and body with the original result, and the quota gate reuses the open reservation, so the message exists once and counts once. The provider keeps the key for 24 hours from the first request, so the age is counted from `first_send_started_at` (set by the database clock right before the first request), not from the latest lease: however many workers were lost in turn, and whatever the lease length, once that age reaches 23 hours (the window less a one-hour safety margin) the earlier request may be forgotten and repeating it could send twice, so the delivery is recorded as an `unknown` attempt without a next attempt instead. The same applies at once to a transport without provider-side deduplication (window zero, SMTP). A lease that never reached the first request leaves nothing in doubt.
|
||||
|
||||
Failing rows. A fault in one row must not hold the head of the queue. When the claim transaction fails after it took a row, its lease rolls back with it, so the same row would be claimed again at once and every delivery behind it would wait. Only a fault that the row itself causes is counted against it: a domain rule it breaks (`ErrInvalidDelivery`, `ErrDeliveryTransition`, invalid content or address), a row that cannot be restored for a reason other than a hash mismatch, or a data or integrity constraint refusal (SQLSTATE classes 22 and 23, `outbound.ErrRowFault`). Everything else says nothing about the row and is never counted: a context that ended, a timeout, a deadlock, a lost connection (SQLSTATE 08, 40, 53, 57, XX), an I/O error, a missing quota configuration. Such an error is returned to the worker, which backs off like for any global failure, and the lease expires or rolls back. For a counted fault the sender records the failure in a short transaction of its own (`RecordFailure`): `failure_count` is incremented, the lease ends, and the row is due again by `RetryPolicy` (outcome `row_failed`; the next pass takes the delivery behind it). The statement leaves a row alone that another worker holds under a live lease, so a claim that rolled back cannot disturb a row that someone else has just claimed. The count means consecutive failures: a successful claim and preparation (the check before the send) clears it, and so does a recorded attempt. A circuit breaker in the worker stops the counting when failures hit different rows pass after pass: three passes in a row that fail on three different rows are read as a global fault, the worker waits with a growing backoff (a `row_failed` pass never loops at once), and failures are moved back but not counted, and no row is cancelled, until a pass succeeds. After 3 consecutive counted failures the row is cancelled with the reason `processing_failed`, the existing terminal status that fits: it is visible to the operator and the alert below fires, and a new status was not needed. A database outage that also stops this record leaves the row under its lease, which expires.
|
||||
|
||||
`EMAIL_PROVIDER=disabled`. Bootstrap does not start the loop: `newMailSenderWorker` returns no worker and logs `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, so `lincodex_mail_sender_running` stays 0 and `LincodexMailDeliveriesOverdue` stays silent. Stored mail waits, pinned to `disabled`; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. A worker that is run against the disabled transport anyway (tests) gets `ErrMailChannelUnavailable` from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins.
|
||||
`EMAIL_PROVIDER=disabled`. Bootstrap does not start the loop: `newMailSenderWorker` returns no worker and logs `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`, so `lincodex_mail_sender_running` stays 0 and `LincodexMailDeliveriesOverdue` stays silent. Stored mail waits, pinned to `disabled`; after the stand restarts with a transport the worker rebinds it and sends it, if the token and the account still pass the check. The local operator command is available only with the Resend transport selected. A worker that is run against the disabled transport anyway (tests) gets `ErrMailChannelUnavailable` from every send, records nothing, releases the lease and the reservation, and backs off (5 seconds doubling to 2 minutes) instead of claiming again at once, so it never spins.
|
||||
|
||||
Loop and shutdown. `worker/mailsender` repeats passes: a pass that handled a delivery is followed at once by the next, an idle pass waits 5 seconds, and a database failure, a missing transport, or an interrupted call waits with the growing backoff. When the context ends the worker claims nothing more, lets the send in progress continue for 5 seconds, stores its result, and returns; the gauge is 0 from then on. The loop is a goroutine of the backend process on its own pool of two connections, like the other workers; more throughput comes from more instances, and each handles one delivery at a time, which suits service mail under the Resend Free quota.
|
||||
|
||||
Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches `accepted`, `rejected`, or `cancelled` (by any path: an attempt, a cancellation, the broken-row cancellation, or `processing_failed`), the same statement sets `text_body` and `html_body` to empty and `body_redacted_at`; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK `deliveries_body_present` accepts an empty body only with the mark; the domain restores such a row as redacted content (`RestoreRedactedMailContent`), which cannot be sent. `unknown` is not terminal and keeps its body, because a retry resends it; an operator who resolves it must clear it. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies.
|
||||
Token at rest. The body of a token mail holds the one-time token, and a reset token is an account takeover primitive for anyone who can read the database or a backup. When a token mail reaches `accepted`, `rejected`, or `cancelled` (by any path: an attempt, a cancellation, the broken-row cancellation, or `processing_failed`), the same statement sets `text_body` and `html_body` to empty and `body_redacted_at`; the subject, the content hash, and the template version stay. The trigger allows exactly that change once, for a terminal row, and refuses any other change of the bodies or of the mark; the CHECK `deliveries_body_present` accepts an empty body only with the mark; the domain restores such a row as redacted content (`RestoreRedactedMailContent`), which cannot be sent. `unknown` keeps its body while it waits for review or a retry, because the worker may need to resend the stored content. The local command does not display or edit the body. Notifications are not redacted. Rolling back migration 00012 puts a placeholder in cleared bodies.
|
||||
|
||||
Privacy. Logs name a delivery only by `delivery_id`, its kind, and closed values (the outcome and the cancel reason); no address, token, link, subject, or body appears in a log line, an error, or a metric label, and the metric has no labels at all. `ServiceMailSender` builds the outgoing message from the stored content and never logs it; `OutgoingMail` and `Delivery` redact themselves.
|
||||
|
||||
@@ -408,7 +408,7 @@ Test fixture only. `resendfixture` and `resend.NewLoopbackSender` are never used
|
||||
|
||||
Tests. `integration_test/mail_sender_test.go` runs a local Resend fixture (`resendfixture`, an `httptest` server speaking the part of the API the transport uses, reached through `resend.NewLoopbackSender`, which accepts only a loopback endpoint) against PostgreSQL; see [TESTING.md](TESTING.md). It is a test fixture only; production binds the real Resend transport with its fixed endpoint.
|
||||
|
||||
Open points. Automatic retry or escalation for `unknown` is not implemented. Sending product notifications, and the permission check they need, are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
|
||||
Open points. Sending product notifications and the permission check they need are planned; until then notifications wait, and they are not counted in the overdue gauge, so a notification backlog does not fire `LincodexMailDeliveriesOverdue` (the gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` covers `domain.ServiceMailKinds`; its predicate is the one of `deliveries_due_idx`). Whether a password reset goes to unverified accounts is for the reset flow to decide. The poll runs every 5 seconds and the claim reads one indexed statement, which suits the current volume.
|
||||
|
||||
### Product policy versions
|
||||
|
||||
@@ -536,7 +536,7 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.
|
||||
|
||||
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 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.
|
||||
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, confirmation, and login, PostgreSQL sessions and a security boundary for a limited set of session operations, 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, confirmation, and login, 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. Profiles, 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/`: 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/`.
|
||||
|
||||
@@ -646,7 +646,7 @@ The brief references Russian Federal Law 152-FZ. The system design calls for sep
|
||||
|
||||
### Identity storage
|
||||
|
||||
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).
|
||||
Identity storage is implemented in migration `backend/db/migrations/00002_create_identity_tables.sql`, the queries in `backend/db/queries/identity.sql`, the domain types, outbound ports, and the PostgreSQL adapter. The backend API implements registration, verification resend, `ConfirmEmail`, login, and basic current-session operations. The frontend registration and confirmation screens are placeholders; see the [API contract](../../api/README.en.md#identity-sessions-cookie-and-csrf).
|
||||
|
||||
- `users`: UUIDv7 `id`; `email`, the delivery form (trimmed ASCII, letter case as typed, returned as `Account.email`), and `email_normalized`, the unique comparison key (the same address with A-Z lowercased); `password_hash`, an Argon2id v19 PHC string; `scenario` and `onboarding_step` with a CHECK that the step belongs to the scenario; nullable `email_verified_at`; `registration_version`; `last_registered_at` with a partial index over unverified accounts for the planned 7-day cleanup; the optimistic `version`; `created_at` and `updated_at`. The delivery form is kept because RFC 5321 allows a case-sensitive local part: mail goes to the address as typed, while uniqueness ignores letter case.
|
||||
- `email_tokens`: `token_hash` (SHA-256, 32-byte `bytea`, unique), `purpose` (`email_verification`; a CHECK lists allowed purposes, so password reset can be added later), `user_id`, the `registration_version` the token is bound to, `created_at`, `expires_at`, `consumed_at`, and `invalidated_at`. Migration 00014 adds `pending_password_hash`, `pending_scenario`, and `pending_onboarding_step`, so each token carries its registration data. A CHECK allows at most one of consumed and invalidated.
|
||||
@@ -659,14 +659,14 @@ Decisions:
|
||||
- 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.
|
||||
- There is no CSRF column. `GetCurrentSession` must return the session's CSRF token after a reload, which a stored hash cannot reproduce. Session authentication can derive the token from the session token with a server key, which needs no storage, or add a column in an additive migration.
|
||||
- There is no CSRF column. `GetCurrentSession` returns the token after a reload: the server derives it with domain-separated HMAC-SHA-256 from the cookie token and `IDENTITY_KEY_SECRET`, so it needs no database storage. Comparison is constant-time; the session token itself is stored in the database only as a SHA-256 hash.
|
||||
|
||||
What the ports guarantee:
|
||||
|
||||
- `UserRepository.Create` returns `ErrEmailTaken` for a duplicate key. `UpdateRegistration` stores the result of `domain.User.ReRegister` only when the stored `version` matches and the email is unverified; the same statement advances `version` and `registration_version` by one, so no caller chooses the registration version, and deletes the registration C1 of the earlier registrant (see [Consent ledger](#consent-ledger)). `MarkEmailVerified` applies only to an unverified account with the given registration version. Both return `ErrUserVersionConflict` otherwise.
|
||||
- `EmailTokenRepository.Consume` is one `UPDATE ... RETURNING` that requires an unconsumed, uninvalidated, unexpired token. Concurrent callers queue on the token row lock; under READ COMMITTED each waiter re-checks the row after the holder finishes, so exactly one succeeds and, if the holder rolls back, a waiter can still succeed. A miss is reported as `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (replaced, or issued for an earlier registration version), or `ErrEmailTokenExpired`. `InvalidateActive` marks every earlier token of a user and purpose.
|
||||
- Consume compares the token's registration version with the account only as its statement reads the account, without locking it, so it cannot see a re-registration that commits right after it. The binding of a token to the current registration therefore holds only when a confirmation calls `MarkEmailVerified(token.UserID, token.RegistrationVersion)` in the same transaction and rolls back on `ErrUserVersionConflict`; the rollback also restores the token, which is then superseded. The confirmation usecase maps that outcome to `verification_token_invalid`.
|
||||
- `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` writes `last_seen_at` only when the stored value is more than one minute older, so frequent requests do not rewrite the row and the idle timeout can end a session up to a minute early; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`.
|
||||
- `SessionRepository.FindActive` and `Touch` take the idle timeout from the caller and accept only an unrevoked session before its absolute deadline and within the idle timeout. `Touch` coalesces writes with a cutoff equal to the smaller of one minute and half the idle timeout, so frequent requests do not rewrite the row and even the shortest supported idle timeout can be extended; it never moves `last_seen_at` back or revives an ended session. `Revoke` and `RevokeAllForUser` set `revoked_at`.
|
||||
- `DeleteUnverifiedRegisteredBefore` deletes one batch of unverified accounts, oldest first, and never waits for a lock. It locks the candidate accounts, their tokens, their sessions, their mail requests, their mail deliveries, and their consent records with `FOR UPDATE SKIP LOCKED` and skips every account whose row, or any token, session, mail request, delivery, or consent row, is locked by another transaction, such as a re-registration, a resend, a confirmation, the delivery consumer, or a delivery worker; skipped accounts stay for the next run. The mail requests, deliveries, and attempts go with the account by cascade; the consent records, which restrict the delete, are deleted explicitly in the same statement.
|
||||
- `postgres.IdentityStore` runs the same repositories outside a transaction. Called with a context from a `Transactor` callback, it returns `ErrNestedTransaction` instead of committing on a separate connection.
|
||||
- Unique and foreign key violations map to `ErrEmailTaken`, `ErrTokenHashConflict`, and `ErrUserNotFound` by SQLSTATE and constraint name, never by error text.
|
||||
@@ -674,17 +674,25 @@ What the ports guarantee:
|
||||
|
||||
### Password hashing
|
||||
|
||||
Implemented and tested: registration creates the hasher from configuration and calls it; login will do the same.
|
||||
Implemented and tested: registration and login use the hasher created from configuration.
|
||||
|
||||
- `domain.Password` holds the password normalized to Unicode NFKC. `domain.NewPassword` applies the registration policy, 15 to 128 code points after normalization; `domain.ParseLoginPassword` accepts 1 to 128. Before normalizing, both reject raw input over 512 bytes (128 code points of at most 4 UTF-8 bytes, so every value the contract schema accepts fits) and invalid UTF-8. These checks run before any hashing and fail with `domain.ErrInvalidPassword`, naming the rule but never the value. The blocklist of common or breached passwords is a separate planned check.
|
||||
- The `outbound.PasswordHasher` port (`port/outbound/password.go`) has `Hash`, `Verify`, and `VerifyDummy`; the `adapter/secondary/argon2id` adapter implements it with `golang.org/x/crypto/argon2`. New hashes use Argon2id v19 with m=65536 KiB, t=3, p=4 (the second recommended option of RFC 9106, above the OWASP baseline of 19 MiB, t=2, p=1), a 16-byte salt from crypto/rand, and a 32-byte key, encoded as `$argon2id$v=19$m=65536,t=3,p=4$<salt>$<key>` in unpadded base64, the format that `domain.NewPasswordHash` and the `users_password_hash_format` CHECK accept. One hash took about 26 to 33 ms on an Apple M5 development machine (`BenchmarkHashRecommendedParameters`, also with one CPU); this is not a production latency figure.
|
||||
- Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; request rate limiting comes with the HTTP operations.
|
||||
- `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.
|
||||
- Memory budget: derivations share a weighted semaphore (`golang.org/x/sync/semaphore`) of `PASSWORD_HASH_CONCURRENCY` times 64 MiB, and each holds its own memory parameter while it runs. The setting accepts 1 to 4; when unset it is the smaller of 2 and GOMAXPROCS, which Go derives from the container CPU limit. Compose passes `PASSWORD_HASH_CONCURRENCY=1` for the 1-CPU backend container, so hashes run one at a time with 64 MiB live; the maximum of 4 needs 256 MiB. Memory of a finished derivation is garbage until the next collection; `GOMEMLIMIT=600MiB` in Compose makes the collector reclaim it before the heap reaches about 78% of the 768 MiB container limit, and the rest is left for stacks and non-heap memory. Waiting calls queue in FIFO order, bounded only by their request context; identity HTTP limits are described in the server-side sessions section.
|
||||
- `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; login does not yet update such hashes automatically.
|
||||
- `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 calls it for an unknown email and an invalid stored hash, so those branches also perform a full Argon2id verification.
|
||||
- Login answers `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 also logs an error and calls `VerifyDummy`. A valid password for an unverified account answers `email_not_verified` and creates no session. Verification time is not uniform: unknown emails and corrupt hashes run `VerifyDummy`, while stored hashes with different Argon2id parameters take different amounts of time.
|
||||
- `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.
|
||||
|
||||
### Server-side sessions
|
||||
|
||||
Login, reading the current session, and logout are implemented in the backend. Login requires the sole `Origin` value to exactly match `APP_PUBLIC_URL`; logout checks the same Origin and a session-bound `X-CSRF-Token`. Origin is checked at the HTTP boundary and does not trust `Host` or arbitrary forwarded headers. The CSRF value is a domain-separated HMAC-SHA-256 derived from the session token, bound to that token, and compared in constant time. `GetCurrentSession` returns it again after a page reload. GET `/api/v1/identity/sessions/current` returns the current session and account, GET `/api/v1/identity/me` returns the current account, and DELETE `/api/v1/identity/sessions/current` revokes the session. These are the only OpenAPI operations currently allowed through the session security boundary; all other protected operations remain denied even with a valid cookie.
|
||||
|
||||
The cookie is named `__Host-lincodex_session` and has `Path=/`, `Secure`, `HttpOnly`, and `SameSite=Strict`, with no `Domain`; `Expires` and `Max-Age` point to the absolute session expiry. PostgreSQL stores only the SHA-256 hash of the random cookie token, never its value; IP addresses and user agents are not stored. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` and accepts `1m` to `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` and accepts `1m` to `365d`. The idle timeout cannot exceed the absolute lifetime; invalid values stop startup. Active requests extend the idle deadline, not the absolute deadline.
|
||||
|
||||
`IDENTITY_KEY_SECRET` must contain at least 32 bytes and stay the same across backend restarts and instances. It also derives the CSRF key with the purpose label `lincodex/identity/session-csrf/v1`; changing the shared secret invalidates old CSRF values but does not revoke PostgreSQL sessions, and `GetCurrentSession` returns the new value. After a successful password check, creation of a new session and revocation of an incoming active session commit in one transaction. A failed login does not revoke the old session. Logout clears an expired or revoked cookie; an Origin or CSRF failure neither revokes nor clears a valid session.
|
||||
|
||||
### Consent ledger
|
||||
|
||||
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.
|
||||
@@ -734,21 +742,21 @@ What the ports guarantee (`outbound.ConsentRepositories`, available on `UnitOfWo
|
||||
|
||||
### 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`.
|
||||
Implemented: `RegisterAccount` and `ResendEmailVerification` are served by `backend/internal/usecase/identity/register.go` (`identity.Registration`) behind the handler `backend/internal/adapter/primary/http/v1/auth.go`. Without `DATABASE_URL` both answer 501 as before. The router mounts `middleware.ClientIP` with `TRUSTED_PROXY_CIDRS`.
|
||||
|
||||
One transaction. A new address creates the account (scenario and the first `onboarding_step` of the scenario), the C1 record (`GrantAtRegistration`, current text version and hash, source `registration`), the SHA-256 hash of a one-time token bound to the registration version, and the verification delivery (`ServiceMailer.EnqueueVerification`); the sending worker sends it later through the mail transport. C4 and every other purpose are never recorded: the body accepts only C1. Re-registration of an unverified address follows the lock order of the identity repositories (invalidate tokens, then `AdvanceRegistration`, then the new C1). An address that is already verified changes nothing and receives nothing: the "you already have an account" notice is not implemented, because any message to a verified address needs its own template and its own limit, and silence cannot reveal the account.
|
||||
|
||||
Pending credentials (pre-hijack protection). Every registration, the first and each repeat, stores its password hash, scenario, and first onboarding step on its own verification token (columns `pending_*` of `email_tokens`, migration 00014). A repeat registration of an unverified address never changes the credentials, scenario, or onboarding step of the `users` row: `UserRepository.AdvanceRegistration` only advances the registration version and the registration time (and discards the earlier registration C1), and the new token carries the new pending credentials. A resend copies the pending credentials of the newest token of the registration. The `password_hash`, `scenario`, and `onboarding_step` of an unverified account row are not authoritative until a verification applies the clicked token's pending data: they hold the first registrant's values only because the columns are mandatory, and no code may authenticate with them or trust them (see the comment on `domain.User`). Invalidating a token (`InvalidateActive`) clears its `pending_*` columns, and a CHECK constraint keeps an invalidated token from holding a pending hash. A resend that finds no pending credentials for the registration issues nothing.
|
||||
|
||||
Email confirmation (`ConfirmEmail`) is implemented. It requires the password saved with that token's registration and checks it against the pending hash. In one transaction the backend checks the current registration version and its C1 record, consumes the token, verifies the address, applies the token's password hash, scenario, and onboarding step to the account, clears `pending_*`, and records exactly one secret-free `identity.email_verified` event. Any refusal leaves the account and token unchanged. Unknown, used, replaced, or superseded tokens, a wrong password, and missing pending credentials answer `verification_token_invalid`; an expired token answers `verification_token_expired`. The Origin must match exactly `APP_PUBLIC_URL`. Confirmation does not create a session. The frontend confirmation screen is still a placeholder; login and session recovery are not implemented.
|
||||
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.
|
||||
|
||||
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.
|
||||
Login accepts only a verified email and checks the account's stored password, never pending registration credentials. An unknown address, wrong password, and invalid stored hash receive the same `invalid_credentials`; unknown addresses and invalid hashes also run `VerifyDummy`, and an invalid stored hash is logged without the email or hash. A correct password for an unverified account answers `email_not_verified` and creates no session. Successful login creates a new session; if the request carried a valid session cookie, the backend revokes it and creates the new session in one transaction. Failed login does not revoke an existing session, and a malformed cookie cannot become a principal.
|
||||
|
||||
Order of checks in registration: validation of the whole body and the C1 text version, replay check, rate limit, password hash (on every branch, before the account is read), transaction. A validation error (400) never depends on the stored accounts and consumes no limit.
|
||||
|
||||
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. 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.
|
||||
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), applies to registration, confirmation, resend, and login; it 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). Login also uses `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (default 10 per hour) for normalized email, whether or not an account exists. Both configurable identity limits accept values from 1 to 10000. 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. 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.
|
||||
|
||||
|
||||
+11
-11
@@ -70,9 +70,9 @@ The Compose health check runs `kafka-broker-api-versions.sh` against `localhost:
|
||||
|
||||
The backend receives `KAFKA_BROKERS`, a comma-separated list of `host:port` bootstrap addresses. Compose supplies `kafka:9092`; a directly launched Go process defaults to `localhost:9092`. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The outbox relay connects to these brokers in the background: the backend does not wait for Kafka at startup, and `/readyz` does not check Kafka. The advertised address `kafka:9092` resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue.
|
||||
|
||||
`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).
|
||||
`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 use it. 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 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).
|
||||
`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 idempotency records and rate limits, and derives the session CSRF key; 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 changes the lookup keys for the last 24 hours of counters and idempotency records and invalidates existing CSRF values, but it does not revoke sessions stored in PostgreSQL. `VERIFICATION_MAIL_MIN_INTERVAL` (default `1m`) and `VERIFICATION_MAIL_DAILY_LIMIT` (default `5`) bound verification mail per address; an empty value means the default. `IDENTITY_CLIENT_HOURLY_LIMIT` defaults to `30` and accepts `1` to `10000`; it limits registration, confirmation, resend, and login attempts per client address when that address is resolved through the trusted proxy chain. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` defaults to `10` and accepts `1` to `10000`; it limits login attempts per normalized email whether or not an account exists. Confirmation is also limited to 5 attempts per token per hour. `IDENTITY_SESSION_IDLE_TIMEOUT` defaults to `24h` and accepts `1m` to `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` defaults to `168h` and accepts `1m` to `365d`. The idle timeout must not exceed the absolute lifetime; invalid values stop backend startup. 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) and [server-side sessions](ARCHITECTURE.md#server-side-sessions).
|
||||
|
||||
down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop.
|
||||
|
||||
@@ -237,7 +237,7 @@ Current state: this build contains the `disabled` and `resend` transports. With
|
||||
|
||||
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).
|
||||
`resend` sends each message with one request to `https://api.resend.com/emails`. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in `EMAIL_FROM` shows up as a rejected send. One attempt is limited by `EMAIL_TIMEOUT`. The transport follows no redirects, never retries, and logs nothing; the sending worker owns retries, backoff, rate-limit pacing, and outcome records, while the quota gate schedules a known daily or monthly reset (see [Mail quotas](#mail-quotas)). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is `unknown` (`delivery_uncertain`), not a failure. The backend process follows the standard `HTTPS_PROXY` and `NO_PROXY` variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend `environment`. The full mapping of answers is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-transport).
|
||||
|
||||
`disabled` sends nothing. Every send returns `ErrMailChannelUnavailable` without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains `mail transport selected` with `email_provider` and, for `disabled`, a `mail delivery is disabled` warning.
|
||||
|
||||
@@ -260,7 +260,7 @@ Compose passes these variables from the root `.env`; it passes an unset `EMAIL_Q
|
||||
|
||||
### Mail deliveries
|
||||
|
||||
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; it needs no setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until product notification sending is implemented. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
|
||||
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; migration 00017 adds the unknown-outcome decision journal and rebuilds the due partial index under a table lock. Rolling 00017 back drops that journal and its audit history, so export the decisions before rollback. Neither migration needs a setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until product notification sending is implemented. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
|
||||
|
||||
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand.
|
||||
- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet.
|
||||
@@ -280,7 +280,7 @@ Migration 00007 creates `mail_quota_usage` and the reservation journal `mail_quo
|
||||
- The internal /metrics endpoint shows the current windows of the configured account, read every 30 seconds: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients`, and `lincodex_mail_quota_provider_exhausted` (1 after a quota refusal by the provider), each with the labels `provider` and `window` (`day` or `month`). `EMAIL_ACCOUNT` is not a label, because the operator chooses its text; with `EMAIL_PROVIDER=disabled` there are no quota series. The alert `LincodexMailQuotaUsedUp` (severity info) fires while a window is used up.
|
||||
- Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored `next_attempt_at`; or deliberately switch the transport or account (see [Mail deliveries](#mail-deliveries) for what stays pinned). Do not lower `used_recipients` or edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused.
|
||||
- `provider_exhausted_at` on a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan.
|
||||
- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy.
|
||||
- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. The local operator command is for terminal unknown outcomes, not quota-waiting deliveries.
|
||||
- Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching `EMAIL_PROVIDER` to `smtp` starts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit.
|
||||
|
||||
### Sending service mail
|
||||
@@ -290,11 +290,11 @@ The backend process runs one sending loop for service identity mail (email verif
|
||||
- Several backend instances may run at once. Each claims a delivery with `FOR UPDATE SKIP LOCKED` and a lease, so one delivery is sent by one instance, and the provider call carries the stable idempotency key `delivery/<id>`. During a rolling deployment the instance that stops finishes its send within 5 seconds, stores the result, and exits.
|
||||
- With `EMAIL_PROVIDER=disabled` the loop does not start and the log says `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` is 0, nothing is sent, and stored service mail waits for the next start with a transport. The worker never spins: after a pass that could not send it backs off.
|
||||
- Before it sends, the worker checks the token and the account. A delivery that must not go out ends as `cancelled` with a `cancel_reason`, no attempt, and no quota use: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid`, or `processing_failed`. The user-caused reasons are normal: a user asked for a new link, confirmed the address, registered again, or waited too long. To see the reasons: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. A user sees a cancelled mail as "not sent, request a new one".
|
||||
- Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A refusal for now (`temporary`, `rate_limited`) leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the same key and body; it repeats until it succeeds, is refused for good, or the token expires and the delivery is cancelled. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas).
|
||||
- `unknown` is never retried by the worker. It means that the provider may have accepted the mail (a lost answer, a 5xx answer) or that the worker that sent it was lost for longer than the provider's 24-hour idempotency window. Check the provider's own log for the message; the alert `LincodexMailDeliveryUnknownOutcome` fires meanwhile. A manual retry with an audit record is planned with the retry policy.
|
||||
- Provider answers: `accepted` means accepted by the provider, not delivered to a person; the backend has no delivery confirmation. A confirmed temporary or 429 refusal means the provider did not accept the message: it leaves the delivery `pending` with a later `next_attempt_at`, and the retry reuses the pinned account, key, and body. Resend's `Retry-After` is a lower bound. Such a refusal does not erase uncertainty from an earlier unknown attempt. After the 23-hour cutoff, confirmed refusals continue only under a pending manual decision; without it, the worker stops and leaves the earlier unknown for operator review. A permanent or invalid-request refusal ends it as `rejected`: read the provider code in `delivery_attempts.provider_code` (for example `validation_error` for an unverified sender domain, or `invalid_api_key`) and fix the cause. A quota answer parks it in `waiting_quota`; see [Mail quotas](#mail-quotas).
|
||||
- An uncertain Resend outcome is retried automatically with the same pinned account, key, and stored body only until 23 hours after the database-recorded first send, one hour before the provider's documented 24-hour idempotency expiry. The worker checks this cutoff again immediately before the network call. After the cutoff, or after a manually authorized send-start whose result is lost, automatic retries stop and the alert `LincodexMailDeliveryUnknownOutcome` asks for review. Check the provider's own log first. For a terminal `unknown` row, use `make -C backend mail-retry ARGS='inspect --delivery <uuid>'` to see metadata and the duplicate warning, then `make -C backend mail-retry ARGS='retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk'` to schedule one audited decision. The command requires the local database credential, is available only with `EMAIL_PROVIDER=resend`, prints its warning before changing state, and never sends mail. The actor is an audit handle rather than authentication, and there is no HTTP operator endpoint. A manual decision does not restart the provider's key window: after another unknown or lost manual send result, the worker stops and requires another decision. An expired idempotency key may produce a duplicate despite the warning.
|
||||
- A claimed delivery holds a lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. A row whose `claimed_until` is long past means that its worker died; another instance takes it over by itself. Do not clear leases by hand.
|
||||
- `content_invalid` and `processing_failed` are not user actions: the first means that a stored row does not match its content hash (a manual edit) or holds a message no transport accepts, the second that the worker failed on the row three times in a row (the retries are spaced by the retry schedule). The alert `LincodexMailCancelledBroken` fires on an increase; read the worker logs for the `delivery_id` and inspect the row's metadata. A row that keeps failing does not block the others: it is retried later (`failure_count`, `next_attempt_at`) and then cancelled.
|
||||
- The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. Do not copy bodies of waiting mail anywhere.
|
||||
- The bodies of a token mail are cleared when it is accepted, rejected, or cancelled (`body_redacted_at` is set), so database dumps and backups of finished token mail hold no token. A mail that is `unknown` keeps its body until an operator resolves it. The retry command displays no address, body, key, or token. Do not copy bodies of waiting mail anywhere.
|
||||
- The lease is measured by the database clock, so clock differences between instances do not matter; only the database's clock does. The call to the provider is bounded by what is left of the lease; with `SHUTDOWN_TIMEOUT` at its default of 10 seconds a stopping instance finishes within 3 seconds of grace plus 5 seconds to store the answer. Lowering `SHUTDOWN_TIMEOUT` shortens the second part (at least 1 second); a result that cannot be stored in time is covered by the takeover.
|
||||
- Logs name a delivery only by `delivery_id`, its kind, and the outcome or cancel reason, for example `service mail was not sent because it is no longer valid`; never an address, a token, a link, or a body. If a token or link appears in a log, treat it as a defect.
|
||||
- The internal /metrics endpoint shows `lincodex_mail_sender_running` (1 while this instance's loop runs, 0 otherwise; no labels) and `lincodex_mail_sender_cancelled_total{reason}` (a counter per cancel reason, zero included) next to the delivery gauges, which also have the status `cancelled`.
|
||||
@@ -378,9 +378,9 @@ All names and addresses come from `deploy/edge/edge.env` (copy `deploy/edge/edge
|
||||
|
||||
### One origin and the Secure cookie
|
||||
|
||||
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.
|
||||
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 backend issues the `__Host-lincodex_session` cookie with `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict`, and no `Domain`; `Expires` and `Max-Age` match the absolute session expiry. 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>`. Login and logout require the sole `Origin` value to exactly match `APP_PUBLIC_URL`; the backend does not derive the allowed origin from `Host` or trust forwarded headers for this check.
|
||||
|
||||
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).
|
||||
Registration, verification resend, email confirmation, login, current-session reading, and logout are available through the backend API. Frontend registration and confirmation screens remain placeholders, and the backend does not read `X-Forwarded-Proto` for the Origin check. The browser login path through the edge has not been verified end to end.
|
||||
|
||||
### Request handling at the edge
|
||||
|
||||
@@ -488,7 +488,7 @@ Ubuntu's `certbot.timer` runs `certbot renew` twice a day and renews a certifica
|
||||
systemctl list-timers certbot.timer
|
||||
sudo certbot certificates
|
||||
|
||||
A reload starts new workers with the new certificate and configuration and lets the old workers finish their open connections, so in-flight requests and keep-alive connections are not dropped. Sessions are not held by nginx at all: the planned design keeps them in PostgreSQL behind an opaque cookie, so reloading or restarting nginx or the tunnel does not sign anyone out. Because sign-in is not implemented yet, the available proof is a request in flight and a kept connection across `systemctl reload nginx`: both complete without a 5xx, and the next request on the same connection succeeds.
|
||||
A reload starts new workers with the new certificate and configuration and lets the old workers finish their open connections, so in-flight requests and keep-alive connections are not dropped. The backend stores session state in PostgreSQL, not nginx: reloading or restarting nginx or the tunnel does not revoke a session while the backend and database remain available. The check below verifies only an in-flight request and keep-alive behavior across `systemctl reload nginx`; browser sign-in persistence after reload has not been verified end to end.
|
||||
|
||||
### Verification
|
||||
|
||||
|
||||
+36
-28
@@ -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 на внутреннем порту.
|
||||
|
||||
Регистрация и подтверждение email работают через API backend. Экраны регистрации и подтверждения во frontend остаются заглушками; вход и остальные перечисленные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
|
||||
Регистрация, подтверждение email, вход и базовые операции с текущей сессией работают через API backend. Экраны регистрации и подтверждения во frontend остаются заглушками; остальные перечисленные продуктовые сценарии пока не реализованы: роли, профили, тесты, грейды, поиск, приглашения, загрузка и анализ резюме, PDF и интеграция с ФСП. ML не возвращает вымышленные результаты. Проверки доступности и технический smoke не подтверждают бизнес-сценарий.
|
||||
|
||||
Подробности запуска, дерева исходников и проверки собраны в [руководстве разработки](DEVELOPMENT.md), [руководстве по развертыванию](DEPLOY.md) и [руководстве по проверкам](TESTING.md).
|
||||
|
||||
@@ -202,11 +202,11 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
- `accepted`: провайдер принял запрос и вернул `ProviderMessageID`. Это не доставка и не прочтение.
|
||||
- `rejected`: провайдер не принял письмо. Либо он ответил отказом, либо транспорт сломался до полной записи запроса (DNS, соединение или TLS), и полный запрос до провайдера не дошел; второй случай всегда `temporary`, и повтор не может продублировать письмо. `Rejection` равен `permanent`, `invalid_request`, `rate_limited`, `quota_exhausted` или `temporary`.
|
||||
- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`), например таймаут, обрыв соединения после записи запроса или ошибка провайдера во время обработки. Это не «не отправлено»: повтор использует тот же ключ идемпотентности и то же содержимое. Дедупликация у провайдера ограничена окном (24 часа у Resend); после него повтор может отправить письмо дважды, поэтому слой доставки обязан прекратить повторы и передать случай оператору.
|
||||
- `unknown`: запрос мог дойти до провайдера, но однозначного ответа нет (`delivery_uncertain`), например таймаут, обрыв соединения после записи запроса или ошибка провайдера во время обработки. Это не «не отправлено»: повтор использует тот же ключ идемпотентности и то же содержимое. Resend хранит ключ идемпотентности 24 часа. Worker прекращает автоматические повторы через 23 часа, оставляя часовой запас; после этого оператор решает, запускать ли повтор, поскольку старый ключ может уже не защитить от дубля.
|
||||
|
||||
`rejected` и `unknown` могут содержать `RetryAfter`, подсказку провайдера о паузе или паузу, которую транспорт вычислил по документированным правилам провайдера, и `ProviderCode`, имя ошибки провайдера. Отказ `quota_exhausted` еще и называет исчерпанное окно в `QuotaPeriod` (`day` или `month`), если провайдер это сообщил; иначе поле пустое. Транспорт берет `ProviderCode` только из своего фиксированного списка документированных имен, а иначе оставляет пустым; поэтому в нем не бывает текста провайдера, и его можно логировать и хранить.
|
||||
|
||||
Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Повторы, backoff и учет результатов относятся к единому запланированному слою доставки, а не к транспорту. Сценарии подтверждения обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера.
|
||||
Ненулевая ошибка значит, что письмо точно не покинуло процесс: `ErrMailChannelUnavailable` в режиме `disabled`, `ErrInvalidOutgoingMail` для некорректного письма или ошибка контекста, если контекст вызывающего завершился до записи запроса. Сбой до записи запроса при живом контексте - это `rejected`/`temporary`, а не ошибка. Транспорт делает один запрос; worker доставки отвечает за повторы, задержки и запись исходов. Сценарии подтверждения обязаны считать `ErrMailChannelUnavailable` неотправкой: он никогда не подтверждает адрес и не заменяет проверку аккаунта. `OutgoingMail` скрывает себя в выводе `fmt` и `slog`, а ошибки и логи транспорта никогда не содержат получателей, темы, тела писем, учетные данные или сырые ответы провайдера.
|
||||
|
||||
Транспорт Resend использует `net/http` без SDK. Один `Send` - это один `POST https://api.resend.com/emails` с полями `from` (`EMAIL_FROM`), `to` (один получатель), `subject`, `text` и `html` (пустая или пробельная часть не передается), ключом в `Authorization: Bearer`, заголовком `User-Agent` и `Idempotency-Key`, равным ключу письма. Resend хранит ключ 24 часа и на тот же ключ с тем же телом возвращает исходный результат без повторной отправки, поэтому повтор обязан передать сохраненное тело под тем же ключом; измененное тело под старым ключом - это конфликт, а не повод создать новый ключ. `EMAIL_TIMEOUT` ограничивает всю попытку. Клиент не следует редиректам, использует HTTP/1.1 и открывает новое соединение для каждой отправки: keep-alive соединение, которое сервер закрыл по простою, сломалось бы уже после передачи запроса и превратило бы письмо, которого Resend не видел, в ложный `unknown`. У запроса также нет `GetBody`, потому что `net/http` считает POST с `Idempotency-Key` повторяемым после обрыва переиспользованного соединения. В адаптере нет цикла повторов, и он ничего не логирует. Ответ читается не больше 64 KiB; разбираются только идентификатор письма и `name` ошибки, а сообщение провайдера и тело ответа не сохраняются.
|
||||
|
||||
@@ -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`, поэтому запросы уведомлений ждут отправки. Регистрация и повторная отправка создают письма подтверждения через `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` содержит:
|
||||
|
||||
@@ -243,7 +243,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
- Получателя: `recipient_user_id`, внешний ключ на `users` с `ON DELETE CASCADE`, и `recipient_email`, форма адреса аккаунта для доставки на момент создания.
|
||||
- Содержимое: `kind` (`verification`, `password_reset` или `notification`), `template_version` (`<kind>.v<N>`), `subject`, `text_body`, `html_body` и `content_sha256` по версии, теме и обеим частям - тот же digest, что у шаблонов писем (`domain.MailContentHash`).
|
||||
- Аккаунт провайдера: `provider` и `provider_account`, значения `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` на момент создания. Это идентичность конфигурации, а не секрет.
|
||||
- Состояние попыток: `status`, `attempt_count`, `next_attempt_at`, `last_attempt_at`, `provider_message_id`, оптимистичная `version`, `created_at` и `updated_at`; все время берется из часов приложения.
|
||||
- Состояние попыток: `status`, `attempt_count`, `next_attempt_at`, `last_attempt_at`, `provider_message_id`, оптимистичная `version`, `created_at` и `updated_at`. Время создания, изменения и следующей попытки берется из часов приложения; начало первого запроса и lease - из часов базы.
|
||||
|
||||
Путь создания:
|
||||
|
||||
@@ -272,7 +272,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| `pending` | Ждет первую попытку или повтор после отказа `temporary` или `rate_limited` | Обязательно: когда доставка должна быть отправлена |
|
||||
| `accepted` | Провайдер принял письмо и вернул `provider_message_id`: "принято провайдером". Это не доставка человеку и не прочтение; ни один статус этого не утверждает | Нет; конечный |
|
||||
| `rejected` | Отказ `permanent` или `invalid_request`; причину нужно устранить | Нет; конечный |
|
||||
| `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Это никогда не "не отправлено": повтор использует тот же ключ и сохраненное тело | Необязательно; отсутствие значит, что автоматического повтора нет |
|
||||
| `unknown` | Попытка могла дойти до провайдера (`delivery_uncertain`). Повтор использует закрепленные аккаунт, ключ и тело | Необязательно; без срока требуется решение оператора |
|
||||
| `cancelled` | Письмо намеренно не отправлено и не будет: токен или аккаунт перестали соответствовать доставке, или сохраненное письмо нельзя отправить. `cancel_reason` говорит почему; попытка не записывается | Нет; конечный |
|
||||
| `waiting_quota` | Исчерпана квота провайдера или локальная квота | Необязательно: ожидаемый сброс (см. [Квоты почты](#квоты-почты)); отсутствует, когда момент сброса неизвестен, например после ответа провайдера о квоте без окна и без паузы, и решение принимает оператор |
|
||||
|
||||
@@ -285,7 +285,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Каждое изменение увеличивает `version`, и хранилище применяет его только поверх предыдущей версии. Время следующей попытки задает политика повторов вызывающего кода, и оно должно соответствовать целевому статусу; CHECK `deliveries_next_attempt_matches_status` повторяет это правило, а `deliveries_provider_message_id_when_accepted` требует ID провайдера ровно для `accepted`.
|
||||
|
||||
Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. История нужна оператору, чтобы оценить неизвестный исход, от нее (от первой попытки) отсчитывается конец 24-часового окна ключа, и на нее ссылается аудит ручного решения. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки.
|
||||
Попытки. Текущее состояние лежит в счетчиках `deliveries`, поэтому worker читает одну строку, а каждая попытка - отдельная строка `delivery_attempts`: номер, время, исход, причина отказа, код провайдера, ID письма у провайдера, подсказка ожидания, итоговый статус и время следующей попытки. Возраст для 23-часового автоматического cutoff отсчитывается от `first_send_started_at`, который БД записывает при первом начале запроса. Если ручной вызов начался, но его lease истек до записи ответа, восстановление добавляет `unknown` попытку до планирования нового решения; время этой записи не раньше прошлого изменения доставки. Решения хранятся в `delivery_retry_decisions`: ID доставки, номер попытки, handle оператора, явное подтверждение риска дубля, факт истекшего lease и время решения. В журнале нет внешнего ключа, поэтому удаление аккаунта не удаляет аудит; триггеры запрещают UPDATE, DELETE и TRUNCATE. Подсказка ожидания хранится точно как Go `time.Duration` в наносекундах (`retry_after_ns`), поэтому чтение после записи ее не меняет. `RecordAttempt` сохраняет доставку и попытку одним запросом: data-modifying CTE обновляет доставку, только пока ее версия равна версии до попытки, и добавляет попытку, только если обновление прошло. Второй писатель той же попытки получает `outbound.ErrDeliveryVersionConflict` и ничего не записывает. Trigger отклоняет UPDATE попытки.
|
||||
|
||||
Учет квот не строится на этой истории: каскад от удаления аккаунта удаляет его доставки и попытки, поэтому подсчет отправок по `delivery_attempts` потерял бы отправки удаленных аккаунтов и позволил бы превысить квоту провайдера. Поэтому у квоты собственный счетчик без каскада с ключом из провайдера, аккаунта провайдера и UTC-суток или месяца; см. [Квоты почты](#квоты-почты).
|
||||
|
||||
@@ -293,7 +293,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Миграция `00012_add_delivery_sending.sql` аддитивна; существующие строки остаются корректными. Она добавляет в `deliveries`: `email_token_id` (необязательный внешний ключ на `email_tokens.id` для писем с токеном, неизменяемый, как остальное содержимое; NULL для уведомлений), `cancel_reason` (задан ровно когда статус `cancelled`, CHECK ограничивает его перечисленными причинами), столбцы lease `claim_owner` и `claimed_until` (оба или ни одного; lease держит только доставка, которую worker еще может отправить), `first_send_started_at` (когда начался первый запрос, по часам базы), `failure_count` (подряд идущие сбои worker на строке), `body_redacted_at` (тела письма с токеном очищены), статус `cancelled` с его CHECK и два частичных индекса: `deliveries_due_idx` по `(next_attempt_at, id)`, чей предикат называет служебные виды и статусы, которые берутся снова, поэтому строки уведомлений в него не попадают, а холостой опрос их не сканирует, и индекс по `email_token_id`. Trigger `deliveries_refuse_content_change` разрешает еще ровно одно изменение тел: у конечного письма с токеном оба тела один раз становятся пустыми вместе с `body_redacted_at`. В `email_tokens` добавляется назначение токена `password_reset`. Откат миграции превращает отмененные доставки в отклоненные и удаляет токены сброса. Запланировано: отмена доставки по отозванному разрешению.
|
||||
|
||||
Хранилище дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota`, `Cancel` и `Rebind`, а для worker отправки - `ClaimDue`, `ReleaseClaim` и `ServiceMailState`.
|
||||
Хранилище дает `Get`, `ListAttempts`, `RecordAttempt` с проверкой версии, `WaitForQuota`, `Cancel` и `Rebind`, а для worker отправки - `ClaimDue`, `ReleaseClaim` и `ServiceMailState`. Миграция `00017_retry_unknown_mail.sql` добавляет маркеры ручного цикла, неизменяемый журнал решений и `unknown` в предикат индекса очереди. Она перестраивает частичный индекс очереди и берет блокировку таблицы на время перестройки. Откат удаляет журнал решений вместе с данными аудита; перед намеренным откатом сохраните экспорт.
|
||||
|
||||
### Квоты почты
|
||||
|
||||
@@ -352,8 +352,8 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Один проход `ServiceMailSender.ProcessNext` проводит одну доставку через три шага:
|
||||
|
||||
1. Транзакция захвата. `DeliveryRepository.ClaimDue` берет самую просроченную доставку с `FOR UPDATE SKIP LOCKED`: вид `verification` или `password_reset` (литералы совпадают с предикатом `deliveries_due_idx`, поэтому опрос читает только этот малый индекс), статус `pending` или `waiting_quota`, `next_attempt_at` наступил, доставка закреплена за настроенным аккаунтом провайдера и ее не держит живой lease. Он записывает `claim_owner` и `claimed_until` (lease), не меняя версию и время обновления, поэтому несколько процессов никогда не возьмут одну доставку. Lease измеряется часами базы данных (`clock_timestamp()` плюс длина lease, и он жив, пока `claimed_until` позже `clock_timestamp()`), а не часами экземпляра приложения, поэтому экземпляры с разными часами не могут перехватить живой lease или держать мертвый; сроки доставок остаются на часах приложения, которые их записали. У доставки в `unknown` или в `waiting_quota` без времени нет срока, и она ждет оператора. В той же транзакции отправитель переносит на настроенный аккаунт письма, сохраненные при `EMAIL_PROVIDER=disabled` (это разрешено только до первой попытки, пока ключ не видел ни один провайдер), выполняет проверку ниже, а затем `QuotaGate.PrepareSend`, который резервирует получателя или переводит доставку в `waiting_quota`. Транзакция фиксируется до вызова транспорта, поэтому медленный провайдер никогда не держит блокировку строки. Сбой внутри нее (детерминированный, например строка, которую нельзя восстановить) откатывает и lease, поэтому сбой записывается для строки отдельной транзакцией; см. "Сбойные строки".
|
||||
2. Проверка прямо перед отправкой, одна короткая транзакция: она блокирует строку доставки (только для владельца lease), заново читает токен и аккаунт через `ServiceMailState`, поэтому отзыв после фиксации захвата учитывается, и в первый раз записывает `first_send_started_at`. Письмо, которое больше нельзя отправлять, отменяется, а резервирование возвращается. Затем один вызов `MailSender.Send` с сохраненным содержимым и стабильным ключом идемпотентности `delivery/<id>`. Отправитель никогда не повторяет вызов. Вызов ограничен тем, что осталось от lease после захвата и бюджета расчета, и льготным периодом остановки.
|
||||
1. Транзакция захвата. `DeliveryRepository.ClaimDue` берет самую просроченную доставку с `FOR UPDATE SKIP LOCKED`: вид `verification` или `password_reset` (литералы совпадают с предикатом `deliveries_due_idx`, поэтому опрос читает только этот малый индекс), статус `pending`, `waiting_quota` или запланированный `unknown`, наступивший `next_attempt_at`, доставка закреплена за настроенным аккаунтом провайдера и ее не держит живой lease. Неопределенный исход автоматически ставится на повтор только до cutoff; `unknown` без срока ждет оператора. Однократное разрешение оператора тоже ставит `unknown` в очередь. Захват записывает `claim_owner` и `claimed_until` (lease), не меняя версию и время обновления, поэтому несколько процессов не возьмут одну доставку. Lease измеряется часами базы данных (`clock_timestamp()` плюс длина lease, и он жив, пока `claimed_until` позже `clock_timestamp()`), а не часами экземпляра приложения; сроки доставок остаются на часах приложения, которые их записали. В той же транзакции отправитель переносит на настроенный аккаунт письма, сохраненные при `EMAIL_PROVIDER=disabled` (это разрешено только до первой попытки, пока ключ не видел ни один провайдер), выполняет проверку ниже, а затем `QuotaGate.PrepareSend`, который резервирует получателя или переводит доставку в `waiting_quota`. Транзакция фиксируется до вызова транспорта, поэтому медленный провайдер никогда не держит блокировку строки. Сбой внутри нее (детерминированный, например строка, которую нельзя восстановить) откатывает и lease, поэтому сбой записывается для строки отдельной транзакцией; см. "Сбойные строки".
|
||||
2. Проверка прямо перед отправкой, одна короткая транзакция: она блокирует строку доставки (только для владельца lease), заново читает токен и аккаунт через `ServiceMailState`, поэтому отзыв после фиксации захвата учитывается, и записывает начало запроса по часам базы. Для неопределенного результата cutoff 23 часа повторно проверяется после квоты и захвата lease, прямо перед сетевым вызовом. Однократное разрешение оператора расходуется при записи send-start. Письмо, которое больше нельзя отправлять, отменяется, а резервирование возвращается. Затем один вызов `MailSender.Send` с сохраненным содержимым и стабильным ключом идемпотентности `delivery/<id>`. Транспорт не повторяет вызов. Вызов ограничен тем, что осталось от lease после захвата и бюджета расчета, и льготным периодом остановки.
|
||||
3. Транзакция расчета. Она сначала блокирует строку доставки (только пока этот worker держит lease), затем `QuotaGate.SettleSend` и `DeliveryRepository.RecordClaimedAttempt` фиксируются вместе, а lease заканчивается вместе с попыткой. `RecordClaimedAttempt` применяется только поверх версии доставки и только для владельца lease, поэтому worker, чей lease перехвачен, записать не может, а если два worker дошли до этого шага для одной доставки, сохраняется только первая; вторая откатывается вместе с расчетом квоты и сообщает `lease_lost`. Сбой базы при сохранении ответа повторяется до трех раз в пределах бюджета расчета, потому что ответ до сохранения существует только в памяти.
|
||||
|
||||
Бюджет времени. Lease равен `EMAIL_TIMEOUT` плюс одна минута. Сначала идут захват и проверка; вызов получает остаток lease за вычетом бюджета расчета (20 секунд), поэтому захват, вызов и весь расчет умещаются в lease. Когда остановка началась, бюджет расчета - меньшее из 5 секунд и `SHUTDOWN_TIMEOUT` за вычетом 3 секунд льготного периода остановки (не меньше 1 секунды), поэтому процесс останавливается в пределах своего тайм-аута остановки, по умолчанию 10 секунд (период остановки в Compose - 30 секунд). Результат, который не удалось сохранить вовремя, покрывает перехват ниже.
|
||||
@@ -385,14 +385,14 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
| `rejected` `permanent` или `invalid_request` | `rejected` | нет | возвращается |
|
||||
| `rejected` `temporary` или `rate_limited` | `pending` | сейчас плюс `RetryPolicy`: 1 минута, удвоение до 30 минут, не меньше `Retry-After` провайдера | возвращается |
|
||||
| `rejected` `quota_exhausted` | `waiting_quota` | сброс, который вернул шлюз (ближайшие 00:00 UTC для суток, первое число следующего месяца для месяца); нет, если провайдер не назвал окно | окно отмечено заполненным |
|
||||
| `unknown` | `unknown` | нет: автоматического повтора нет | считается |
|
||||
| `unknown` | `unknown` | расписание повторов до cutoff 23 часа, затем без срока до решения оператора | считается |
|
||||
| Ошибка `Send`: нет транспорта (`ErrMailChannelUnavailable`) или context завершился | без изменений, lease освобожден | остается срок | возвращается |
|
||||
| Ошибка `Send`: неверное сообщение (`ErrInvalidOutgoingMail`) | `cancelled`, `content_invalid` | нет | возвращается |
|
||||
| Ошибка `Send`: любая другая без ответа | не считается против строки; она отодвигается по `RetryPolicy`, а worker делает паузу | сейчас плюс `RetryPolicy` | возвращается |
|
||||
|
||||
В расписании повторов нет предела числа попыток намеренно: токен истекает, и тогда проверка отменяет доставку с `token_expired`. К каждой паузе добавляется ограниченный jitter, до пятой части сверх расписания, из подменяемого источника (в тестах nil, поэтому время точное), чтобы доставки, отклоненные вместе, не возвращались вместе. `unknown` никогда не читается как неотправленное и никогда не повторяется worker; решает оператор, и срабатывает alert `LincodexMailDeliveryUnknownOutcome`.
|
||||
В расписании повторов нет предела числа попыток намеренно: токен истекает, и тогда проверка отменяет доставку с `token_expired`. К каждой паузе добавляется ограниченный jitter, до пятой части сверх расписания, из подменяемого источника (в тестах nil, поэтому время точное), чтобы доставки, отклоненные вместе, не возвращались вместе. `unknown` никогда не считается подтвержденным отказом. Подтвержденный отказ доказывает, что именно этот запрос провайдер не принял, но не снимает неопределенность от более ранней попытки `unknown`. Автоматические повторы с тем же закрепленным аккаунтом, ключом и телом заканчиваются через 23 часа от первого send-start; один час оставлен как запас до 24-часового срока Resend. Операторское решение требует handle, явного подтверждения риска дубля и записи в append-only audit. Worker выполняет его только при `EMAIL_PROVIDER=resend`. `make -C backend mail-retry ARGS='inspect --delivery <uuid>'` показывает метаданные и предупреждение; `make -C backend mail-retry ARGS='retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk'` сначала печатает предупреждение, затем атомарно записывает решение и ставит один ручной цикл в очередь, но сам не отправляет письмо. Для команды нет HTTP-интерфейса; доступ ограничен доступом к локальному процессу и учетным данным БД, а actor - только handle для аудита. Старый ключ может уже не дедуплицировать письмо, поэтому повтор способен создать дубль даже после подтверждения риска. После ручного `unknown` или потери lease после send-start автоматический повтора нет, нужна новая команда с подтверждением; подтвержденные временные и 429-отказы продолжают повторы под тем же решением. Alert `LincodexMailDeliveryUnknownOutcome` срабатывает, пока нужен разбор.
|
||||
|
||||
Worker потерян после вызова. Если worker остановился после вызова провайдера, но до сохранения ответа, его lease истекает, и другой worker берет доставку на той же попытке и повторяет запрос с тем же ключом идемпотентности. Resend отвечает на повторный ключ и тело исходным результатом, а шлюз квот повторно использует открытое резервирование, поэтому письмо существует одно и считается один раз. Провайдер хранит ключ 24 часа от первого запроса, поэтому возраст считается от `first_send_started_at` (его по часам базы записывает проверка прямо перед первым запросом), а не от последнего lease: сколько бы worker ни потерялось подряд и какой бы длины ни был lease, когда этот возраст достигает 23 часов (окно за вычетом часового запаса), прежний запрос может быть забыт, и повтор способен отправить письмо дважды, поэтому вместо этого доставка записывается как попытка `unknown` без следующей попытки. То же применяется сразу для транспорта без дедупликации на стороне провайдера (окно ноль, SMTP). Lease, не дошедший до первого запроса, ничего не оставляет под сомнением.
|
||||
Потеря автоматического вызова. Если worker остановился после вызова провайдера, но до сохранения ответа, другой worker может взять ту же попытку и повторить запрос с тем же ключом, пока не наступил cutoff 23 часа. Потерянный результат после ручного send-start записывается как `unknown` и ждет нового решения; восстановление само не вызывает провайдера. Resend отвечает на повторный ключ и тело исходным результатом, а шлюз квот повторно использует открытое резервирование, поэтому письмо существует одно и считается один раз. Провайдер хранит ключ 24 часа от первого запроса, поэтому возраст считается от `first_send_started_at` (его по часам базы записывает проверка прямо перед первым запросом), а не от последнего lease: сколько бы worker ни потерялось подряд и какой бы длины ни был lease, когда этот возраст достигает 23 часов (окно за вычетом часового запаса), прежний запрос может быть забыт, и повтор способен отправить письмо дважды, поэтому вместо этого доставка записывается как попытка `unknown` без следующей попытки. То же применяется сразу для транспорта без дедупликации на стороне провайдера (окно ноль, SMTP). Lease, не дошедший до первого запроса, ничего не оставляет под сомнением.
|
||||
|
||||
Сбойные строки. Сбой одной строки не должен занимать начало очереди. Когда транзакция захвата падает после того, как взяла строку, ее lease откатывается вместе с ней, и та же строка тут же была бы взята снова, а все доставки за ней ждали бы. Против строки считается только сбой, который вызывает сама строка: нарушаемое ею правило домена (`ErrInvalidDelivery`, `ErrDeliveryTransition`, неверное содержимое или адрес), строку нельзя восстановить по причине, отличной от несовпадения хеша, или отказ ограничения данных или целостности (классы SQLSTATE 22 и 23, `outbound.ErrRowFault`). Все остальное о строке ничего не говорит и никогда не считается: завершившийся context, тайм-аут, deadlock, потеря соединения (SQLSTATE 08, 40, 53, 57, XX), ошибка ввода-вывода, отсутствие настройки квоты. Такая ошибка возвращается worker, который делает паузу, как при любом глобальном сбое, а lease истекает или откатывается. Для считаемого сбоя отправитель записывает его короткой отдельной транзакцией (`RecordFailure`): `failure_count` растет, lease заканчивается, и строка снова должна быть отправлена по `RetryPolicy` (исход `row_failed`; следующий проход берет доставку за ней). Запрос не трогает строку, которую другой worker держит под живым lease, поэтому откатившийся захват не может помешать строке, которую кто-то только что взял. Счетчик означает сбои подряд: успешный захват и подготовка (проверка перед отправкой) его очищают, как и записанная попытка. Предохранитель в worker останавливает счет, когда сбои попадают на разные строки проход за проходом: три прохода подряд, упавших на трех разных строках, читаются как глобальный сбой, worker ждет с растущей паузой (проход `row_failed` никогда не крутится сразу), а сбои отодвигаются, но не считаются и ни одна строка не отменяется, пока проход не завершится успешно. После 3 считаемых сбоев подряд строка отменяется с причиной `processing_failed`: это существующий конечный статус, который подходит, оператор его видит, и срабатывает alert ниже, поэтому новый статус не понадобился. Если сбой базы мешает и этой записи, строка остается под своим lease, который истекает.
|
||||
|
||||
@@ -400,7 +400,7 @@ Worker потерян после вызова. Если worker останови
|
||||
|
||||
Цикл и остановка. `worker/mailsender` повторяет проходы: после прохода, обработавшего доставку, сразу идет следующий, после холостого прохода worker ждет 5 секунд, а после сбоя базы, отсутствия транспорта или прерванного вызова ждет с растущей паузой. Когда context завершается, worker больше ничего не захватывает, дает выполняющейся отправке продолжиться 5 секунд, сохраняет ее результат и возвращается; после этого gauge равен 0. Цикл - горутина процесса backend на собственном pool из двух соединений, как у других worker; больший объем дают дополнительные экземпляры, а каждый обрабатывает одну доставку за раз, что подходит для служебной почты при квоте Resend Free.
|
||||
|
||||
Токен в хранилище. Тело письма с токеном содержит одноразовый токен, а токен сброса - примитив захвата аккаунта для любого, кто может читать базу или резервную копию. Когда письмо с токеном достигает `accepted`, `rejected` или `cancelled` (любым путем: попыткой, отменой, отменой испорченной строки или `processing_failed`), тот же запрос делает `text_body` и `html_body` пустыми и ставит `body_redacted_at`; тема, хеш содержимого и версия шаблона остаются. Trigger разрешает ровно это изменение один раз для конечной строки и отклоняет любое другое изменение тел или метки; CHECK `deliveries_body_present` принимает пустое тело только с меткой; домен восстанавливает такую строку как очищенное содержимое (`RestoreRedactedMailContent`), которое отправить нельзя. `unknown` не конечный и сохраняет тело, потому что повтор отправляет его снова; оператор, который его разрешает, должен очистить его. Уведомления не очищаются. Откат миграции 00012 подставляет заглушку в очищенные тела.
|
||||
Токен в хранилище. Тело письма с токеном содержит одноразовый токен, а токен сброса - примитив захвата аккаунта для любого, кто может читать базу или резервную копию. Когда письмо с токеном достигает `accepted`, `rejected` или `cancelled` (любым путем: попыткой, отменой, отменой испорченной строки или `processing_failed`), тот же запрос делает `text_body` и `html_body` пустыми и ставит `body_redacted_at`; тема, хеш содержимого и версия шаблона остаются. Trigger разрешает ровно это изменение один раз для конечной строки и отклоняет любое другое изменение тел или метки; CHECK `deliveries_body_present` принимает пустое тело только с меткой; домен восстанавливает такую строку как очищенное содержимое (`RestoreRedactedMailContent`), которое отправить нельзя. `unknown` сохраняет тело, пока ждет разбора или повтора, потому что worker может повторно отправить сохраненное содержимое. Локальная команда не показывает и не меняет тело. Уведомления не очищаются. Откат миграции 00012 подставляет заглушку в очищенные тела.
|
||||
|
||||
Приватность. Журнал называет доставку только по `delivery_id`, ее виду и закрытым значениям (исход и причина отмены); адрес, токен, ссылка, тема и тело не попадают ни в строку журнала, ни в ошибку, ни в label метрики, а у метрики вообще нет labels. `ServiceMailSender` строит исходящее письмо из сохраненного содержимого и никогда его не логирует; `OutgoingMail` и `Delivery` скрывают себя сами.
|
||||
|
||||
@@ -408,7 +408,7 @@ Worker потерян после вызова. Если worker останови
|
||||
|
||||
Тесты. `integration_test/mail_sender_test.go` запускает локальную имитацию Resend (`resendfixture`, сервер `httptest`, который говорит на части API, используемой транспортом, и доступен через `resend.NewLoopbackSender`, принимающий только loopback endpoint) против PostgreSQL; см. [TESTING.md](TESTING.md). Это только тестовая подмена; production использует настоящий транспорт Resend с фиксированным endpoint.
|
||||
|
||||
Открытые вопросы. Автоматический повтор и эскалация для `unknown` пока не реализованы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема.
|
||||
Открытые вопросы. Отправка продуктовых уведомлений и нужная ей проверка разрешений запланированы; до их реализации уведомления ждут и не учитываются в gauge просрочки, поэтому очередь уведомлений не включает `LincodexMailDeliveriesOverdue` (gauge `lincodex_mail_delivery_oldest_due_pending_age_seconds` охватывает `domain.ServiceMailKinds`; его предикат - предикат `deliveries_due_idx`). Идет ли сброс пароля на неподтвержденные аккаунты, решает сценарий сброса. Опрос выполняется каждые 5 секунд, захват читает один индексированный запрос, что подходит для текущего объема.
|
||||
|
||||
### Версии продуктовой политики
|
||||
|
||||
@@ -536,7 +536,7 @@ backend/
|
||||
|
||||
За пределами реализованных потоков 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`) без зарегистрированного продуктового вида задания, usecase регистрации, повторной отправки и подтверждения identity, usecase согласий, который записывает C1 в потоке регистрации, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `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, PostgreSQL сессии и проверку ограниченного набора операций сессии, 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` создает письма подтверждения при регистрации и повторной отправке. Письма сброса пароля относятся к будущему потоку сброса. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
|
||||
|
||||
@@ -646,7 +646,7 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Хранение identity
|
||||
|
||||
Хранение 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).
|
||||
Хранение identity реализовано миграцией `backend/db/migrations/00002_create_identity_tables.sql`, запросами `backend/db/queries/identity.sql`, доменными типами, outbound-портами и адаптером Postgres. Backend API реализует регистрацию, повторную отправку подтверждения, `ConfirmEmail`, вход и базовые операции с текущей сессией. Экраны регистрации и подтверждения во frontend остаются заглушками; см. [контракт API](../../api/README.md#identity-сессии-cookie-и-csrf).
|
||||
|
||||
- `users`: UUIDv7 `id`; `email` - форма для доставки (ASCII без пробелов по краям, регистр как при вводе, возвращается в `Account.email`), и `email_normalized` - уникальный ключ сравнения (тот же адрес, в котором A-Z переведены в нижний регистр); `password_hash` - строка PHC Argon2id v19; `scenario` и `onboarding_step` с CHECK, что шаг относится к сценарию; nullable `email_verified_at`; `registration_version`; `last_registered_at` с частичным индексом по неподтвержденным аккаунтам для запланированной очистки через 7 дней; оптимистичная `version`; `created_at` и `updated_at`. Форма для доставки хранится, потому что RFC 5321 допускает local part с учетом регистра: письмо уходит на адрес в введенном виде, а уникальность не учитывает регистр.
|
||||
- `email_tokens`: `token_hash` (SHA-256, `bytea` из 32 байт, уникальный), `purpose` (`email_verification`; CHECK перечисляет допустимые назначения, поэтому сброс пароля можно добавить позже), `user_id`, `registration_version`, к которой привязан токен, `created_at`, `expires_at`, `consumed_at` и `invalidated_at`. Миграция 00014 добавляет `pending_password_hash`, `pending_scenario` и `pending_onboarding_step`, чтобы каждый токен нес данные своей регистрации. CHECK допускает не больше одного из consumed и invalidated.
|
||||
@@ -659,14 +659,14 @@ contact_grant относится к паре кандидат-компания
|
||||
- База хранит хеши, а не пароли и исходные токены. Токен несет 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 нельзя удалить и нельзя использовать в транзакции, которая его добавила.
|
||||
- Каждое сохраняемое время берется из часов приложения, которые передает вызывающий код, поэтому сроки и проверки по ним используют одни часы. Репозитории отклоняют нулевое время.
|
||||
- Колонки для CSRF нет. `GetCurrentSession` должен вернуть CSRF-токен сессии после перезагрузки страницы, а сохраненный хеш не позволяет его восстановить. Аутентификация сессий может выводить токен из токена сессии с серверным ключом, что не требует хранения, или добавить колонку аддитивной миграцией.
|
||||
- Колонки для CSRF нет. `GetCurrentSession` возвращает токен после перезагрузки страницы: сервер выводит его HMAC-SHA-256 с доменным разделением из cookie-токена и `IDENTITY_KEY_SECRET`, поэтому хранить или восстанавливать исходный токен в БД не нужно. Сравнение выполняется за постоянное время; сам session token в БД хранится только как SHA-256 хеш.
|
||||
|
||||
Что гарантируют порты:
|
||||
|
||||
- `UserRepository.Create` возвращает `ErrEmailTaken` для повторного ключа. `UpdateRegistration` сохраняет результат `domain.User.ReRegister`, только если сохраненная `version` совпадает и email не подтвержден; тот же запрос увеличивает `version` и `registration_version` на единицу, поэтому версию регистрации не выбирает вызывающий код, и удаляет регистрационное C1 прежнего регистранта (см. [Журнал согласий](#журнал-согласий)). `MarkEmailVerified` применяется только к неподтвержденному аккаунту с указанной версией регистрации. В остальных случаях оба возвращают `ErrUserVersionConflict`.
|
||||
- `EmailTokenRepository.Consume` - один `UPDATE ... RETURNING`, который требует непогашенный, неаннулированный и неистекший токен. Параллельные вызовы ждут в очереди на блокировку строки токена; при READ COMMITTED каждый ожидающий заново проверяет строку после завершения владельца блокировки, поэтому успешен ровно один, а если владелец откатился, ожидающий еще может погасить токен. Неудача сообщается как `ErrEmailTokenNotFound`, `ErrEmailTokenConsumed`, `ErrEmailTokenInvalidated` (заменен или выдан для более ранней версии регистрации) или `ErrEmailTokenExpired`. `InvalidateActive` помечает все прежние токены пользователя с этим назначением.
|
||||
- Consume сравнивает версию регистрации токена с аккаунтом только в том виде, в каком его прочитал запрос, без блокировки, поэтому не видит повторную регистрацию, зафиксированную сразу после него. Привязка токена к текущей регистрации поэтому соблюдается, только если подтверждение вызывает `MarkEmailVerified(token.UserID, token.RegistrationVersion)` в той же транзакции и откатывает ее при `ErrUserVersionConflict`; откат возвращает и токен, который затем считается замененным. Usecase подтверждения переводит этот исход в `verification_token_invalid`.
|
||||
- `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` записывает `last_seen_at`, только если сохраненное значение старше более чем на минуту, поэтому частые запросы не переписывают строку, а таймаут простоя может завершить сессию на минуту раньше; `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`.
|
||||
- `SessionRepository.FindActive` и `Touch` получают таймаут простоя от вызывающего кода и принимают только неотозванную сессию до ее абсолютного срока и в пределах таймаута простоя. `Touch` объединяет записи с интервалом, равным меньшему из одной минуты и половины таймаута простоя: частые запросы не переписывают строку, а короткий допустимый idle timeout успевает продлеваться. `Touch` не сдвигает `last_seen_at` назад и не возобновляет завершенную сессию. `Revoke` и `RevokeAllForUser` устанавливают `revoked_at`.
|
||||
- `DeleteUnverifiedRegisteredBefore` удаляет одну пачку неподтвержденных аккаунтов, начиная со старых, и никогда не ждет блокировку. Он блокирует аккаунты-кандидаты, их токены, сессии, запросы писем, доставки писем и записи согласий через `FOR UPDATE SKIP LOCKED` и пропускает каждый аккаунт, у которого строка аккаунта или любая строка токена, сессии, запроса письма, доставки или согласия заблокирована другой транзакцией, например повторной регистрацией, повторной отправкой, подтверждением, обработчиком доставки или worker доставки; пропущенные аккаунты остаются до следующего запуска. Запросы писем, доставки и попытки удаляются вместе с аккаунтом каскадно; записи согласий, которые запрещают удаление аккаунта, удаляются явно в том же запросе.
|
||||
- `postgres.IdentityStore` выполняет те же репозитории вне транзакции. При вызове с контекстом из callback `Transactor` он возвращает `ErrNestedTransaction`, а не фиксирует изменения через отдельное соединение.
|
||||
- Нарушения уникальности и внешних ключей переводятся в `ErrEmailTaken`, `ErrTokenHashConflict` и `ErrUserNotFound` по SQLSTATE и имени ограничения, а не по тексту ошибки.
|
||||
@@ -674,14 +674,14 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Хеширование паролей
|
||||
|
||||
Реализовано и покрыто тестами: регистрация создает hasher из конфигурации и вызывает его; вход будет делать то же.
|
||||
Реализовано и покрыто тестами: регистрация и вход используют hasher из конфигурации.
|
||||
|
||||
- `domain.Password` хранит пароль, нормализованный в Unicode NFKC. `domain.NewPassword` применяет политику регистрации: от 15 до 128 кодовых точек после нормализации; `domain.ParseLoginPassword` принимает от 1 до 128. До нормализации оба отклоняют исходный ввод длиннее 512 байт (128 кодовых точек по 4 байта UTF-8 максимум, поэтому любое значение, принятое схемой контракта, помещается) и некорректный UTF-8. Эти проверки выполняются до любого хеширования и завершаются `domain.ErrInvalidPassword` с названием правила, но без значения. Blocklist распространенных и утекших паролей - отдельная запланированная проверка.
|
||||
- Порт `outbound.PasswordHasher` (`port/outbound/password.go`) содержит `Hash`, `Verify` и `VerifyDummy`; адаптер `adapter/secondary/argon2id` реализует его через `golang.org/x/crypto/argon2`. Новые хеши используют Argon2id v19 с m=65536 KiB, t=3, p=4 (второй рекомендованный вариант RFC 9106, выше базового уровня OWASP 19 MiB, t=2, p=1), соль 16 байт из crypto/rand и ключ 32 байта в формате `$argon2id$v=19$m=65536,t=3,p=4$<salt>$<key>` в base64 без дополнения - этот формат принимают `domain.NewPasswordHash` и CHECK `users_password_hash_format`. Один хеш занял примерно 26-33 ms на машине разработчика Apple M5 (`BenchmarkHashRecommendedParameters`, в том числе на одном CPU); это не измерение задержки в production.
|
||||
- Бюджет памяти: вычисления делят взвешенный семафор (`golang.org/x/sync/semaphore`) размером `PASSWORD_HASH_CONCURRENCY`, умноженное на 64 MiB, и каждое держит свой параметр памяти, пока выполняется. Настройка принимает от 1 до 4; если она не задана, берется меньшее из 2 и GOMAXPROCS, который Go выводит из лимита CPU контейнера. Compose передает `PASSWORD_HASH_CONCURRENCY=1` для backend-контейнера с 1 CPU, поэтому хеши вычисляются по одному и занимают 64 MiB живой памяти; максимум 4 требует 256 MiB. Память завершенного вычисления остается мусором до следующей сборки; `GOMEMLIMIT=600MiB` в Compose заставляет сборщик освободить ее раньше, чем куча дойдет примерно до 78% лимита контейнера 768 MiB, а остаток приходится на стеки и память вне кучи. Ожидающие вызовы стоят в очереди FIFO, ограниченной только контекстом запроса; ограничение частоты запросов появится вместе с HTTP-операциями.
|
||||
- `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`, а хеш со старыми параметрами стоит столько, сколько стоят его параметры, пока следующий успешный вход его не перехеширует.
|
||||
- Бюджет памяти: вычисления делят взвешенный семафор (`golang.org/x/sync/semaphore`) размером `PASSWORD_HASH_CONCURRENCY`, умноженное на 64 MiB, и каждое держит свой параметр памяти, пока выполняется. Настройка принимает от 1 до 4; если она не задана, берется меньшее из 2 и GOMAXPROCS, который Go выводит из лимита CPU контейнера. Compose передает `PASSWORD_HASH_CONCURRENCY=1` для backend-контейнера с 1 CPU, поэтому хеши вычисляются по одному и занимают 64 MiB живой памяти; максимум 4 требует 256 MiB. Память завершенного вычисления остается мусором до следующей сборки; `GOMEMLIMIT=600MiB` в Compose заставляет сборщик освободить ее раньше, чем куча дойдет примерно до 78% лимита контейнера 768 MiB, а остаток приходится на стеки и память вне кучи. Ожидающие вызовы стоят в очереди FIFO, ограниченной только контекстом запроса; HTTP-лимиты identity описаны в разделе серверных сессий.
|
||||
- `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 и некорректного сохраненного хеша, чтобы эти ветки также выполняли полноценную проверку Argon2id.
|
||||
- Вход отвечает `invalid_credentials` для неизвестного email, неверного пароля и некорректного сохраненного хеша (`errors.Is(err, domain.ErrInvalidPasswordHash)`, из репозитория или из `Verify`); для некорректного хеша он также пишет ошибку в лог и вызывает `VerifyDummy`. Подтвержденный email с верным паролем, но без успешной верификации, получает `email_not_verified` и не создает сессию. Время проверки не полностью одинаково: для неизвестного email и поврежденного хеша выполняется `VerifyDummy`, а сохраненные хеши с разными Argon2id-параметрами требуют разное время.
|
||||
- `identity.Credentials.HashNewPassword` проверяет новый пароль и только потом хеширует его; регистрация вызывает его во всех ветках до поиска email.
|
||||
- Ошибки и логи никогда не содержат пароль или хеш. `domain.Password`, `domain.PasswordHash`, `domain.SecretToken` и `domain.EmailAddress` скрывают значение в выводе `fmt`, `slog` и JSON и хранят его за указателем, поэтому при печати внешней структуры, даже через неэкспортируемое поле, виден только адрес.
|
||||
|
||||
@@ -734,21 +734,21 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
### Регистрация, подтверждение и повторная отправка
|
||||
|
||||
Реализовано: `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`.
|
||||
Реализовано: `RegisterAccount` и `ResendEmailVerification` обслуживает `backend/internal/usecase/identity/register.go` (`identity.Registration`) за обработчиком `backend/internal/adapter/primary/http/v1/auth.go`. Без `DATABASE_URL` обе операции по-прежнему отвечают 501. Роутер подключает `middleware.ClientIP` с `TRUSTED_PROXY_CIDRS`.
|
||||
|
||||
Одна транзакция. Новый адрес создает аккаунт (сценарий и первый `onboarding_step` сценария), запись C1 (`GrantAtRegistration`, текущая версия и хеш текста, источник `registration`), SHA-256 хеш одноразового токена, привязанного к версии регистрации, и доставку подтверждения (`ServiceMailer.EnqueueVerification`); отправляет ее позже воркер отправки через почтовый транспорт. C4 и любая другая цель никогда не записываются: тело принимает только C1. Повторная регистрация неподтвержденного адреса соблюдает порядок блокировок репозиториев identity (аннулировать токены, затем `AdvanceRegistration`, затем новая C1). Уже подтвержденный адрес ничего не меняет и ничего не получает: уведомление "у вас уже есть аккаунт" не реализовано, потому что любое письмо на подтвержденный адрес требует своего шаблона и своего лимита, а молчание не раскрывает аккаунт.
|
||||
|
||||
Отложенные учетные данные (защита от pre-hijack). Каждая регистрация, первая и каждая повторная, хранит хеш пароля, сценарий и первый шаг онбординга на своем токене подтверждения (столбцы `pending_*` таблицы `email_tokens`, миграция 00014). Повторная регистрация неподтвержденного адреса никогда не меняет учетные данные, сценарий и шаг онбординга строки `users`: `UserRepository.AdvanceRegistration` только увеличивает версию регистрации и время регистрации (и удаляет C1 прежней регистрации), а новый токен несет новые отложенные данные. Повторная отправка копирует отложенные данные новейшего токена регистрации. `password_hash`, `scenario` и `onboarding_step` строки неподтвержденного аккаунта не авторитетны, пока подтверждение не применит отложенные данные нажатого токена: в них значения первого регистранта лишь потому, что столбцы обязательны, и никакой код не вправе по ним аутентифицировать или им доверять (см. комментарий к `domain.User`). Аннулирование токена (`InvalidateActive`) очищает его столбцы `pending_*`, а CHECK не дает аннулированному токену хранить отложенный хеш. Повторная отправка, не нашедшая отложенных данных регистрации, ничего не выпускает.
|
||||
|
||||
Подтверждение почты (`ConfirmEmail`) реализовано. Оно требует пароль, сохраненный для регистрации этого токена, и проверяет его по отложенному хешу. В одной транзакции backend проверяет текущую версию регистрации и запись C1, погашает токен, подтверждает адрес, переносит с токена на аккаунт хеш пароля, сценарий и шаг онбординга, очищает `pending_*` и записывает ровно одно событие `identity.email_verified` без секретов. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный, устаревший токен, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`; истекший токен дает `verification_token_expired`. Origin должен точно совпадать с `APP_PUBLIC_URL`. Подтверждение не создает сессию. Экран подтверждения во frontend пока остается заглушкой; вход и восстановление сессии еще не реализованы.
|
||||
Подтверждение почты (`ConfirmEmail`) реализовано. Оно требует пароль, сохраненный для регистрации этого токена, и проверяет его по отложенному хешу. В одной транзакции backend проверяет текущую версию регистрации и запись C1, погашает токен, подтверждает адрес, переносит с токена на аккаунт хеш пароля, сценарий и шаг онбординга, очищает `pending_*` и записывает ровно одно событие `identity.email_verified` без секретов. При любом отказе состояние аккаунта и токена не меняется. Неизвестный, использованный, замененный, устаревший токен, неверный пароль и отсутствие отложенных данных дают `verification_token_invalid`; истекший токен дает `verification_token_expired`. Origin должен точно совпадать с `APP_PUBLIC_URL`. Подтверждение не создает сессию. Экран подтверждения во frontend пока остается заглушкой.
|
||||
|
||||
Планируемое поведение входа: неподтвержденный аккаунт не сможет войти. Вход будет отвечать как при неверном пароле (или `email_not_verified` только там, где это разрешает контракт) и не будет сравнивать пароль со строкой неподтвержденного аккаунта или с отложенными данными.
|
||||
Вход принимает только подтвержденный email и проверяет сохраненный пароль аккаунта, а не отложенные данные регистрации. Неизвестный адрес, неверный пароль и некорректный сохраненный хеш получают одинаковый `invalid_credentials`; неизвестный адрес и некорректный хеш дополнительно проходят `VerifyDummy`, а ошибка сохраненного хеша записывается в лог без email или хеша. Верный пароль для неподтвержденного аккаунта отвечает `email_not_verified` и не создает сессию. Успешный вход создает новую сессию; если запрос принес действующую cookie сессии, сервер отзывает ее и создает новую в одной транзакции. Неуспешный вход не отзывает старую сессию, а некорректная cookie не становится principal.
|
||||
|
||||
Порядок проверок регистрации: валидация всего тела и версии текста 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`, хешируется секретом и пропускается, когда адрес неизвестен (общий бакет позволил бы одному клиенту заблокировать всех). Отклоненный вызов `Take` не увеличивает свой счетчик; если предыдущая проверка лимита прошла, ее счетчик уже учел попытку, даже когда следующая проверка отказала. Отказ отвечает 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`, хешируется секретом и пропускается, когда адрес неизвестен (общий бакет позволил бы одному клиенту заблокировать всех). Вход также ограничен `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` (по умолчанию 10 в час) для нормализованного email, независимо от наличия аккаунта. Оба настраиваемых лимита принимают значения от 1 до 10000. Отклоненный вызов `Take` не увеличивает свой счетчик; если предыдущая проверка лимита прошла, ее счетчик уже учел попытку, даже когда следующая проверка отказала. Отказ отвечает 429 `rate_limited` с `Retry-After` в целых секундах с округлением вверх. Счетчики эфемерны: перезапуск Redis их сбрасывает, а квота почтового провайдера остается последней границей. Сбой Redis дает 500 и никогда не пропускает запрос. Ни адрес, ни токен не логируются.
|
||||
|
||||
Политика замены токена. Каждый выпуск токена подтверждения (регистрация, повторная регистрация, повторная отправка) сначала аннулирует все неиспользованные токены подтверждения аккаунта и затем сохраняет новый, поэтому одновременно работает не больше одной ссылки. Повторная отправка не меняет пароль, сценарий, запись согласия и версию регистрации, меняется только токен. Письмо аннулированного токена воркер отправки отменяет, поэтому доставляется только текущая ссылка. Срок жизни токена берется из продуктовой политики (`identity.verification_token_lifetime_hours`, 24 в демонстрационной версии), а не из конфигурации.
|
||||
|
||||
@@ -756,6 +756,14 @@ contact_grant относится к паре кандидат-компания
|
||||
|
||||
Без определенного адреса клиента (middleware `ClientIP` не выполнился) лимит клиента пропускается и действуют только лимиты адреса: общий бакет "unknown" позволил бы одному клиенту заблокировать всех, что хуже. `IDENTITY_KEY_SECRET` обязателен; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` позволяет стенду разработки взять случайный. Ключи лимитера содержат hash tag Redis (`{key}`), поэтому скрипт с несколькими ключами безопасен для кластера.
|
||||
|
||||
### Серверные сессии
|
||||
|
||||
Вход, чтение текущей сессии и выход реализованы на backend. Login требует единственный `Origin`, точно равный `APP_PUBLIC_URL`; logout проверяет тот же Origin и session-bound `X-CSRF-Token`. Проверка Origin выполняется на HTTP boundary и не доверяет `Host` или произвольным forwarded headers. Токен CSRF выводится через domain-separated HMAC-SHA-256 с ключом из `IDENTITY_KEY_SECRET`, связан с конкретным session token и сравнивается за постоянное время. `GetCurrentSession` возвращает CSRF-токен снова после перезагрузки страницы. GET `/api/v1/identity/sessions/current` возвращает сессию с аккаунтом, GET `/api/v1/identity/me` - текущий аккаунт, DELETE `/api/v1/identity/sessions/current` отзывает сессию. Это единственные OpenAPI operations, которым текущая HTTP security boundary разрешает session principal; остальные защищенные operations остаются закрытыми даже при валидной cookie.
|
||||
|
||||
Cookie называется `__Host-lincodex_session` и имеет `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict`, без `Domain`; `Expires` и `Max-Age` указывают на абсолютное завершение сессии. В PostgreSQL сохраняется только SHA-256 хеш случайного cookie token, а не его значение; IP и user agent не сохраняются. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h`, принимает от `1m` до `30d`; `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h`, принимает от `1m` до `365d`. Таймаут простоя не может превышать абсолютный срок; неверные значения останавливают запуск. Активный запрос продлевает срок простоя, но не абсолютный срок.
|
||||
|
||||
`IDENTITY_KEY_SECRET` должен иметь не менее 32 байт и оставаться одинаковым между перезапусками и экземплярами backend. Он также выводит ключ CSRF с разделением назначения `lincodex/identity/session-csrf/v1`; смена общего секрета делает прежние значения CSRF недействительными, но не отзывает сессии в PostgreSQL - клиент получает новый токен через GetCurrentSession. После успешной проверки пароля создание новой сессии и отзыв принесенной действующей сессии коммитятся одной транзакцией. Ошибка входа старую сессию не отзывает. Logout с просроченной или отозванной cookie очищает ее в браузере; ошибка Origin или CSRF не отзывает и не очищает действующую сессию.
|
||||
|
||||
Известные ограничения. Повторная отправка для неизвестного или подтвержденного адреса пропускает работу с токеном и письмом, поэтому ее время отличается от неподтвержденного аккаунта на несколько запросов к базе; регистрация скрывает разницу за хешем пароля. Blocklist паролей из контракта еще не реализован; действуют только правила длины `domain.NewPassword`.
|
||||
|
||||
### Организации и членства
|
||||
|
||||
+11
-11
@@ -72,9 +72,9 @@ Compose healthcheck запускает `kafka-broker-api-versions.sh` проти
|
||||
|
||||
Backend получает `KAFKA_BROKERS` - список адресов bootstrap в формате `host:port` через запятую. Compose задает `kafka:9092`; прямой запуск Go по умолчанию использует `localhost:9092`. Явно пустое значение, пустой элемент списка, отсутствующий или нулевой порт либо схема URL приводят к ошибке конфигурации. Relay outbox подключается к этим брокерам в фоне: backend не ждет Kafka при старте, а `/readyz` ее не проверяет. Объявленный адрес `kafka:9092` разрешается только внутри Compose сети, поэтому для прямого запуска нужен отдельно доступный брокер. Redis остается кешем и не используется как очередь.
|
||||
|
||||
`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#хеширование-паролей).
|
||||
`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`) ограничивают письма подтверждения на адрес и запросы на клиента; пустое значение означает значение по умолчанию. Подтверждение также ограничено 5 попытками на токен в час. Метрика `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` и храните неизменным между перезапусками и на всех экземплярах). Он ключует записи идемпотентности и лимиты, а также выводит ключ для session CSRF; Compose не стартует без него, а backend не стартует без него, если не задан `IDENTITY_ALLOW_EPHEMERAL_KEY=true`, который нужен только стендам разработки. Смена секрета меняет ключи счетчиков и поиска записей идемпотентности за последние 24 часа и делает прежние CSRF-токены недействительными, но не отзывает сессии, сохраненные в PostgreSQL. `VERIFICATION_MAIL_MIN_INTERVAL` (по умолчанию `1m`) и `VERIFICATION_MAIL_DAILY_LIMIT` (по умолчанию `5`) ограничивают письма подтверждения на адрес; пустое значение означает значение по умолчанию. `IDENTITY_CLIENT_HOURLY_LIMIT` по умолчанию `30` и принимает значения от `1` до `10000`; он ограничивает регистрацию, подтверждение, повторную отправку и вход по адресу клиента, если тот разрешен доверенной цепочкой. `IDENTITY_LOGIN_EMAIL_HOURLY_LIMIT` по умолчанию `10` и принимает значения от `1` до `10000`; он ограничивает вход по нормализованному email независимо от наличия аккаунта. Подтверждение также ограничено 5 попытками на токен в час. `IDENTITY_SESSION_IDLE_TIMEOUT` по умолчанию `24h` (от `1m` до `30d`), `IDENTITY_SESSION_ABSOLUTE_LIFETIME` по умолчанию `168h` (от `1m` до `365d`); idle timeout не может превышать absolute lifetime, а некорректная конфигурация останавливает backend при запуске. Метрика `lincodex_identity_rate_limit_refusals_total{scope}` считает отказы; большая доля `scope="client"` намекает на сломанную цепочку прокси (см. `TRUSTED_PROXY_CIDRS`). См. [ARCHITECTURE.md](ARCHITECTURE.md#регистрация-подтверждение-и-повторная-отправка) и раздел о серверных сессиях в [ARCHITECTURE.md](ARCHITECTURE.md#серверные-сессии).
|
||||
|
||||
down останавливает контейнеры, сохраняя именованные volumes. Не удаляйте volume с базой или файлами в рамках обычного останова.
|
||||
|
||||
@@ -239,7 +239,7 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
|
||||
|
||||
Совместимость выпуска: `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#почтовый-транспорт).
|
||||
`resend` отправляет каждое письмо одним запросом к `https://api.resend.com/emails`. Создание транспорта не обращается к сети, поэтому при запуске не проверяются ни ключ, ни домен отправителя; неверный ключ или неподтвержденный домен в `EMAIL_FROM` проявятся как отказ при отправке. Одну попытку ограничивает `EMAIL_TIMEOUT`. Транспорт не следует редиректам, никогда не повторяет запрос и ничего не логирует; повторы, backoff, темп при rate limit и учет результатов выполняет worker отправки, а ожидание известного сброса дневной или месячной квоты решает шлюз квот (см. [Квоты почты](#квоты-почты)). Каждый запрос несет ключ идемпотентности письма, и Resend 24 часа не отправляет повторно письмо с тем же ключом и телом; после этого окна повтор может отправить письмо дважды. Успех значит, что Resend принял запрос и вернул идентификатор письма, а не что письмо доставлено или прочитано. Таймаут, потерянный ответ после отправки запроса или ошибка 500 от Resend дают `unknown` (`delivery_uncertain`), а не ошибку. Процесс backend учитывает стандартные переменные `HTTPS_PROXY` и `NO_PROXY`, но сервис backend в Compose их не передает, поэтому под Compose запрос идет в Resend напрямую; если стенду нужен прокси для исходящего трафика, добавьте эти переменные в `environment` сервиса backend. Полное соответствие ответов описано в [ARCHITECTURE.md](ARCHITECTURE.md#почтовый-транспорт).
|
||||
|
||||
`disabled` ничего не отправляет. Каждая отправка возвращает `ErrMailChannelUnavailable` без идентификатора сообщения провайдера и никогда не считается принятой или доставленной. Этот режим не подтверждает email, не отмечает аккаунт подтвержденным и не пропускает проверки аккаунта. В логе запуска есть `mail transport selected` с полем `email_provider`, а для `disabled` еще и предупреждение `mail delivery is disabled`.
|
||||
|
||||
@@ -282,21 +282,21 @@ Compose передает эти переменные из корневого `.e
|
||||
- Внутренний endpoint /metrics показывает текущие окна настроенного аккаунта, которые читаются каждые 30 секунд: `lincodex_mail_quota_used_recipients`, `lincodex_mail_quota_limit_recipients` и `lincodex_mail_quota_provider_exhausted` (1 после отказа провайдера по квоте), каждая с labels `provider` и `window` (`day` или `month`). `EMAIL_ACCOUNT` не становится label, потому что его текст выбирает оператор; при `EMAIL_PROVIDER=disabled` серий квот нет. Alert `LincodexMailQuotaUsedUp` (severity info) срабатывает, пока окно исчерпано.
|
||||
- Варианты, пока письма ждут: дождаться сброса, для этого ничего делать не нужно; или после осознанной смены тарифа у провайдера поднять лимиты и перезапустить backend, тогда новые отправки снова допускаются, а отложенные доставки сохраняют свой `next_attempt_at`; или осознанно сменить транспорт или аккаунт (что остается закрепленным, описано в [Доставки писем](#доставки-писем)). Не уменьшайте `used_recipients` и не правьте журнал вручную, чтобы освободить отправки: у провайдера свой счет, и такие отправки он только отклонит.
|
||||
- `provider_exhausted_at` в строке значит, что провайдер ответил отказом по квоте, хотя по локальному счету место было. Возможные причины: аккаунт отправляет письма еще откуда-то; Resend учитывает в той же квоте полученные (входящие) письма; или настроенный лимит выше тарифа. Приведите лимиты в соответствие с тарифом.
|
||||
- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Ручной повтор с записью в аудит запланирован вместе с политикой повторов.
|
||||
- Месячная квота Resend следует платежному циклу аккаунта, а месяц шлюза - календарный месяц UTC. После месячного отказа доставка повторяется в начале следующего месяца UTC; если платежный цикл сбрасывается позже, этот повтор снова получит отказ и будет ждать еще месяц. Локальная команда оператора предназначена для терминального `unknown`, а не для доставок, ожидающих сброса квоты.
|
||||
- Сниженный лимит действует со следующего резервирования. Во время поэтапного обновления экземпляры со старым и новым лимитом работают одновременно, и каждый проверяет лимит, с которым запущен, поэтому сниженный лимит соблюдается только после того, как все экземпляры работают с новой конфигурацией. Переключение `EMAIL_PROVIDER` на `smtp` начинает для relay отдельные счетчики с его явно заданными лимитами; доставки, закрепленные за прежним аккаунтом, шлюз отклоняет, а не отправляет без лимита.
|
||||
|
||||
### Отправка служебной почты
|
||||
|
||||
Процесс backend запускает один цикл отправки служебной почты identity (подтверждение почты и сброс пароля). Он стартует вместе с backend, когда `EMAIL_PROVIDER` равен `resend` и задан `DATABASE_URL`, использует ту же базу, что и другие worker, через pool из двух соединений и не требует собственных настроек: интервал опроса (5 секунд), lease на захваченную доставку (`EMAIL_TIMEOUT` плюс одна минута), льготный период остановки (5 секунд), расписание повторов (1 минута с удвоением до 30 минут) и пауза после сбоя (5 секунд с удвоением до 2 минут) - константы в `backend/internal/bootstrap/mail_sender.go`. Миграция 00012 добавляет его столбцы; модель, проверки и исходы описаны в [ARCHITECTURE.md](ARCHITECTURE.md#отправка-служебной-почты).
|
||||
Процесс backend запускает один цикл отправки служебной почты identity (подтверждение почты и сброс пароля). Он стартует вместе с backend, когда `EMAIL_PROVIDER` равен `resend` и задан `DATABASE_URL`, использует ту же базу, что и другие worker, через pool из двух соединений и не требует собственных настроек: интервал опроса (5 секунд), lease на захваченную доставку (`EMAIL_TIMEOUT` плюс одна минута), льготный период остановки (5 секунд), расписание повторов (1 минута с удвоением до 30 минут) и пауза после сбоя (5 секунд с удвоением до 2 минут) - константы в `backend/internal/bootstrap/mail_sender.go`. Миграция 00012 добавляет его столбцы, а 00017 - журнал решений для неопределенного исхода и пересоздает частичный индекс доставок под блокировкой таблицы. Откат 00017 удаляет журнал и всю историю аудита, поэтому перед ним экспортируйте решения. Модель, проверки и исходы описаны в [ARCHITECTURE.md](ARCHITECTURE.md#отправка-служебной-почты).
|
||||
|
||||
- Одновременно может работать несколько экземпляров backend. Каждый захватывает доставку через `FOR UPDATE SKIP LOCKED` и lease, поэтому одну доставку отправляет один экземпляр, а вызов провайдера несет стабильный ключ идемпотентности `delivery/<id>`. При поэтапном обновлении останавливающийся экземпляр завершает отправку в течение 5 секунд, сохраняет результат и выходит.
|
||||
- При `EMAIL_PROVIDER=disabled` цикл не запускается, а в журнале пишется `mail sender worker is not started because EMAIL_PROVIDER is disabled; stored deliveries wait`; `lincodex_mail_sender_running` равен 0, ничего не отправляется, а сохраненная служебная почта ждет следующего запуска с транспортом. Worker никогда не крутится вхолостую: после прохода, который ничего не смог отправить, он делает паузу.
|
||||
- Перед отправкой worker проверяет токен и аккаунт. Доставка, которую нельзя отправлять, завершается как `cancelled` с `cancel_reason`, без попытки и без расхода квоты: `token_missing`, `token_purpose_mismatch`, `token_owner_mismatch`, `token_consumed`, `token_revoked`, `token_expired`, `account_not_current`, `recipient_mismatch`, `content_invalid` или `processing_failed`. Причины, вызванные пользователем, нормальны: пользователь запросил новую ссылку, подтвердил адрес, зарегистрировался заново или слишком долго ждал. Причины можно посмотреть так: `SELECT cancel_reason, count(*) FROM deliveries WHERE status = 'cancelled' GROUP BY cancel_reason`. Пользователь видит отмененное письмо как "не отправлено, запросите новое".
|
||||
- Ответы провайдера: `accepted` означает принято провайдером, а не доставлено человеку; подтверждения доставки у backend нет. Отказ "пока" (`temporary`, `rate_limited`) оставляет доставку в `pending` с более поздним `next_attempt_at`, а повтор использует тот же ключ и тело; он повторяется, пока не удастся, пока не будет отказа навсегда или пока токен не истечет и доставка не будет отменена. Постоянный отказ или отказ из-за запроса завершает ее как `rejected`: прочитайте код провайдера в `delivery_attempts.provider_code` (например `validation_error` для неподтвержденного домена отправителя или `invalid_api_key`) и устраните причину. Ответ о квоте переводит ее в `waiting_quota`; см. [Квоты почты](#квоты-почты).
|
||||
- `unknown` worker никогда не повторяет. Это значит, что провайдер мог принять письмо (потерянный ответ, ответ 5xx) или что worker, отправивший его, был потерян дольше 24-часового окна идемпотентности провайдера. Найдите сообщение в журнале самого провайдера; пока срабатывает alert `LincodexMailDeliveryUnknownOutcome`. Ручной повтор с записью аудита запланирован вместе с политикой повторов.
|
||||
- Ответы провайдера: `accepted` означает принято провайдером, а не доставлено человеку; подтверждения доставки у backend нет. Подтвержденный временный отказ или 429 означает, что провайдер не принял письмо: доставка остается в `pending` с более поздним `next_attempt_at`, повтор использует закрепленные аккаунт, ключ и тело. `Retry-After` от Resend - нижняя граница ожидания. Такой отказ не снимает неопределенность от более ранней попытки `unknown`. После cutoff продолжать повторы подтвержденных отказов можно только в рамках ожидающего ручного решения; без него worker остановится и оставит более ранний `unknown` на проверку оператора. Постоянный отказ или отказ из-за запроса завершает ее как `rejected`: прочитайте код провайдера в `delivery_attempts.provider_code` (например `validation_error` для неподтвержденного домена отправителя или `invalid_api_key`) и устраните причину. Ответ о квоте переводит ее в `waiting_quota`; см. [Квоты почты](#квоты-почты).
|
||||
- Неопределенный исход Resend автоматически повторяется с теми же закрепленными аккаунтом, ключом и сохраненным телом только до 23 часов после первого начала отправки, записанного часами базы. Это на час раньше документированного 24-часового срока хранения ключа. Worker повторяет проверку cutoff прямо перед сетевым вызовом. После cutoff или после ручного send-start с потерянным результатом автоматические повторы останавливаются, а alert `LincodexMailDeliveryUnknownOutcome` требует проверки. Сначала проверьте журнал провайдера. Для терминальной строки `unknown` выполните `make -C backend mail-retry ARGS='inspect --delivery <uuid>'`, чтобы увидеть метаданные и предупреждение о возможном дубле, затем `make -C backend mail-retry ARGS='retry --delivery <uuid> --actor operator:<handle> --acknowledge-duplicate-risk'`, чтобы запланировать одно аудируемое решение. Команда требует локальный доступ к базе, доступна только при `EMAIL_PROVIDER=resend`, показывает предупреждение до изменения состояния и сама письмо не отправляет. Actor является меткой для аудита, а не аутентификацией; HTTP endpoint оператора нет. Ручное решение не запускает заново срок ключа провайдера: после нового `unknown` или потери результата ручной отправки worker остановится и потребует еще одно решение. Истекший ключ идемпотентности может привести к дублю и после подтверждения риска.
|
||||
- Захваченная доставка держит lease: `SELECT id, kind, claimed_until FROM deliveries WHERE claim_owner IS NOT NULL`. Строка с давно прошедшим `claimed_until` значит, что ее worker умер; другой экземпляр подхватит ее сам. Не сбрасывайте lease вручную.
|
||||
- `content_invalid` и `processing_failed` - не действия пользователя: первое значит, что сохраненная строка не совпадает со своим хешем содержимого (ручная правка) или содержит сообщение, которое не принимает ни один транспорт, второе - что worker трижды подряд потерпел сбой на строке (повторы разнесены расписанием). Alert `LincodexMailCancelledBroken` срабатывает при росте; прочитайте журнал worker по `delivery_id` и осмотрите метаданные строки. Строка, которая сбоит постоянно, не блокирует остальные: она повторяется позже (`failure_count`, `next_attempt_at`), а затем отменяется.
|
||||
- Тела письма с токеном очищаются, когда оно принято, отклонено или отменено (ставится `body_redacted_at`), поэтому дампы и резервные копии завершенной почты с токеном токенов не содержат. Письмо в `unknown` сохраняет тело, пока оператор его не разрешит. Не копируйте тела ожидающих писем никуда.
|
||||
- Тела письма с токеном очищаются, когда оно принято, отклонено или отменено (ставится `body_redacted_at`), поэтому дампы и резервные копии завершенной почты с токеном токенов не содержат. Письмо в `unknown` сохраняет тело, пока оператор его не разрешит. Команда повтора не показывает адрес, тело, ключ или токен. Не копируйте тела ожидающих писем никуда.
|
||||
- Lease измеряется часами базы, поэтому различие часов экземпляров не важно, важны только часы базы. Вызов провайдера ограничен остатком lease; при `SHUTDOWN_TIMEOUT` по умолчанию 10 секунд останавливающийся экземпляр укладывается в 3 секунды льготного периода плюс 5 секунд на сохранение ответа. Снижение `SHUTDOWN_TIMEOUT` укорачивает вторую часть (не меньше 1 секунды); результат, не сохраненный вовремя, покрывает перехват.
|
||||
- Журнал называет доставку только по `delivery_id`, ее виду и исходу или причине отмены, например `service mail was not sent because it is no longer valid`; никогда не по адресу, токену, ссылке или телу. Если токен или ссылка появились в журнале, считайте это дефектом.
|
||||
- Внутренний endpoint /metrics показывает `lincodex_mail_sender_running` (1, пока цикл этого экземпляра работает, иначе 0; без labels) и `lincodex_mail_sender_cancelled_total{reason}` (счетчик по причине отмены, включая нулевые) рядом с gauges доставок, у которых теперь есть и статус `cancelled`.
|
||||
@@ -380,9 +380,9 @@ Edge-хост общий с другими сервисами. Здесь все
|
||||
|
||||
### Один origin и Secure cookie
|
||||
|
||||
Браузер видит только `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.
|
||||
Браузер видит только `https://<EDGE_DOMAIN>`. SPA и `/api` приходят с одного origin: edge пересылает каждый путь без изменений, а frontend контейнер отдает SPA с запасным вариантом `try_files ... /index.html`, поэтому глубокая ссылка вроде `/some/deep/link` возвращает SPA, и проксирует `/api/` в Go. Backend выдает cookie `__Host-lincodex_session` с `Path=/`, `Secure`, `HttpOnly`, `SameSite=Strict` и без `Domain`; `Expires` и `Max-Age` равны абсолютному сроку сессии. 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`, точно равный `APP_PUBLIC_URL`; backend не выводит разрешенный origin из `Host` и не доверяет forwarded headers для этой проверки.
|
||||
|
||||
Регистрация, повторная отправка подтверждения и подтверждение email доступны через API, но вход не реализован. Экраны регистрации и подтверждения во frontend остаются заглушками, а backend не читает `X-Forwarded-Proto`. Поэтому браузерный путь подтверждения и вход через edge не проверены end to end; проверен транспорт cookie (HTTPS, один origin, переданные исходные хост и схема).
|
||||
Регистрация, повторная отправка подтверждения, подтверждение email, вход, чтение текущей сессии и выход доступны через backend API. Экраны регистрации и подтверждения во frontend остаются заглушками, а backend не читает `X-Forwarded-Proto` для проверки origin. Браузерный путь входа через edge не проверен end to end.
|
||||
|
||||
### Обработка запросов на edge
|
||||
|
||||
@@ -490,7 +490,7 @@ Docker обходит ufw для опубликованных портов: он
|
||||
systemctl list-timers certbot.timer
|
||||
sudo certbot certificates
|
||||
|
||||
Reload запускает новые workers с новым сертификатом и конфигурацией и дает старым workers дойти до конца открытых соединений, поэтому запросы в полете и keep-alive соединения не обрываются. Сессии nginx вообще не хранит: планируемая схема держит их в PostgreSQL за непрозрачной cookie, поэтому reload или перезапуск nginx или туннеля никого не разлогинивает. Пока вход не реализован, доступное доказательство - запрос в полете и удерживаемое соединение через `systemctl reload nginx`: оба завершаются без 5xx, а следующий запрос по тому же соединению проходит.
|
||||
Reload запускает новые workers с новым сертификатом и конфигурацией и дает старым workers дойти до конца открытых соединений, поэтому запросы в полете и keep-alive соединения не обрываются. Состояние сессии хранит backend в PostgreSQL, а не nginx: reload или перезапуск nginx либо туннеля не отзывает сессию, пока работают backend и база. Проверка ниже подтверждает только завершение запроса в полете и работу keep-alive через `systemctl reload nginx`; сохранение входа через браузер после reload не проверено end to end.
|
||||
|
||||
### Проверка
|
||||
|
||||
|
||||
Reference in new issue
Block a user