feat(identity): confirm registration email atomically

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

No files matched your search

+8 -7
View File
@@ -102,7 +102,7 @@ The ML service answers its errors with the same `Problem` schema. Its `ProblemCo
### Identity: sessions, cookie, and CSRF
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount` and `ResendEmailVerification` are implemented; the other public operations still answer 501 `not_implemented` after request validation, and the backend's `v1.DenyAllSecurity` rejects every session, so operations that require one answer 401 `unauthenticated`. Values marked as planned come from the planned email confirmation, login, and session configuration.
The `identity` tag covers registration, email verification, login, logout, and the current account. All operations are in the contract. `RegisterAccount`, `ResendEmailVerification`, and `ConfirmEmail` are implemented. Login still answers 501 `not_implemented`, and `v1.DenyAllSecurity` rejects every request to a protected operation with 401 `unauthenticated`. Frontend registration and confirmation screens remain placeholders, and login is not implemented.
| Method and path | operationId | Security | Success | Specific errors |
| --- | --- | --- | --- | --- |
@@ -119,14 +119,15 @@ Every operation also declares the `default` problem response.
Registration and verification:
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email, and login answers 401 `invalid_credentials` for both an unknown email and a wrong password.
- Accounts are not enumerated. Registration and resend answer the same neutral 202 for a new, unverified, verified, or unknown email. Login is not implemented yet, so its contract behavior of answering 401 `invalid_credentials` for both an unknown email and a wrong password is not available.
- Before the server looks up the email, it validates the whole registration body (password bounds after NFKC normalization, the password blocklist, the C1 version) and computes the Argon2id hash on every branch, so neither a 400 nor the response time depends on whether the account exists.
- Registering an unverified email again never changes the password hash, the scenario, or the onboarding step of the account row. Every registration, the first and each repeat, stores its own pending credentials (password hash and scenario) on its own verification token, replaces the C1 record, advances the registration version, and invalidates every earlier verification token. Confirming a token (`ConfirmEmail`) must apply the pending credentials of that token only, and must require the password of that registration to confirm a token that carries pending credentials; the current `EmailVerificationRequest` has no password field, so email confirmation requires a contract change. This stops a pre-registration with someone else's password from being adopted by the address owner who clicks the attacker's link, and the reverse. The account row of an unverified account cannot be used to sign in: login refuses every unverified account and never compares a password with the row or the pending credentials of an unverified account. For a verified email nothing changes; the server sends nothing.
- Implementation of registration and resend. Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). Limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, and the limiter keys. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-and-verification-resend).
- Registering an unverified email again never changes the password hash, scenario, or onboarding step of the account row. Every registration, the first and each repeat, stores its pending credentials (password hash, scenario, and first onboarding step) on its own verification token, replaces the C1 record, advances the registration version, and invalidates earlier verification tokens. `ConfirmEmail` requires the password chosen for that registration and checks it against the pending hash on the clicked token. In one transaction the server checks the current registration version and its C1 record, consumes the token, verifies the email, applies that token's pending credentials to the account, clears its `pending_*` fields, and records exactly one `identity.email_verified` event. Any refusal leaves the account and token unchanged. An unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers 400 `verification_token_invalid`; an expired token answers 400 `verification_token_expired`. This prevents an address owner who clicks someone else's link from accepting that registrant's password, and vice versa. Confirmation does not create a session or cookie. Login is not implemented. The planned login rule is that an unverified account cannot sign in.
- Implementation of registration and resend. Verified address: nothing changes and nothing is sent (the "you already have an account" notice is not implemented). Limits per address (shared by registration and resend, keyed by an HMAC of the normalized address, counted whether or not an account exists): at least `VERIFICATION_MAIL_MIN_INTERVAL` (default 60 s) between messages and at most `VERIFICATION_MAIL_DAILY_LIMIT` (default 5) per 24 hours; per client: `IDENTITY_CLIENT_HOURLY_LIMIT` (default 30 per hour). `ConfirmEmail` also limits each token to 5 attempts per hour and uses the same client limit. A refused request answers 429 `rate_limited` with `Retry-After` in whole seconds and issues no token. Token replacement policy: every issue first invalidates all unused verification tokens of the account, so one link works at a time; resend changes only the token. `IDENTITY_KEY_SECRET` (at least 32 bytes, required; `IDENTITY_ALLOW_EPHEMERAL_KEY=true` allows a random one on a development stand) keys the idempotency scope, the fingerprint, and the limiter keys. A concurrent request with the same key waits for the first and is replayed, so `idempotency_in_progress` is not produced. Details: [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#registration-email-verification-and-resend).
- Every verification token is bound to the registration version it was issued for, so a token issued before a re-registration never confirms the newer credentials. Resend issues a token for the current version with the pending credentials of that registration, invalidates the earlier ones, and changes nothing else. Planned values: tokens live 24 hours; an account that stays unverified is deleted with its consent record and tokens 7 days after its last registration. These lifetimes come from the versioned product policy (demo version 1 of the `product` family), not from configuration; see [ARCHITECTURE.md](../docs/en/ARCHITECTURE.md#product-policy-versions).
- Registration requires Idempotency-Key. For this anonymous operation the key is scoped by the operation, the key, and an HMAC of the normalized email; the fingerprint is an HMAC-SHA-256 with a server secret over the canonical JSON body. The body, the password, and plain hashes of either are never stored, and the secret keeps the fingerprint from serving as an offline password check.
- The verification link is `<frontend origin>/verify-email#token=<token>`. The page removes the fragment with `history.replaceState` and posts the token only after an explicit user action, so the token stays out of server logs and Referer headers and a link scanner does not consume it. Verification does not start a session.
- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token answers `verification_token_invalid`. The client offers a new link and sign-in for both. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
- `ConfirmEmail` takes both `token` and the `password` selected for that registration; clients that sent only a token must be updated. The password follows `LoginPassword`: NFKC normalization and 1 to 128 code points; the registration blocklist is not applied again. `Origin` must match `APP_PUBLIC_URL`; a missing Origin, the literal value null, or a foreign Origin answers 403 `csrf_check_failed`. Confirmation attempts are limited to 5 per token per hour and also use the shared `IDENTITY_CLIENT_HOURLY_LIMIT`; a refused attempt answers 429 `rate_limited` with `Retry-After`.
- The verification link is `<frontend origin>/verify-email#token=<token>`. The frontend confirmation screen is still a placeholder. A client page must remove the fragment with `history.replaceState`, wait for an explicit user action, and post both token and registration password; a link scanner that only opens the page does not consume the token.
- An expired token answers `verification_token_expired`; an unknown, used, replaced, or superseded token, a wrong password, or missing pending credentials answers `verification_token_invalid`. The client offers a new link for either error, and can offer sign-in after login is implemented. A repeated confirmation with a used token is deliberately not an idempotent 200: exactly one request succeeds per token.
Consent C1 and the account:
@@ -137,7 +138,7 @@ Consent C1 and the account:
Sessions and CSRF:
- The `sessionCookie` scheme is the cookie `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain. The server keeps sessions in PostgreSQL and takes the caller only from the session. Only a verified account gets a session. Login revokes the session the request carried and issues a new identifier and CSRF token; logout revokes the session server-side. Planned timeouts: 24 hours idle and 7 days absolute; activity extends only the idle deadline. Both come from the versioned product policy, not from configuration.
- Planned session behavior: the `sessionCookie` scheme uses `__Host-lincodex_session` with `Path=/; Secure; HttpOnly; SameSite=Strict` and no Domain; the server will keep sessions in PostgreSQL and identify the caller from the session. Once login is implemented, only a verified account will receive a session, and login will revoke the session from the request and issue a new identifier and CSRF token. Logout will revoke the session server-side. Policy timeouts are 24 hours idle and 7 days absolute; activity extends only the idle deadline. Configuration does not override these values.
- The `sessionCsrf` scheme is the `X-CSRF-Token` header with the session-bound token from `Session.csrf_token`. Every unsafe operation that requires `sessionCookie` must also require `sessionCsrf`; `TestUnsafeSessionOperationsRequireCSRFToken` in the backend enforces it on the bundle. The client keeps the token in memory and restores it with `GetCurrentSession` after a reload or after 403 `csrf_check_failed`.
- Every unsafe request, including the public ones, must carry an `Origin` from the configured allowlist, otherwise 403 `csrf_check_failed` (planned; see the [development guide](../docs/en/DEVELOPMENT.md#sessions-on-local-http)). Public identity operations are rate-limited (429 with `Retry-After`).
- Responses with a session or account carry `Cache-Control: no-store`.