feat(identity): register accounts and resend verification mail

This commit is contained in:
shira committed 2026-10-06 23:59:51 +03:00
1 parent 5e202ac972
commit 4436f626a3
55 files changed
+3227 -88

No files matched your search

+23 -2
View File
@@ -120,6 +120,23 @@ type Config struct {
// that may run at once; further logins and registrations wait.
PasswordHashConcurrency int
// IdentityKeySecret keys the HMACs that scope idempotency records and
// rate limit counters by email address, so neither holds a plain hash of
// an address or a password. Empty means a random secret for the life of
// the process.
IdentityKeySecret string
// IdentityAllowEphemeralKey lets a development stand run without
// IDENTITY_KEY_SECRET, with a random secret per process.
IdentityAllowEphemeralKey bool
// VerificationMailMinInterval and VerificationMailDailyLimit bound the
// verification messages to one address: the registration and every
// resend count against both.
VerificationMailMinInterval time.Duration
VerificationMailDailyLimit int
// IdentityClientHourlyLimit bounds the registrations and resends of one
// client network address per hour.
IdentityClientHourlyLimit int
// TrustedProxyCIDRs are the reverse proxies in front of the API. The
// client address is taken from X-Forwarded-For only through them (see
// middleware.ClientIP). Empty trusts no proxy.
@@ -173,6 +190,9 @@ func LoadFromEnv(lookup LookupEnv) (Config, error) {
if err := config.loadPasswordHash(lookup); err != nil {
return Config{}, err
}
if err := config.loadIdentity(lookup); err != nil {
return Config{}, err
}
if err := config.loadTrustedProxies(lookup); err != nil {
return Config{}, err
}
@@ -223,6 +243,9 @@ func (config Config) Validate() error {
if err := config.ValidatePasswordHash(); err != nil {
return err
}
if err := config.ValidateIdentity(); err != nil {
return err
}
if err := validateAddress("HTTP_ADDR", config.HTTPAddr); err != nil {
return err
}
@@ -267,8 +290,6 @@ func DatabaseURLFromEnv(lookup LookupEnv) string {
// boolOrDefault accepts only "true" or "false", ignoring case and surrounding
// spaces. strconv.ParseBool would also accept 1, t, and similar shorthands,
// which are easy to mistype in deployment files.
//
//nolint:unparam // Every setting names its own default; that all current defaults are true is a coincidence.
func boolOrDefault(lookup LookupEnv, key string, fallback bool) (bool, error) {
value, ok := lookup(key)
if !ok {
+3
View File
@@ -112,6 +112,9 @@ func testEnvironment(values map[string]string) LookupEnv {
if value, ok := values[key]; ok {
return value, true
}
if key == "IDENTITY_KEY_SECRET" {
return "config-test-identity-key-secret-0123456789", true
}
if key == "SEAWEEDFS_ACCESS_KEY" {
return "test-access", true
}
+98
View File
@@ -0,0 +1,98 @@
package config
import (
"errors"
"fmt"
"strings"
"time"
)
const (
// defaultVerificationMailMinInterval is the shortest time between two
// verification messages to one address, counting the registration and
// every resend.
defaultVerificationMailMinInterval = time.Minute
// minVerificationMailMinInterval and maxVerificationMailMinInterval bound
// the setting: a shorter interval is no brake, a longer one is a
// lock-out that a person who mistyped cannot wait out.
minVerificationMailMinInterval = time.Second
maxVerificationMailMinInterval = time.Hour
// defaultVerificationMailDailyLimit is the number of verification
// messages to one address per 24 hours.
defaultVerificationMailDailyLimit = 5
maxVerificationMailDailyLimit = 50
// defaultIdentityClientHourlyLimit is the number of registrations and
// resends per client network address per hour. It is a brake on one
// source reaching many addresses; the per-address limits above protect
// one address from many sources.
defaultIdentityClientHourlyLimit = 30
maxIdentityClientHourlyLimit = 10000
// MinIdentityKeySecretBytes is the shortest accepted IDENTITY_KEY_SECRET.
MinIdentityKeySecretBytes = 32
// examplePlaceholderPrefix starts the placeholder values of the example
// environment file; a secret that keeps it is public.
examplePlaceholderPrefix = "replace-this"
)
// loadIdentity reads the registration settings. IDENTITY_KEY_SECRET is
// required: without it ValidateIdentity refuses the configuration, unless
// IDENTITY_ALLOW_EPHEMERAL_KEY is true, which lets a development stand draw a
// random secret for the life of the process and so forget idempotency records
// and rate limit counters on every restart.
//
// The three limits treat an empty value as unset, as the mail quota does:
// Compose passes an unset variable as an empty string.
func (config *Config) loadIdentity(lookup LookupEnv) error {
config.IdentityKeySecret = strings.TrimSpace(valueOrDefault(lookup, "IDENTITY_KEY_SECRET", ""))
var err error
config.IdentityAllowEphemeralKey, err = boolOrDefault(lookup, "IDENTITY_ALLOW_EPHEMERAL_KEY", false)
if err != nil {
return err
}
setOnly := func(key string) (string, bool) {
value, ok := lookup(key)
if strings.TrimSpace(value) == "" {
return "", false
}
return value, ok
}
config.VerificationMailMinInterval, err = durationOrDefault(setOnly, "VERIFICATION_MAIL_MIN_INTERVAL", defaultVerificationMailMinInterval)
if err != nil {
return err
}
config.VerificationMailDailyLimit, err = intOrDefault(setOnly, "VERIFICATION_MAIL_DAILY_LIMIT", defaultVerificationMailDailyLimit)
if err != nil {
return err
}
config.IdentityClientHourlyLimit, err = intOrDefault(setOnly, "IDENTITY_CLIENT_HOURLY_LIMIT", defaultIdentityClientHourlyLimit)
return err
}
// ValidateIdentity checks the registration settings. Errors never include
// the secret.
func (config Config) ValidateIdentity() error {
if config.IdentityKeySecret == "" && !config.IdentityAllowEphemeralKey {
return errors.New("Config.ValidateIdentity - IDENTITY_KEY_SECRET is required (generate one with: openssl rand -base64 48); " +
"set IDENTITY_ALLOW_EPHEMERAL_KEY=true only on a development stand")
}
if strings.HasPrefix(config.IdentityKeySecret, examplePlaceholderPrefix) {
return errors.New("Config.ValidateIdentity - IDENTITY_KEY_SECRET is an example placeholder; generate a real one with: openssl rand -base64 48")
}
if config.IdentityKeySecret != "" && len(config.IdentityKeySecret) < MinIdentityKeySecretBytes {
return fmt.Errorf("Config.ValidateIdentity - IDENTITY_KEY_SECRET must have at least %d bytes", MinIdentityKeySecretBytes)
}
if config.VerificationMailMinInterval < minVerificationMailMinInterval || config.VerificationMailMinInterval > maxVerificationMailMinInterval {
return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be between %s and %s",
minVerificationMailMinInterval, maxVerificationMailMinInterval)
}
if config.VerificationMailDailyLimit < 1 || config.VerificationMailDailyLimit > maxVerificationMailDailyLimit {
return fmt.Errorf("Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT must be between 1 and %d", maxVerificationMailDailyLimit)
}
if config.IdentityClientHourlyLimit < 1 || config.IdentityClientHourlyLimit > maxIdentityClientHourlyLimit {
return fmt.Errorf("Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT must be between 1 and %d", maxIdentityClientHourlyLimit)
}
if config.VerificationMailMinInterval >= 24*time.Hour {
return errors.New("Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL must be shorter than the daily window")
}
return nil
}
+113
View File
@@ -0,0 +1,113 @@
package config
import (
"strings"
"testing"
"time"
)
func TestLoadFromEnvIdentityDefaults(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_ALLOW_EPHEMERAL_KEY": "true", "IDENTITY_KEY_SECRET": ""}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.IdentityKeySecret != "" ||
settings.VerificationMailMinInterval != time.Minute ||
settings.VerificationMailDailyLimit != 5 ||
settings.IdentityClientHourlyLimit != 30 {
t.Fatalf("identity defaults = %q, %s, %d, %d", settings.IdentityKeySecret,
settings.VerificationMailMinInterval, settings.VerificationMailDailyLimit, settings.IdentityClientHourlyLimit)
}
}
func TestLoadFromEnvIdentityExplicit(t *testing.T) {
secret := strings.Repeat("k", MinIdentityKeySecretBytes)
settings, err := LoadFromEnv(testEnvironment(map[string]string{
"IDENTITY_KEY_SECRET": " " + secret + " ",
"VERIFICATION_MAIL_MIN_INTERVAL": "90s",
"VERIFICATION_MAIL_DAILY_LIMIT": "3",
"IDENTITY_CLIENT_HOURLY_LIMIT": "100",
}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.IdentityKeySecret != secret || settings.VerificationMailMinInterval != 90*time.Second ||
settings.VerificationMailDailyLimit != 3 || settings.IdentityClientHourlyLimit != 100 {
t.Fatalf("identity settings were not read: %+v", settings)
}
}
func TestLoadFromEnvRejectsIdentitySettings(t *testing.T) {
tests := map[string]struct {
key, value, want string
}{
"short secret": {"IDENTITY_KEY_SECRET", "too-short", "Config.ValidateIdentity - IDENTITY_KEY_SECRET"},
"interval below": {"VERIFICATION_MAIL_MIN_INTERVAL", "500ms", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"},
"interval above": {"VERIFICATION_MAIL_MIN_INTERVAL", "2h", "Config.ValidateIdentity - VERIFICATION_MAIL_MIN_INTERVAL"},
"interval malformed": {"VERIFICATION_MAIL_MIN_INTERVAL", "soon", "config.durationOrDefault - parse VERIFICATION_MAIL_MIN_INTERVAL"},
"daily zero": {"VERIFICATION_MAIL_DAILY_LIMIT", "0", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"},
"daily too high": {"VERIFICATION_MAIL_DAILY_LIMIT", "51", "Config.ValidateIdentity - VERIFICATION_MAIL_DAILY_LIMIT"},
"daily malformed": {"VERIFICATION_MAIL_DAILY_LIMIT", "five", "config.intOrDefault - VERIFICATION_MAIL_DAILY_LIMIT"},
"client zero": {"IDENTITY_CLIENT_HOURLY_LIMIT", "0", "Config.ValidateIdentity - IDENTITY_CLIENT_HOURLY_LIMIT"},
}
for name, test := range tests {
_, err := LoadFromEnv(testEnvironment(map[string]string{test.key: test.value}))
if err == nil || !strings.HasPrefix(err.Error(), test.want) {
t.Fatalf("LoadFromEnv(%s) error = %v, want an error starting with %q", name, err, test.want)
}
}
}
func TestIdentityErrorsDoNotQuoteTheSecret(t *testing.T) {
_, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_KEY_SECRET": "short-secret-value"}))
if err == nil || strings.Contains(err.Error(), "short-secret-value") {
t.Fatalf("LoadFromEnv() error = %v, want an error without the secret", err)
}
}
func TestLoadFromEnvIdentityEmptyLimitsMeanUnset(t *testing.T) {
settings, err := LoadFromEnv(testEnvironment(map[string]string{
"VERIFICATION_MAIL_MIN_INTERVAL": "",
"VERIFICATION_MAIL_DAILY_LIMIT": " ",
"IDENTITY_CLIENT_HOURLY_LIMIT": "",
}))
if err != nil {
t.Fatalf("LoadFromEnv() error = %v", err)
}
if settings.VerificationMailMinInterval != time.Minute || settings.VerificationMailDailyLimit != 5 || settings.IdentityClientHourlyLimit != 30 {
t.Fatalf("empty limits = %s, %d, %d, want the defaults", settings.VerificationMailMinInterval,
settings.VerificationMailDailyLimit, settings.IdentityClientHourlyLimit)
}
}
func TestLoadFromEnvRequiresTheIdentityKeySecret(t *testing.T) {
// Not through testEnvironment, which supplies a secret.
lookup := func(key string) (string, bool) {
if key == "IDENTITY_KEY_SECRET" || key == "IDENTITY_ALLOW_EPHEMERAL_KEY" {
return "", false
}
return testEnvironment(nil)(key)
}
_, err := LoadFromEnv(lookup)
if err == nil || !strings.Contains(err.Error(), "IDENTITY_KEY_SECRET is required") || !strings.Contains(err.Error(), "openssl rand") {
t.Fatalf("LoadFromEnv() error = %v, want the missing secret named with how to generate one", err)
}
ephemeral := func(key string) (string, bool) {
if key == "IDENTITY_ALLOW_EPHEMERAL_KEY" {
return "true", true
}
return lookup(key)
}
settings, err := LoadFromEnv(ephemeral)
if err != nil || !settings.IdentityAllowEphemeralKey {
t.Fatalf("LoadFromEnv(ephemeral) = %v, %v, want an accepted development configuration", settings.IdentityAllowEphemeralKey, err)
}
}
func TestLoadFromEnvRejectsThePlaceholderSecret(t *testing.T) {
const placeholder = "replace-this-identity-key-secret-0123456789abcdef"
_, err := LoadFromEnv(testEnvironment(map[string]string{"IDENTITY_KEY_SECRET": placeholder}))
if err == nil || !strings.Contains(err.Error(), "example placeholder") || strings.Contains(err.Error(), placeholder) {
t.Fatalf("LoadFromEnv() error = %v, want a refusal that does not quote the value", err)
}
}
@@ -0,0 +1,84 @@
-- +goose Up
-- Replay records of anonymous commands that carry an Idempotency-Key, first
-- of all the registration. A record is written in the same transaction as
-- the effect it guards, so a record that is visible always belongs to a
-- committed command: a running command is represented by the uncommitted row
-- itself, on which a concurrent request with the same scope waits.
--
-- Nothing here identifies a person or reveals a credential. scope_hash is an
-- HMAC-SHA-256 with a server secret over the operation, the key, and the
-- normalized email, and fingerprint is an HMAC-SHA-256 with a server secret
-- over the canonical request body; without the secret neither can be used to
-- confirm an email address or to test a password offline.
CREATE TABLE idempotency_records (
scope_hash bytea NOT NULL,
fingerprint bytea NOT NULL,
created_at timestamptz NOT NULL,
-- The key may be accepted as new once this time has passed.
expires_at timestamptz NOT NULL,
CONSTRAINT idempotency_records_pkey PRIMARY KEY (scope_hash),
CONSTRAINT idempotency_records_scope_hash_sha256 CHECK (
octet_length(scope_hash) = 32
),
CONSTRAINT idempotency_records_fingerprint_sha256 CHECK (
octet_length(fingerprint) = 32
),
CONSTRAINT idempotency_records_expiry_after_creation CHECK (
expires_at > created_at
)
);
-- Serves the bounded purge of expired records.
CREATE INDEX idempotency_records_expires_at_idx
ON idempotency_records (expires_at);
-- Pending credentials of a registration, bound to the verification token
-- issued for it. A registration of an unverified address never changes the
-- credentials of the account row: it issues a token that carries its own
-- password hash and scenario. Confirming a token applies the credentials of
-- that token, so whoever registered an address first or last cannot make the
-- owner of the address adopt a password the owner did not choose. NULL for
-- tokens that carry none (a resend copies them from the registration's
-- latest token; password reset tokens carry none).
ALTER TABLE email_tokens
ADD COLUMN pending_password_hash text,
ADD COLUMN pending_scenario text,
ADD COLUMN pending_onboarding_step text,
ADD CONSTRAINT email_tokens_pending_all_or_none CHECK (
(pending_password_hash IS NULL) = (pending_scenario IS NULL)
AND (pending_scenario IS NULL) = (pending_onboarding_step IS NULL)
),
ADD CONSTRAINT email_tokens_invalidated_keeps_no_pending CHECK (
invalidated_at IS NULL OR pending_password_hash IS NULL
),
ADD CONSTRAINT email_tokens_pending_password_hash_format CHECK (
pending_password_hash IS NULL
OR (
char_length(pending_password_hash) <= 512
AND pending_password_hash
~ '^\$argon2id\$v=19\$m=[1-9][0-9]{0,9},t=[1-9][0-9]{0,9},p=[1-9][0-9]{0,2}\$[A-Za-z0-9+/]+\$[A-Za-z0-9+/]+$'
)
),
ADD CONSTRAINT email_tokens_pending_scenario_step CHECK (
pending_scenario IS NULL
OR (
pending_scenario = 'candidate'
AND pending_onboarding_step = 'candidate_consents'
)
OR (
pending_scenario = 'employer'
AND pending_onboarding_step = 'employer_company'
)
);
-- +goose Down
ALTER TABLE email_tokens
DROP CONSTRAINT email_tokens_pending_scenario_step,
DROP CONSTRAINT email_tokens_invalidated_keeps_no_pending,
DROP CONSTRAINT email_tokens_pending_password_hash_format,
DROP CONSTRAINT email_tokens_pending_all_or_none,
DROP COLUMN pending_onboarding_step,
DROP COLUMN pending_scenario,
DROP COLUMN pending_password_hash;
DROP TABLE idempotency_records;
+139 -4
View File
@@ -273,7 +273,10 @@ INSERT INTO email_tokens (
token_hash,
registration_version,
created_at,
expires_at
expires_at,
pending_password_hash,
pending_scenario,
pending_onboarding_step
) VALUES (
sqlc.arg(id),
sqlc.arg(user_id),
@@ -281,12 +284,92 @@ INSERT INTO email_tokens (
sqlc.arg(token_hash),
sqlc.arg(registration_version),
sqlc.arg(created_at),
sqlc.arg(expires_at)
sqlc.arg(expires_at),
sqlc.narg(pending_password_hash),
sqlc.narg(pending_scenario),
sqlc.narg(pending_onboarding_step)
);
-- The pending credentials of the newest token of a registration, for a
-- resend, which issues its token with the same credentials.
-- name: GetLatestPendingRegistration :one
SELECT
pending_password_hash,
pending_scenario,
pending_onboarding_step
FROM email_tokens
WHERE
user_id = sqlc.arg(user_id)
AND purpose = sqlc.arg(purpose)
AND registration_version = sqlc.arg(registration_version)
AND pending_password_hash IS NOT NULL
ORDER BY created_at DESC, id DESC
LIMIT 1;
-- Starts a new registration of an unverified account without touching its
-- credentials, scenario, or onboarding step: the new registration carries
-- them on its verification token. Advances the registration version, which
-- ends every earlier token, and deletes the registration C1 of the earlier
-- registrant like UpdateUserRegistration does.
-- name: AdvanceUserRegistration :one
WITH updated AS (
UPDATE users
SET
registration_version = registration_version + 1,
last_registered_at = sqlc.arg(registered_at),
updated_at = sqlc.arg(registered_at),
version = version + 1
WHERE
users.id = sqlc.arg(id)
AND users.version = sqlc.arg(expected_version)
AND users.email_verified_at IS NULL
RETURNING
users.id,
users.email,
users.email_normalized,
users.password_hash,
users.scenario,
users.onboarding_step,
users.email_verified_at,
users.registration_version,
users.last_registered_at,
users.version,
users.created_at,
users.updated_at
),
discarded_consent AS (
DELETE FROM consent_records
USING updated
WHERE
consent_records.subject_id = updated.id
AND consent_records.purpose = 'c1'
AND consent_records.source = 'registration'
)
SELECT
updated.id,
updated.email,
updated.email_normalized,
updated.password_hash,
updated.scenario,
updated.onboarding_step,
updated.email_verified_at,
updated.registration_version,
updated.last_registered_at,
updated.version,
updated.created_at,
updated.updated_at
FROM updated;
-- name: InvalidateActiveEmailTokens :execrows
UPDATE email_tokens
SET invalidated_at = sqlc.arg(invalidated_at)
SET
invalidated_at = sqlc.arg(invalidated_at),
-- An invalidated token keeps no password hash: it can never be confirmed.
pending_password_hash = NULL,
pending_scenario = NULL,
pending_onboarding_step = NULL
WHERE
user_id = sqlc.arg(user_id)
AND purpose = sqlc.arg(purpose)
@@ -323,7 +406,10 @@ RETURNING
token.created_at,
token.expires_at,
token.consumed_at,
token.invalidated_at;
token.invalidated_at,
token.pending_password_hash,
token.pending_scenario,
token.pending_onboarding_step;
-- Explains why ConsumeEmailToken matched no row.
-- name: GetEmailTokenState :one
@@ -416,3 +502,52 @@ SET revoked_at = sqlc.arg(revoked_at)
WHERE
user_id = sqlc.arg(user_id)
AND revoked_at IS NULL;
-- Stores the replay record of a command. A record whose retention has passed
-- is replaced, so the key is accepted as new after the retention. A live
-- record is left as it is and nothing is returned; the caller then reads it
-- with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
-- on the row of the first one until its transaction ends.
-- name: ReserveIdempotencyRecord :one
INSERT INTO idempotency_records (
scope_hash,
fingerprint,
created_at,
expires_at
) VALUES (
sqlc.arg(scope_hash),
sqlc.arg(fingerprint),
sqlc.arg(created_at),
sqlc.arg(expires_at)
)
ON CONFLICT (scope_hash) DO UPDATE
SET
fingerprint = excluded.fingerprint,
created_at = excluded.created_at,
expires_at = excluded.expires_at
WHERE idempotency_records.expires_at <= excluded.created_at
RETURNING scope_hash, fingerprint, created_at, expires_at;
-- name: GetLiveIdempotencyRecord :one
SELECT
scope_hash,
fingerprint,
created_at,
expires_at
FROM idempotency_records
WHERE
scope_hash = sqlc.arg(scope_hash)
AND expires_at > sqlc.arg(at);
-- Deletes at most batch_limit expired records. Locked rows are skipped, so
-- the statement never waits for a concurrent reservation.
-- name: PurgeExpiredIdempotencyRecords :execrows
DELETE FROM idempotency_records
WHERE scope_hash IN (
SELECT stale.scope_hash
FROM idempotency_records AS stale
WHERE stale.expires_at <= sqlc.arg(at)
ORDER BY stale.expires_at
LIMIT sqlc.arg(batch_limit)
FOR UPDATE SKIP LOCKED
);
@@ -131,6 +131,7 @@ func bootstrap(t *testing.T, services ...service) *testEnvironment {
"REDIS_PASSWORD": redisPassword,
"REDIS_TIMEOUT": redisTimeout.String(),
"SEAWEEDFS_ACCESS_KEY": seaweedfsAccessKey,
"IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab",
"SEAWEEDFS_SECRET_KEY": seaweedfsSecretKey,
"SEAWEEDFS_BUCKET": seaweedfsBucket,
"SEAWEEDFS_TIMEOUT": storageTimeout.String(),
@@ -629,6 +629,7 @@ func (harness *quotaHarness) gateFromConfig(t *testing.T, mail map[string]string
func loadQuotaConfig(mail map[string]string) (config.Config, error) {
values := map[string]string{
"SEAWEEDFS_ACCESS_KEY": "test-access",
"IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab",
"SEAWEEDFS_SECRET_KEY": "test-secret",
"EMAIL_FROM": "no-reply@example.com",
"EMAIL_ACCOUNT": quotaAccount,
@@ -0,0 +1,87 @@
//go:build integration
package integration_test
import (
"errors"
"testing"
"time"
"lincodex/backend/internal/port/outbound"
)
func TestRedisRateLimiter(t *testing.T) {
env := bootstrap(t, redisService)
ctx := t.Context()
limiter := env.Redis
t.Run("admits up to the limit and then reports the wait", func(t *testing.T) {
rule := outbound.RateLimitRule{Window: 10 * time.Second, Limit: 2}
for attempt := 1; attempt <= 2; attempt++ {
decision, err := limiter.Take(ctx, "limit-basic", rule)
if err != nil || !decision.Allowed || decision.RetryAfter != 0 {
t.Fatalf("take %d = %+v, %v, want allowed", attempt, decision, err)
}
}
decision, err := limiter.Take(ctx, "limit-basic", rule)
if err != nil || decision.Allowed || decision.RetryAfter <= 0 || decision.RetryAfter > rule.Window {
t.Fatalf("third take = %+v, %v, want refused with a wait inside the window", decision, err)
}
})
t.Run("a refused take counts nothing in any rule", func(t *testing.T) {
interval := outbound.RateLimitRule{Window: 300 * time.Millisecond, Limit: 1}
daily := outbound.RateLimitRule{Window: time.Hour, Limit: 3}
if decision, err := limiter.Take(ctx, "limit-atomic", interval, daily); err != nil || !decision.Allowed {
t.Fatalf("first take = %+v, %v", decision, err)
}
// Refused by the interval: the daily counter must stay at 1.
for range 5 {
if decision, err := limiter.Take(ctx, "limit-atomic", interval, daily); err != nil || decision.Allowed {
t.Fatalf("take inside the interval = %+v, %v, want refused", decision, err)
}
}
time.Sleep(350 * time.Millisecond)
for attempt := 2; attempt <= 3; attempt++ {
decision, err := limiter.Take(ctx, "limit-atomic", interval, daily)
if err != nil || !decision.Allowed {
t.Fatalf("take %d after the interval = %+v, %v, want allowed", attempt, decision, err)
}
time.Sleep(350 * time.Millisecond)
}
decision, err := limiter.Take(ctx, "limit-atomic", interval, daily)
if err != nil || decision.Allowed || decision.RetryAfter < 50*time.Minute {
t.Fatalf("take over the daily limit = %+v, %v, want refused until the daily window ends", decision, err)
}
})
t.Run("keys are independent and windows reset", func(t *testing.T) {
rule := outbound.RateLimitRule{Window: 200 * time.Millisecond, Limit: 1}
for _, key := range []string{"limit-a", "limit-b"} {
if decision, err := limiter.Take(ctx, key, rule); err != nil || !decision.Allowed {
t.Fatalf("first take of %s = %+v, %v", key, decision, err)
}
}
time.Sleep(250 * time.Millisecond)
if decision, err := limiter.Take(ctx, "limit-a", rule); err != nil || !decision.Allowed {
t.Fatalf("take after the window = %+v, %v, want allowed", decision, err)
}
})
t.Run("rejects an invalid rule", func(t *testing.T) {
for name, rules := range map[string][]outbound.RateLimitRule{
"no rule": nil,
"zero limit": {{Window: time.Second, Limit: 0}},
"zero window": {{Window: 0, Limit: 1}},
"tiny window": {{Window: time.Microsecond, Limit: 1}},
"second fails": {{Window: time.Second, Limit: 1}, {Window: time.Second, Limit: -1}},
} {
if _, err := limiter.Take(ctx, "limit-invalid", rules...); !errors.Is(err, outbound.ErrInvalidRateLimitRule) {
t.Fatalf("Take(%s) error = %v, want ErrInvalidRateLimitRule", name, err)
}
}
if _, err := limiter.Take(ctx, "", outbound.RateLimitRule{Window: time.Second, Limit: 1}); !errors.Is(err, outbound.ErrInvalidRateLimitRule) {
t.Fatalf("Take with an empty key error = %v", err)
}
})
}
@@ -0,0 +1,642 @@
//go:build integration
package integration_test
import (
"bytes"
"context"
"crypto/sha256"
"errors"
"log/slog"
"net/http"
"net/http/httptest"
"regexp"
"slices"
"strconv"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
httpadapter "lincodex/backend/internal/adapter/primary/http"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
"lincodex/backend/internal/adapter/secondary/mail/resend"
"lincodex/backend/internal/adapter/secondary/mail/resend/resendfixture"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/health"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
"lincodex/backend/internal/usecase/policy"
)
const (
registrationTestTimeout = 5 * time.Minute
registrationPath = "/api/v1/identity/registrations"
resendPath = "/api/v1/identity/email-verification-requests"
registrationPassword = "correct horse battery staple"
registrationC1 = `{"text_version":"c1-2026-10-01","accepted":true}`
// registrationMinInterval is long enough that one request, including the
// password hash, finishes well inside it, and short enough to wait out.
// The production default is a minute.
registrationMinInterval = 3 * time.Second
registrationDailyLimit = 3
registrationSecret = "integration-test-identity-key-secret-0123456789"
)
var (
registrationTables = slices.Concat(mailSenderTables, usersDependentTables, []pgx.Identifier{{"idempotency_records"}})
// verificationLinkToken finds the token in the fragment of the link of
// the sent message.
verificationLinkToken = regexp.MustCompile(`#token=([A-Za-z0-9_-]{32,128})`)
)
type registrationHarness struct {
pool *pgxpool.Pool
router http.Handler
sender *notification.ServiceMailSender
fixture *resendfixture.Server
clock *testClock
logs *syncBuffer
identity *postgresadapter.IdentityStore
// registration is the usecase behind the router.
registration *identity.Registration
// nextKey makes every request carry a new Idempotency-Key.
nextKey int
// start is the application time at the beginning of every subtest.
start time.Time
}
func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironment, clientHourlyLimit int64) *registrationHarness {
t.Helper()
pool := env.newPoolWithMaxConns(ctx, t, 16)
// The demo policy is effective from its publication by the database clock,
// so the application clock must not be earlier than now.
clock := &testClock{now: time.Now().UTC().Add(time.Minute).Truncate(time.Microsecond)}
start := clock.Now()
logs := &syncBuffer{}
logger := slog.New(slog.NewJSONHandler(logs, nil))
templates, err := mailtemplate.NewRenderer(env.Config.AppPublicURL)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
fixture := resendfixture.New()
t.Cleanup(fixture.Close)
transport, err := resend.NewLoopbackSender(resendfixture.APIKey, mailSenderFrom, 10*time.Second, fixture.URL(), clock.Now)
if err != nil {
t.Fatalf("NewLoopbackSender() error = %v", err)
}
account, err := domain.NewMailProviderAccount("resend", mailSenderAccount)
if err != nil {
t.Fatalf("NewMailProviderAccount() error = %v", err)
}
// The product policy carries the verification token lifetime.
if _, err := policy.NewPublisher(postgresadapter.NewPolicyStore(pool).Policies(), clock.Now).EnsureDemoProductPolicy(ctx); err != nil {
t.Fatalf("EnsureDemoProductPolicy() error = %v", err)
}
hasher, err := argon2id.NewHasher(2)
if err != nil {
t.Fatalf("NewHasher() error = %v", err)
}
keyring, err := identity.NewKeyring([]byte(registrationSecret))
if err != nil {
t.Fatalf("NewKeyring() error = %v", err)
}
transactor := postgresadapter.NewTransactor(pool)
identityStore := postgresadapter.NewIdentityStore(pool)
registration, err := identity.NewRegistration(identity.RegistrationDependencies{
Transactor: transactor,
ConsentTexts: postgresadapter.NewConsentStore(pool),
Idempotency: identityStore.IdempotencyRecords(),
Consents: consent.NewService(transactor, clock.Now),
Credentials: identity.NewCredentials(hasher),
Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(templates), account, clock.Now),
Limiter: env.Redis,
Keyring: keyring,
Clock: clock.Now,
}, identity.RegistrationSettings{
MailMinInterval: registrationMinInterval,
MailDailyLimit: registrationDailyLimit,
ClientHourlyLimit: clientHourlyLimit,
})
if err != nil {
t.Fatalf("NewRegistration() error = %v", err)
}
responder := problem.NewResponder(logger)
healthHandler := v1.NewHealthHandler(health.NewReadiness(env.Postgres), time.Second)
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler(registration)))
router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, prometheus.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
limits, err := domain.NewMailQuotaLimits(1000, 10000)
if err != nil {
t.Fatalf("NewMailQuotaLimits() error = %v", err)
}
gate := notification.NewQuotaGate(account, limits, resend.IdempotencyWindow, clock.Now, logger)
sender, err := notification.NewServiceMailSender(transactor, transport, gate, notification.ServiceMailSenderSettings{
Account: account,
Lease: time.Minute,
StoreTimeout: 30 * time.Second,
SettleBudget: mailSenderSettleBudget,
ShutdownSettleBudget: time.Second,
MaxFailures: 3,
Retry: notification.RetryPolicy{Initial: time.Minute, Max: 30 * time.Minute},
}, clock.Now, logger)
if err != nil {
t.Fatalf("NewServiceMailSender() error = %v", err)
}
return &registrationHarness{
start: start, pool: pool, router: router, sender: sender, fixture: fixture, clock: clock, logs: logs, identity: identityStore,
registration: registration,
}
}
type registrationResponse struct {
status int
body string
retryAfter string
// contentType is part of the shape that must not depend on the branch.
contentType string
}
func (harness *registrationHarness) post(t *testing.T, path, body string, headers map[string]string) registrationResponse {
t.Helper()
request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
request.Header.Set("Content-Type", "application/json")
for name, value := range headers {
request.Header.Set(name, value)
}
recorder := httptest.NewRecorder()
harness.router.ServeHTTP(recorder, request)
return registrationResponse{
status: recorder.Code,
body: recorder.Body.String(),
retryAfter: recorder.Header().Get("Retry-After"),
contentType: recorder.Header().Get("Content-Type"),
}
}
func registrationBody(email, scenario, password, consent string) string {
return `{"email":"` + email + `","password":"` + password + `","scenario":"` + scenario + `","consent_c1":` + consent + `}`
}
// register posts a registration under a fresh Idempotency-Key unless key is
// given.
func (harness *registrationHarness) register(t *testing.T, email, scenario, key string) registrationResponse {
t.Helper()
return harness.registerBody(t, registrationBody(email, scenario, registrationPassword, registrationC1), key)
}
func (harness *registrationHarness) registerBody(t *testing.T, body, key string) registrationResponse {
t.Helper()
if key == "" {
harness.nextKey++
key = "integration-key-" + strconv.Itoa(harness.nextKey)
}
return harness.post(t, registrationPath, body, map[string]string{"Idempotency-Key": key})
}
func (harness *registrationHarness) resend(t *testing.T, email string) registrationResponse {
t.Helper()
return harness.post(t, resendPath, `{"email":"`+email+`"}`, nil)
}
func (harness *registrationHarness) count(ctx context.Context, t *testing.T, query string, args ...any) int {
t.Helper()
var count int
if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil {
t.Fatalf("count %q: %v", query, err)
}
return count
}
// drain runs the sending worker until it finds nothing due and returns how
// many deliveries it settled.
func (harness *registrationHarness) drain(ctx context.Context, t *testing.T) int {
t.Helper()
settled := 0
for range 20 {
result, err := harness.sender.ProcessNext(ctx, ctx)
if err != nil {
t.Fatalf("ProcessNext() error = %v", err)
}
if result.Outcome == inbound.MailPassIdle {
return settled
}
settled++
}
t.Fatal("the sending worker did not go idle")
return settled
}
// truncate empties the tables of the flow. CASCADE also empties tables that
// later migrations add with a reference to users, so this suite does not
// depend on usersDependentTables being kept up to date by other tasks.
func (harness *registrationHarness) truncate(ctx context.Context, t *testing.T) {
t.Helper()
names := make([]string, 0, len(registrationTables))
for _, table := range registrationTables {
names = append(names, table.Sanitize())
}
harness.exec(ctx, t, "TRUNCATE "+strings.Join(names, ", ")+" CASCADE")
}
func (harness *registrationHarness) exec(ctx context.Context, t *testing.T, statement string, args ...any) {
t.Helper()
if _, err := harness.pool.Exec(ctx, statement, args...); err != nil {
t.Fatalf("exec %q: %v", statement, err)
}
}
func (harness *registrationHarness) assertLogsHoldNoSecrets(t *testing.T, forbidden ...string) {
t.Helper()
logs := harness.logs.String()
for _, marker := range forbidden {
if marker != "" && strings.Contains(logs, marker) {
t.Fatalf("a secret or an address reached the logs:\n%s", logs)
}
}
}
// requireProblemStatus checks the status and the problem code of a response
// and returns its body.
func requireProblemStatus(t *testing.T, response registrationResponse, status int, code string) string {
t.Helper()
if response.status != status || !strings.Contains(response.body, `"code":"`+code+`"`) {
t.Fatalf("response = %d %s, want %d with code %s", response.status, response.body, status, code)
}
return response.body
}
// requireRetryWithinInterval checks the wait of a refusal by the minimum
// interval: at least one second and at most the interval.
func requireRetryWithinInterval(t *testing.T, response registrationResponse) {
t.Helper()
wait, err := strconv.Atoi(response.retryAfter)
if err != nil || wait < 1 || wait > int(registrationMinInterval/time.Second) {
t.Fatalf("Retry-After = %q, want 1 to %d seconds", response.retryAfter, int(registrationMinInterval/time.Second))
}
}
func requireAccepted(t *testing.T, response registrationResponse) {
t.Helper()
if response.status != http.StatusAccepted || response.body != `{"status":"accepted"}` {
t.Fatalf("response = %d %s, want the neutral 202", response.status, response.body)
}
}
func TestRegistrationOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout)
defer cancel()
harness := newRegistrationHarness(ctx, t, env, 1000)
reset := func(t *testing.T) {
t.Helper()
harness.truncate(ctx, t)
harness.clock.Set(harness.start)
}
t.Run("a candidate registers in one transaction with C1 and a queued message", func(t *testing.T) {
reset(t)
requests := len(harness.fixture.Requests())
response := harness.register(t, "Candidate.One@Example.com", "candidate", "")
requireAccepted(t, response)
var scenario, step string
var verified *time.Time
var version int64
err := harness.pool.QueryRow(ctx,
`SELECT scenario, onboarding_step, email_verified_at, registration_version FROM users WHERE email_normalized = 'candidate.one@example.com'`,
).Scan(&scenario, &step, &verified, &version)
if err != nil {
t.Fatalf("read the account: %v", err)
}
if scenario != "candidate" || step != "candidate_consents" || verified != nil || version != 1 {
t.Fatalf("account = %s %s verified=%v version=%d", scenario, step, verified, version)
}
assertRowCount(ctx, t, harness.pool, usersTable, 1)
// C1 with the current text version and its hash; nothing else, in
// particular no C4.
c1Text, err := postgresadapter.NewConsentStore(harness.pool).ConsentTexts().Current(ctx, domain.ConsentPurposePersonalData, harness.clock.Now())
if err != nil {
t.Fatalf("read the current C1 text: %v", err)
}
assertRowCount(ctx, t, harness.pool, consentRecordsTable, 1)
var purpose, textVersion, source string
var textHash []byte
var revoked *time.Time
err = harness.pool.QueryRow(ctx, `SELECT purpose, text_version, text_hash, source, revoked_at FROM consent_records`).
Scan(&purpose, &textVersion, &textHash, &source, &revoked)
wantHash := c1Text.Hash()
if err != nil || purpose != "c1" || textVersion != string(c1Text.Version()) || !bytes.Equal(textHash, wantHash[:]) ||
source != "registration" || revoked != nil {
t.Fatalf("consent record = %s %s %x %s revoked=%v, err=%v", purpose, textVersion, textHash, source, revoked, err)
}
if harness.count(ctx, t, `SELECT count(*) FROM consent_records WHERE purpose = 'c4'`) != 0 {
t.Fatal("C4 was recorded by the registration")
}
// One token hash (never the raw token) and one queued delivery bound
// to it, in the same commit.
assertRowCount(ctx, t, harness.pool, emailTokensTable, 1)
var tokenHash []byte
var tokenID, deliveryTokenID string
var tokenVersion int64
if err := harness.pool.QueryRow(ctx, `SELECT id::text, token_hash, registration_version FROM email_tokens`).Scan(&tokenID, &tokenHash, &tokenVersion); err != nil {
t.Fatalf("read the token: %v", err)
}
if len(tokenHash) != sha256.Size || tokenVersion != 1 {
t.Fatalf("token hash length = %d, version = %d", len(tokenHash), tokenVersion)
}
var status string
if err := harness.pool.QueryRow(ctx, `SELECT status, email_token_id::text FROM deliveries`).Scan(&status, &deliveryTokenID); err != nil {
t.Fatalf("read the delivery: %v", err)
}
if status != string(domain.DeliveryStatusPending) || deliveryTokenID != tokenID {
t.Fatalf("delivery = %s bound to %s, want pending bound to token %s", status, deliveryTokenID, tokenID)
}
// The sending worker sends it through the local Resend fixture.
if settled := harness.drain(ctx, t); settled != 1 {
t.Fatalf("settled %d deliveries, want 1", settled)
}
sent := harness.fixture.Requests()[requests:]
if len(sent) != 1 || !slices.Equal(sent[0].To, []string{"Candidate.One@Example.com"}) {
t.Fatalf("fixture received %d messages to %v", len(sent), sent)
}
link := verificationLinkToken.FindStringSubmatch(sent[0].Text)
if link == nil {
t.Fatal("the message holds no verification link with the token in the fragment")
}
sum := sha256.Sum256([]byte(link[1]))
if !bytes.Equal(sum[:], tokenHash) {
t.Fatal("the token of the link does not match the stored hash")
}
harness.assertLogsHoldNoSecrets(t, "Candidate.One", registrationPassword, link[1])
})
t.Run("an employer registers once and a repeat creates no second account and reveals nothing", func(t *testing.T) {
reset(t)
first := harness.register(t, "employer@example.com", "employer", "employer-key-1")
requireAccepted(t, first)
var step string
if err := harness.pool.QueryRow(ctx, `SELECT onboarding_step FROM users`).Scan(&step); err != nil || step != "employer_company" {
t.Fatalf("onboarding step = %q, err = %v, want employer_company", step, err)
}
// The same request replays: one account, one token, one message.
replay := harness.register(t, "employer@example.com", "employer", "employer-key-1")
if replay != first {
t.Fatalf("replay = %+v, want exactly %+v", replay, first)
}
assertRowCount(ctx, t, harness.pool, usersTable, 1)
assertRowCount(ctx, t, harness.pool, emailTokensTable, 1)
assertRowCount(ctx, t, harness.pool, pgx.Identifier{"deliveries"}, 1)
// The same key with another body is a reused key.
reused := harness.registerBody(t, registrationBody("employer@example.com", "employer", "another correct horse battery", registrationC1), "employer-key-1")
requireProblemStatus(t, reused, http.StatusUnprocessableEntity, "idempotency_key_reused")
// A new registration of the pending address, with another password and
// scenario, never changes the credentials of the account row.
var firstHash string
if err := harness.pool.QueryRow(ctx, `SELECT password_hash FROM users`).Scan(&firstHash); err != nil {
t.Fatalf("read the password hash: %v", err)
}
time.Sleep(registrationMinInterval + 100*time.Millisecond)
again := harness.registerBody(t, registrationBody("employer@example.com", "candidate", "an attacker chosen long password", registrationC1), "")
if again != first {
t.Fatalf("repeat = %+v, want the same answer as the first registration %+v", again, first)
}
assertRowCount(ctx, t, harness.pool, usersTable, 1)
var scenario string
var version int64
if err := harness.pool.QueryRow(ctx, `SELECT scenario, registration_version FROM users`).Scan(&scenario, &version); err != nil {
t.Fatalf("read the account: %v", err)
}
var hashAfter, stepAfter string
if err := harness.pool.QueryRow(ctx, `SELECT password_hash, onboarding_step FROM users`).Scan(&hashAfter, &stepAfter); err != nil {
t.Fatalf("read the account: %v", err)
}
if scenario != "employer" || stepAfter != "employer_company" || hashAfter != firstHash || version != 2 {
t.Fatalf("after the repeat: scenario = %s, step = %s, registration version = %d, hash unchanged = %t; want the first registration's credentials and version 2",
scenario, stepAfter, version, hashAfter == firstHash)
}
// Each token carries the pending credentials of its own registration;
// the invalidated first token keeps none.
rows, err := harness.pool.Query(ctx, `SELECT pending_password_hash, pending_scenario, pending_onboarding_step, registration_version, invalidated_at IS NOT NULL
FROM email_tokens ORDER BY created_at, id`)
if err != nil {
t.Fatalf("read the tokens: %v", err)
}
type pendingRow struct {
hash, scenario, step *string
version int64
invalidated bool
}
var pendings []pendingRow
for rows.Next() {
var row pendingRow
if err := rows.Scan(&row.hash, &row.scenario, &row.step, &row.version, &row.invalidated); err != nil {
t.Fatalf("scan a token: %v", err)
}
pendings = append(pendings, row)
}
rows.Close()
if len(pendings) != 2 ||
!pendings[0].invalidated || pendings[0].hash != nil || pendings[0].scenario != nil || pendings[0].step != nil || pendings[0].version != 1 ||
pendings[1].invalidated || pendings[1].hash == nil || *pendings[1].hash == firstHash ||
pendings[1].scenario == nil || *pendings[1].scenario != "candidate" ||
pendings[1].step == nil || *pendings[1].step != "candidate_consents" || pendings[1].version != 2 {
t.Fatalf("tokens do not carry their own pending credentials: %+v", pendings)
}
assertRowCount(ctx, t, harness.pool, consentRecordsTable, 1)
if active := harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NULL AND consumed_at IS NULL`); active != 1 {
t.Fatalf("%d unused tokens, want exactly the new one", active)
}
if all := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`); all != 2 {
t.Fatalf("%d tokens, want the replaced one and the new one", all)
}
// A verified address is left alone and answers the same way.
var userID string
if err := harness.pool.QueryRow(ctx, `SELECT id::text FROM users`).Scan(&userID); err != nil {
t.Fatalf("read the account ID: %v", err)
}
harness.exec(ctx, t, `UPDATE users SET email_verified_at = $1 WHERE id = $2`, harness.clock.Now(), userID)
tokens := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`)
deliveries := harness.count(ctx, t, `SELECT count(*) FROM deliveries`)
time.Sleep(registrationMinInterval + 100*time.Millisecond)
verified := harness.register(t, "employer@example.com", "employer", "")
if verified != first {
t.Fatalf("verified address answered %+v, want %+v", verified, first)
}
if harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) != tokens ||
harness.count(ctx, t, `SELECT count(*) FROM deliveries`) != deliveries ||
harness.count(ctx, t, `SELECT count(*) FROM users WHERE scenario = 'employer' AND registration_version = 2`) != 1 {
t.Fatal("a registration of a verified address changed the account or queued a message")
}
// The replaced token never reaches the user: the sending worker
// cancels its message because the token is no longer current.
harness.drain(ctx, t)
harness.assertLogsHoldNoSecrets(t, "employer@example.com", registrationPassword)
})
t.Run("a stale consent text version is refused the same way and consumes nothing", func(t *testing.T) {
reset(t)
stale := `{"text_version":"c1-2000-01-01","accepted":true}`
for _, email := range []string{"new.address@example.com", "known.address@example.com"} {
if email == "known.address@example.com" {
requireAccepted(t, harness.register(t, email, "candidate", ""))
time.Sleep(registrationMinInterval + 100*time.Millisecond)
}
response := harness.registerBody(t, registrationBody(email, "candidate", registrationPassword, stale), "")
body := requireProblemStatus(t, response, http.StatusBadRequest, "validation_failed")
if !strings.Contains(body, `"/consent_c1/text_version"`) {
t.Fatalf("problem %s does not point at /consent_c1/text_version", body)
}
}
assertRowCount(ctx, t, harness.pool, usersTable, 1)
})
t.Run("resend replaces the unused token and is rate limited without a new token", func(t *testing.T) {
reset(t)
requests := len(harness.fixture.Requests())
const email = "resend.candidate@example.com"
requireAccepted(t, harness.register(t, email, "candidate", ""))
assertRowCount(ctx, t, harness.pool, emailTokensTable, 1)
// Inside the minimum interval: 429 with the wait, and no new token.
limited := harness.resend(t, email)
requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited")
requireRetryWithinInterval(t, limited)
assertRowCount(ctx, t, harness.pool, emailTokensTable, 1)
// Within the daily limit: every resend replaces the previous token.
for sent := 2; sent <= registrationDailyLimit; sent++ {
time.Sleep(registrationMinInterval + 100*time.Millisecond)
requireAccepted(t, harness.resend(t, email))
assertRowCount(ctx, t, harness.pool, emailTokensTable, sent)
if active := harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NULL AND consumed_at IS NULL`); active != 1 {
t.Fatalf("after resend %d: %d unused tokens, want 1", sent, active)
}
}
// A resend keeps the credentials of the registration it resends for on
// its new token; every invalidated token keeps none.
if harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE pending_password_hash IS NOT NULL`) != 1 ||
harness.count(ctx, t, `SELECT count(*) FROM email_tokens WHERE invalidated_at IS NOT NULL AND pending_password_hash IS NOT NULL`) != 0 ||
harness.count(ctx, t, `SELECT count(*) FROM email_tokens AS token JOIN users ON users.id = token.user_id
WHERE token.invalidated_at IS NULL AND token.pending_password_hash = users.password_hash`) != 1 {
t.Fatal("resent tokens do not carry the pending credentials of the registration")
}
// Over the daily limit: 429 with a long wait and no new token.
time.Sleep(registrationMinInterval + 100*time.Millisecond)
capped := harness.resend(t, email)
requireProblemStatus(t, capped, http.StatusTooManyRequests, "rate_limited")
if wait, err := strconv.Atoi(capped.retryAfter); err != nil || wait <= int(registrationMinInterval/time.Second) {
t.Fatalf("Retry-After over the daily limit = %q, want the wait until the window ends", capped.retryAfter)
}
assertRowCount(ctx, t, harness.pool, emailTokensTable, registrationDailyLimit)
// Only the message of the last token is current; the others are
// cancelled by the worker, and the message goes through the fixture.
harness.drain(ctx, t)
sent := harness.fixture.Requests()[requests:]
if len(sent) != 1 || !slices.Equal(sent[0].To, []string{email}) {
t.Fatalf("fixture received %d messages, want exactly the one of the current token: %v", len(sent), sent)
}
var lastHash []byte
if err := harness.pool.QueryRow(ctx, `SELECT token_hash FROM email_tokens WHERE invalidated_at IS NULL`).Scan(&lastHash); err != nil {
t.Fatalf("read the current token: %v", err)
}
link := verificationLinkToken.FindStringSubmatch(sent[0].Text)
sum := sha256.Sum256([]byte(link[1]))
if link == nil || !bytes.Equal(sum[:], lastHash) {
t.Fatal("the delivered link is not the one of the current token")
}
if cancelled := harness.count(ctx, t, `SELECT count(*) FROM deliveries WHERE status = 'cancelled'`); cancelled != registrationDailyLimit-1 {
t.Fatalf("%d cancelled deliveries, want %d", cancelled, registrationDailyLimit-1)
}
harness.assertLogsHoldNoSecrets(t, "resend.candidate", link[1])
})
t.Run("resend answers an unknown and a verified address like an unverified one", func(t *testing.T) {
reset(t)
requireAccepted(t, harness.register(t, "pending@example.com", "candidate", ""))
requireAccepted(t, harness.register(t, "done@example.com", "candidate", ""))
harness.exec(ctx, t, `UPDATE users SET email_verified_at = $1 WHERE email_normalized = 'done@example.com'`, harness.clock.Now())
time.Sleep(registrationMinInterval + 100*time.Millisecond)
tokens := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`)
pending := harness.resend(t, "pending@example.com")
unknown := harness.resend(t, "nobody@example.com")
verified := harness.resend(t, "done@example.com")
requireAccepted(t, pending)
if unknown != pending || verified != pending {
t.Fatalf("answers differ: pending %+v, unknown %+v, verified %+v", pending, unknown, verified)
}
if got := harness.count(ctx, t, `SELECT count(*) FROM email_tokens`); got != tokens+1 {
t.Fatalf("%d tokens, want %d: only the unverified account gets one", got, tokens+1)
}
assertRowCount(ctx, t, harness.pool, usersTable, 2)
// The limit does not depend on the account either: a never
// registered address is refused on the same schedule.
for _, email := range []string{"pending@example.com", "nobody@example.com", "done@example.com"} {
response := harness.resend(t, email)
requireProblemStatus(t, response, http.StatusTooManyRequests, "rate_limited")
requireRetryWithinInterval(t, response)
}
})
t.Run("a validation error does not consume the limit", func(t *testing.T) {
reset(t)
bad := harness.registerBody(t, registrationBody("not-an-email", "candidate", registrationPassword, registrationC1), "")
requireProblemStatus(t, bad, http.StatusBadRequest, "validation_failed")
short := harness.registerBody(t, registrationBody("short.password@example.com", "candidate", "too short", registrationC1), "")
requireProblemStatus(t, short, http.StatusBadRequest, "validation_failed")
requireAccepted(t, harness.register(t, "short.password@example.com", "candidate", ""))
})
}
func TestRegistrationClientLimit(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout)
defer cancel()
harness := newRegistrationHarness(ctx, t, env, 2)
harness.truncate(ctx, t)
// The usecase counts a request with a client key against the per-client
// rule; the handler supplies the key from the resolved network address.
registration := harness.registration
for index, email := range []string{"client.one@example.com", "client.two@example.com", "client.three@example.com"} {
err := registration.Register(ctx, identity.RegisterCommand{
IdempotencyKey: "client-key-" + email, Email: email, Password: registrationPassword,
Scenario: "candidate", ConsentTextVersion: "c1-2026-10-01", ClientKey: "203.0.113.9",
})
var limited *identity.RateLimitedError
switch {
case index < 2 && err != nil:
t.Fatalf("registration %d error = %v, want accepted", index+1, err)
case index == 2 && !errors.As(err, &limited):
t.Fatalf("registration 3 error = %v, want *RateLimitedError", err)
}
}
assertRowCount(ctx, t, harness.pool, usersTable, 2)
}
@@ -411,7 +411,7 @@ func TestProfileSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -0,0 +1,120 @@
package httpadapter
import (
"context"
"errors"
"log/slog"
"net/http"
"testing"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/usecase/identity"
)
const resendPath = "/api/v1/identity/email-verification-requests"
// scriptedRegistration answers every call with its fixed error and records
// the last commands.
type scriptedRegistration struct {
err error
register identity.RegisterCommand
resend identity.ResendCommand
}
func (registration *scriptedRegistration) Register(_ context.Context, command identity.RegisterCommand) error {
registration.register = command
return registration.err
}
func (registration *scriptedRegistration) ResendVerification(_ context.Context, command identity.ResendCommand) error {
registration.resend = command
return registration.err
}
func newIdentityRouter(t *testing.T, registration v1.AccountRegistration) http.Handler {
t.Helper()
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
handler := v1.NewHandler(healthHandler, problem.NewResponder(logger), v1.WithIdentity(v1.NewIdentityHandler(registration)))
return newTestRouterWithAPI(t, healthHandler, handler, logger)
}
func TestRegistrationOperationsMapUsecaseOutcomes(t *testing.T) {
registerRequest := identityRequest{
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
}
resendRequest := identityRequest{method: http.MethodPost, path: resendPath, body: `{"email":"candidate@example.com"}`}
staleConsent := &identity.InvalidFieldError{Pointer: "/consent_c1/text_version", Err: errors.New("stale")}
for _, test := range []struct {
name string
request identityRequest
err error
statusCode int
code api.ProblemCode
pointer string
retryAfter string
}{
{name: "register accepted", request: registerRequest, statusCode: http.StatusAccepted},
{name: "resend accepted", request: resendRequest, statusCode: http.StatusAccepted},
{
name: "register stale consent version", request: registerRequest, err: staleConsent,
statusCode: http.StatusBadRequest, code: api.ProblemCodeValidationFailed, pointer: "/consent_c1/text_version",
},
{
name: "register reused key", request: registerRequest, err: identity.ErrIdempotencyKeyReused,
statusCode: http.StatusUnprocessableEntity, code: api.ProblemCodeIdempotencyKeyReused,
},
{
name: "register limited", request: registerRequest, err: &identity.RateLimitedError{RetryAfter: 1500 * time.Millisecond},
statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "2",
},
{
name: "resend limited", request: resendRequest, err: &identity.RateLimitedError{RetryAfter: 59 * time.Second},
statusCode: http.StatusTooManyRequests, code: api.ProblemCodeRateLimited, retryAfter: "59",
},
{
name: "resend internal failure", request: resendRequest, err: errors.New("database unavailable"),
statusCode: http.StatusInternalServerError, code: api.ProblemCodeInternal,
},
} {
t.Run(test.name, func(t *testing.T) {
response := serveIdentityRequest(t, newIdentityRouter(t, &scriptedRegistration{err: test.err}), test.request)
if test.statusCode == http.StatusAccepted {
if response.Code != http.StatusAccepted || response.Body.String() != `{"status":"accepted"}` {
t.Fatalf("response = %d %s, want the neutral 202", response.Code, response.Body.String())
}
return
}
body := requireProblem(t, response, test.statusCode, test.code)
if test.pointer != "" && (len(body.Errors) != 1 || body.Errors[0].Pointer != test.pointer) {
t.Fatalf("errors = %v, want one error at %s", body.Errors, test.pointer)
}
if got := response.Header().Get("Retry-After"); got != test.retryAfter {
t.Fatalf("Retry-After = %q, want %q", got, test.retryAfter)
}
})
}
}
func TestRegistrationPassesTheRequestToTheUsecase(t *testing.T) {
registration := &scriptedRegistration{}
router := newIdentityRouter(t, registration)
response := serveIdentityRequest(t, router, identityRequest{
method: http.MethodPost, path: registrationPath, body: registrationBody(validPassword, validConsent),
headers: map[string]string{"Idempotency-Key": testIdempotencyKey},
})
if response.Code != http.StatusAccepted {
t.Fatalf("status = %d: %s", response.Code, response.Body.String())
}
want := identity.RegisterCommand{
IdempotencyKey: testIdempotencyKey, Email: "candidate@example.com", Password: validPassword,
Scenario: "candidate", ConsentTextVersion: "c1-2026-10-01", ClientKey: "192.0.2.1",
}
if registration.register != want {
t.Fatalf("command = %+v, want %+v", registration.register, want)
}
}
@@ -27,7 +27,7 @@ func newMetricsTestRouter(t *testing.T, apiHandler func(*v1.HealthHandler, *prob
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
responder := problem.NewResponder(logger)
collector := metrics.New()
router, err := NewRouter(healthHandler, apiHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, collector, logger)
router, err := NewRouter(healthHandler, apiHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, collector, logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -73,8 +73,10 @@ func ClientIP(trusted []netip.Prefix) func(http.Handler) http.Handler {
// ClientAddr returns the client address that the ClientIP middleware stored.
// The second result is false when the middleware did not run or the peer
// address was not an IP address; a caller must then fail closed, for example
// by sharing one limiter bucket, instead of skipping its limit.
// address was not an IP address. A caller then skips its per-client limit
// and keeps its other limits: a shared "unknown" bucket would let one client
// lock out everyone, which is the worse failure than a missing per-client
// brake. The registration handler does this and counts nothing for it.
func ClientAddr(ctx context.Context) (netip.Addr, bool) {
addr, ok := ctx.Value(clientAddrKey{}).(netip.Addr)
return addr, ok && addr.IsValid()
@@ -275,7 +275,7 @@ func TestOrganizationSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -0,0 +1,22 @@
package problem
import (
"context"
"lincodex/backend/internal/adapter/primary/http/api"
)
// InvalidField is the validation_failed problem for one invalid value that
// only the application can detect, such as a stale consent text version. The
// pointer is a JSON Pointer into the location of the value; the body of the
// problem never echoes the value.
func InvalidField(ctx context.Context, location api.ProblemFieldLocation, pointer string) *api.ProblemStatusCode {
return validationProblem(ctx, []api.ProblemFieldError{fieldError(location, pointer, fieldCodeInvalid)})
}
// RateLimited is the 429 problem with the wait before a retry. The wait is
// rounded up to whole seconds, at least one.
func RateLimited(ctx context.Context, waitSeconds int32) *api.TooManyRequestsHeaders {
problem := New(ctx, api.ProblemCodeRateLimited)
return &api.TooManyRequestsHeaders{RetryAfter: api.NewOptInt32(max(waitSeconds, 1)), Response: problem.Response}
}
@@ -27,7 +27,7 @@ func TestRequestLogNamesTheRouteTemplateAndNoRequestData(t *testing.T) {
logger := slog.New(slog.NewJSONHandler(&logs, nil))
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
responder := problem.NewResponder(logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, responder), v1.NewDenyAllSecurity(), responder, metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -4,6 +4,7 @@ import (
"fmt"
"log/slog"
"net/http"
"net/netip"
"github.com/go-chi/chi/v5"
kitmiddleware "github.com/wahrwelt-kit/go-httpkit/httputil/middleware"
@@ -27,7 +28,8 @@ const (
// unknown routes under /api to 404, unsupported methods to 405, and any other
// server error or panic to 500 without exposing its text. Operation errors go
// through apiHandler.NewError. security decides every operation that requires
// a session; the generated server answers its rejection, and a request
// a session; trustedProxies are the reverse proxies whose X-Forwarded-For
// is believed; the generated server answers its rejection, and a request
// without the session cookie, with 401 unauthenticated through NewError.
func NewRouter(
health *v1.HealthHandler,
@@ -36,6 +38,7 @@ func NewRouter(
problems *problem.Responder,
collector httpmiddleware.RequestMetrics,
logger *slog.Logger,
trustedProxies []netip.Prefix,
) (http.Handler, error) {
apiServer, err := apiadapter.NewServer(
apiHandler,
@@ -55,6 +58,9 @@ func NewRouter(
// same route template as the metrics, never the raw path or query.
resolveRoute := operationRoute(apiServer)
router.Use(kitmiddleware.RequestID())
// The client address is resolved once, through the trusted proxies only,
// for the per-client rate limits of the handlers.
router.Use(httpmiddleware.ClientIP(trustedProxies))
router.Use(httpmiddleware.RequestLog(logger, resolveRoute, healthPath, readinessPath))
router.Use(httpmiddleware.CollectMetrics(collector, resolveRoute))
router.Group(func(operational chi.Router) {
@@ -393,7 +393,7 @@ func TestGeneratedServerSecurityOrder(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
security := &recordingSecurity{}
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), security, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -503,7 +503,7 @@ func TestQuestionnaireSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -715,7 +715,7 @@ func TestAssessmentSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -1010,7 +1010,7 @@ func TestNeedSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -1337,7 +1337,7 @@ func TestSupportCaseSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -1803,7 +1803,7 @@ func TestInvitationSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -1910,7 +1910,7 @@ func TestConsentSchemaValidationPrecedesImplementation(t *testing.T) {
t.Run(test.name, func(t *testing.T) {
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, v1.NewHandler(healthHandler, problem.NewResponder(logger)), &recordingSecurity{}, problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -2021,7 +2021,7 @@ func TestPublicOperationPanicReturnsInternalProblem(t *testing.T) {
getHealthz: func(context.Context) (*api.HealthResponse, error) { panic(panicText) },
}
recorder := &requestRecorder{}
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger)
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), recorder, logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -2198,7 +2198,7 @@ func newTestHealthHandler(checker readinessFunc) *v1.HealthHandler {
func newTestRouterWithAPI(t *testing.T, healthHandler *v1.HealthHandler, apiHandler api.Handler, logger *slog.Logger) http.Handler {
t.Helper()
router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger)
router, err := NewRouter(healthHandler, apiHandler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), metrics.New(), logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -2210,7 +2210,7 @@ func newOverrideRouterWithMetrics(t *testing.T, collector *requestRecorder, getH
logger := slog.New(slog.DiscardHandler)
healthHandler := newTestHealthHandler(func(context.Context) error { return nil })
handler := healthzOverride{Handler: v1.NewHandler(healthHandler, problem.NewResponder(logger)), getHealthz: getHealthz}
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger)
router, err := NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), problem.NewResponder(logger), collector, logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -32,19 +32,55 @@ type Handler struct {
api.UnimplementedHandler
health *HealthHandler
identity *IdentityHandler
problems *problem.Responder
}
var _ api.Handler = (*Handler)(nil)
func NewHandler(health *HealthHandler, problems *problem.Responder) *Handler {
return &Handler{health: health, problems: problems}
// HandlerOption adds the handler of a business area to Handler.
type HandlerOption func(*Handler)
// WithIdentity serves the registration operations. A nil handler leaves them
// to the embedded api.UnimplementedHandler, as when no database is
// configured.
func WithIdentity(identity *IdentityHandler) HandlerOption {
return func(handler *Handler) { handler.identity = identity }
}
func NewHandler(health *HealthHandler, problems *problem.Responder, options ...HandlerOption) *Handler {
handler := &Handler{health: health, problems: problems}
for _, option := range options {
option(handler)
}
return handler
}
func (handler *Handler) GetHealthz(ctx context.Context) (*api.HealthResponse, error) {
return handler.health.GetHealthz(ctx)
}
func (handler *Handler) RegisterAccount(
ctx context.Context,
request *api.RegistrationRequest,
params api.RegisterAccountParams,
) (api.RegisterAccountRes, error) {
if handler.identity == nil {
return handler.UnimplementedHandler.RegisterAccount(ctx, request, params)
}
return handler.identity.RegisterAccount(ctx, request, params)
}
func (handler *Handler) ResendEmailVerification(
ctx context.Context,
request *api.EmailVerificationResendRequest,
) (api.ResendEmailVerificationRes, error) {
if handler.identity == nil {
return handler.UnimplementedHandler.ResendEmailVerification(ctx, request)
}
return handler.identity.ResendEmailVerification(ctx, request)
}
// NewError implements api.Handler for errors returned by operations.
func (handler *Handler) NewError(ctx context.Context, err error) *api.ProblemStatusCode {
return handler.problems.HandlerError(ctx, err)
@@ -0,0 +1,119 @@
package v1
import (
"context"
"errors"
"math"
"time"
"lincodex/backend/internal/adapter/primary/http/api"
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
"lincodex/backend/internal/adapter/primary/http/problem"
"lincodex/backend/internal/usecase/identity"
)
// AccountRegistration is what IdentityHandler needs from the registration
// usecase.
type AccountRegistration interface {
Register(ctx context.Context, command identity.RegisterCommand) error
ResendVerification(ctx context.Context, command identity.ResendCommand) error
}
// IdentityHandler serves the anonymous registration operations. Both answer
// the same neutral 202 whatever the state of the address; see the contract.
type IdentityHandler struct {
registration AccountRegistration
}
func NewIdentityHandler(registration AccountRegistration) *IdentityHandler {
return &IdentityHandler{registration: registration}
}
func (handler *IdentityHandler) RegisterAccount(
ctx context.Context,
request *api.RegistrationRequest,
params api.RegisterAccountParams,
) (api.RegisterAccountRes, error) {
err := handler.registration.Register(ctx, identity.RegisterCommand{
IdempotencyKey: params.IdempotencyKey,
Email: string(request.Email),
Password: string(request.Password),
Scenario: string(request.Scenario),
ConsentTextVersion: string(request.ConsentC1.TextVersion),
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return accepted(), nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.RegisterAccountBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
case errors.Is(err, identity.ErrIdempotencyKeyReused):
return (*api.RegisterAccountUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func (handler *IdentityHandler) ResendEmailVerification(
ctx context.Context,
request *api.EmailVerificationResendRequest,
) (api.ResendEmailVerificationRes, error) {
err := handler.registration.ResendVerification(ctx, identity.ResendCommand{
Email: string(request.Email),
ClientKey: clientKey(ctx),
})
switch {
case err == nil:
return accepted(), nil
case errors.Is(err, identity.ErrInvalidField):
return (*api.ResendEmailVerificationBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
}
if limited, ok := rateLimited(ctx, err); ok {
return limited, nil
}
return nil, err
}
func accepted() *api.IdentityRequestAccepted {
return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted}
}
// clientKey is the limiter key of the client network address that the
// ClientIP middleware resolved. Without it, for example when the middleware
// is not mounted, the per-client limit is skipped and only the per-address
// limits apply: a shared bucket would let one client lock everyone out.
func clientKey(ctx context.Context) string {
address, ok := httpmiddleware.ClientAddr(ctx)
if !ok {
return ""
}
return httpmiddleware.LimiterKey(address)
}
func invalidFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode {
field, ok := errors.AsType[*identity.InvalidFieldError](err)
if !ok {
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
}
location := api.ProblemFieldLocationBody
if field.Pointer == "/Idempotency-Key" {
location = api.ProblemFieldLocationHeader
}
return problem.InvalidField(ctx, location, field.Pointer)
}
func rateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
limited, ok := errors.AsType[*identity.RateLimitedError](err)
if !ok {
return nil, false
}
return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), true
}
// wholeSeconds rounds a wait up, so a client that waits the stated time is
// not refused again for the remainder.
func wholeSeconds(wait time.Duration) int32 {
return int32(min(math.Ceil(wait.Seconds()), math.MaxInt32))
}
@@ -0,0 +1,107 @@
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
"lincodex/backend/internal/port/outbound"
)
type idempotencyRepository struct {
queries *sqlc.Queries
}
func (repository idempotencyRepository) Reserve(
ctx context.Context,
record outbound.IdempotencyRecord,
) (outbound.IdempotencyRecord, bool, error) {
const location = "idempotencyRepository.Reserve"
if err := requireTime(location, record.CreatedAt, outbound.ErrIdempotencyRecordNotFound); err != nil {
return outbound.IdempotencyRecord{}, false, err
}
if !record.ExpiresAt.After(record.CreatedAt) {
return outbound.IdempotencyRecord{}, false, errors.New(location + " - expiry must be after creation")
}
row, err := repository.queries.ReserveIdempotencyRecord(ctx, sqlc.ReserveIdempotencyRecordParams{
ScopeHash: record.Scope[:],
Fingerprint: record.Fingerprint[:],
CreatedAt: pgTime(record.CreatedAt),
ExpiresAt: pgTime(record.ExpiresAt),
})
if err == nil {
return idempotencyFromRow(location, row.ScopeHash, row.Fingerprint, row.CreatedAt.Time, row.ExpiresAt.Time, true)
}
if !isNoRows(err) {
return outbound.IdempotencyRecord{}, false, fmt.Errorf("%s - store record: %w", location, mapIdentityError(err))
}
// A live record with the scope exists and was left as it is. It is
// visible now: a concurrent writer committed before this statement
// returned.
existing, err := repository.Find(ctx, record.Scope, record.CreatedAt)
if err != nil {
return outbound.IdempotencyRecord{}, false, fmt.Errorf("%s - read live record: %w", location, err)
}
return existing, false, nil
}
func (repository idempotencyRepository) Find(
ctx context.Context,
scope [outbound.IdempotencyDigestSize]byte,
at time.Time,
) (outbound.IdempotencyRecord, error) {
const location = "idempotencyRepository.Find"
if err := requireTime(location, at, outbound.ErrIdempotencyRecordNotFound); err != nil {
return outbound.IdempotencyRecord{}, err
}
row, err := repository.queries.GetLiveIdempotencyRecord(ctx, sqlc.GetLiveIdempotencyRecordParams{
ScopeHash: scope[:],
At: pgTime(at),
})
if err != nil {
return outbound.IdempotencyRecord{}, fmt.Errorf("%s - select record: %w", location, mapNoRows(err, outbound.ErrIdempotencyRecordNotFound))
}
record, _, err := idempotencyFromRow(location, row.ScopeHash, row.Fingerprint, row.CreatedAt.Time, row.ExpiresAt.Time, false)
return record, err
}
func (repository idempotencyRepository) PurgeExpired(ctx context.Context, at time.Time, limit int32) (int64, error) {
const location = "idempotencyRepository.PurgeExpired"
if err := requireTime(location, at, outbound.ErrIdempotencyRecordNotFound); err != nil {
return 0, err
}
if limit <= 0 {
return 0, errors.New(location + " - limit must be positive")
}
deleted, err := repository.queries.PurgeExpiredIdempotencyRecords(ctx, sqlc.PurgeExpiredIdempotencyRecordsParams{
At: pgTime(at),
BatchLimit: limit,
})
if err != nil {
return 0, fmt.Errorf("%s - delete records: %w", location, mapIdentityError(err))
}
return deleted, nil
}
func idempotencyFromRow(
location string,
scope, fingerprint []byte,
createdAt, expiresAt time.Time,
created bool,
) (outbound.IdempotencyRecord, bool, error) {
record := outbound.IdempotencyRecord{CreatedAt: createdAt, ExpiresAt: expiresAt}
if len(scope) != outbound.IdempotencyDigestSize || len(fingerprint) != outbound.IdempotencyDigestSize {
return outbound.IdempotencyRecord{}, false, errors.New(location + " - stored digest has an unexpected size")
}
copy(record.Scope[:], scope)
copy(record.Fingerprint[:], fingerprint)
return record, created, nil
}
func isNoRows(err error) bool {
return errors.Is(err, pgx.ErrNoRows)
}
@@ -97,6 +97,14 @@ func (store *IdentityStore) Sessions() outbound.SessionRepository {
return sessionRepository{queries: store.queries}
}
func (store *IdentityStore) IdempotencyRecords() outbound.IdempotencyRepository {
return idempotencyRepository{queries: store.queries}
}
func (unit *UnitOfWork) IdempotencyRecords() outbound.IdempotencyRepository {
return idempotencyRepository{queries: unit.queries}
}
func (unit *UnitOfWork) Users() outbound.UserRepository {
return userRepository{queries: unit.queries}
}
@@ -226,6 +234,26 @@ func (repository userRepository) UpdateRegistration(ctx context.Context, user do
return userFromRow(sqlc.User(row))
}
func (repository userRepository) AdvanceRegistration(
ctx context.Context,
id uuid.UUID,
expectedVersion int64,
at time.Time,
) (domain.User, error) {
if err := requireTime("userRepository.AdvanceRegistration", at, domain.ErrInvalidUser); err != nil {
return domain.User{}, err
}
row, err := repository.queries.AdvanceUserRegistration(ctx, sqlc.AdvanceUserRegistrationParams{
ID: pgUUID(id),
ExpectedVersion: expectedVersion,
RegisteredAt: pgTime(at),
})
if err != nil {
return domain.User{}, fmt.Errorf("userRepository.AdvanceRegistration - update user: %w", mapNoRows(err, outbound.ErrUserVersionConflict))
}
return userFromRow(sqlc.User(row))
}
func (repository userRepository) MarkEmailVerified(
ctx context.Context,
id uuid.UUID,
@@ -318,7 +346,7 @@ func (repository emailTokenRepository) Insert(ctx context.Context, token domain.
if token.ID == uuid.Nil || token.TokenHash.IsZero() {
return fmt.Errorf("emailTokenRepository.Insert - token was not built by domain.NewEmailToken: %w", domain.ErrInvalidEmailToken)
}
err := repository.queries.InsertEmailToken(ctx, sqlc.InsertEmailTokenParams{
params := sqlc.InsertEmailTokenParams{
ID: pgUUID(token.ID),
UserID: pgUUID(token.UserID),
Purpose: string(token.Purpose),
@@ -326,13 +354,62 @@ func (repository emailTokenRepository) Insert(ctx context.Context, token domain.
RegistrationVersion: token.RegistrationVersion,
CreatedAt: pgTime(token.CreatedAt),
ExpiresAt: pgTime(token.ExpiresAt),
})
if err != nil {
}
if pending := token.Pending; pending != nil {
params.PendingPasswordHash = pgtype.Text{String: pending.PasswordHash.PHC(), Valid: true}
params.PendingScenario = pgtype.Text{String: string(pending.Scenario), Valid: true}
params.PendingOnboardingStep = pgtype.Text{String: string(pending.OnboardingStep), Valid: true}
}
if err := repository.queries.InsertEmailToken(ctx, params); err != nil {
return fmt.Errorf("emailTokenRepository.Insert - insert email token: %w", mapIdentityError(err))
}
return nil
}
func (repository emailTokenRepository) LatestPending(
ctx context.Context,
userID uuid.UUID,
registrationVersion int64,
) (domain.PendingRegistration, bool, error) {
row, err := repository.queries.GetLatestPendingRegistration(ctx, sqlc.GetLatestPendingRegistrationParams{
UserID: pgUUID(userID),
Purpose: string(domain.EmailTokenPurposeEmailVerification),
RegistrationVersion: registrationVersion,
})
if errors.Is(err, pgx.ErrNoRows) {
return domain.PendingRegistration{}, false, nil
}
if err != nil {
return domain.PendingRegistration{}, false, fmt.Errorf("emailTokenRepository.LatestPending - select pending registration: %w", mapIdentityError(err))
}
pending, err := pendingFromColumns(row.PendingPasswordHash, row.PendingScenario, row.PendingOnboardingStep)
if err != nil {
return domain.PendingRegistration{}, false, err
}
return *pending, true, nil
}
// pendingFromColumns decodes the pending credentials of a token row; nil when
// the token carries none.
func pendingFromColumns(hash, scenario, step pgtype.Text) (*domain.PendingRegistration, error) {
if !hash.Valid {
return nil, nil
}
passwordHash, err := domain.NewPasswordHash(hash.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode password hash: %w", err)
}
parsedScenario, err := domain.ParseScenario(scenario.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode scenario: %w", err)
}
parsedStep, err := domain.ParseOnboardingStep(step.String)
if err != nil {
return nil, fmt.Errorf("postgres.pendingFromColumns - decode onboarding step: %w", err)
}
return &domain.PendingRegistration{PasswordHash: passwordHash, Scenario: parsedScenario, OnboardingStep: parsedStep}, nil
}
func (repository emailTokenRepository) InvalidateActive(
ctx context.Context,
userID uuid.UUID,
@@ -416,7 +493,12 @@ func emailTokenFromRow(row sqlc.EmailToken) (domain.EmailToken, error) {
if err != nil {
return domain.EmailToken{}, err
}
pending, err := pendingFromColumns(row.PendingPasswordHash, row.PendingScenario, row.PendingOnboardingStep)
if err != nil {
return domain.EmailToken{}, err
}
return domain.EmailToken{
Pending: pending,
ID: uuid.UUID(row.ID.Bytes),
UserID: uuid.UUID(row.UserID.Bytes),
Purpose: purpose,
@@ -11,6 +11,104 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
const advanceUserRegistration = `-- name: AdvanceUserRegistration :one
WITH updated AS (
UPDATE users
SET
registration_version = registration_version + 1,
last_registered_at = $1,
updated_at = $1,
version = version + 1
WHERE
users.id = $2
AND users.version = $3
AND users.email_verified_at IS NULL
RETURNING
users.id,
users.email,
users.email_normalized,
users.password_hash,
users.scenario,
users.onboarding_step,
users.email_verified_at,
users.registration_version,
users.last_registered_at,
users.version,
users.created_at,
users.updated_at
),
discarded_consent AS (
DELETE FROM consent_records
USING updated
WHERE
consent_records.subject_id = updated.id
AND consent_records.purpose = 'c1'
AND consent_records.source = 'registration'
)
SELECT
updated.id,
updated.email,
updated.email_normalized,
updated.password_hash,
updated.scenario,
updated.onboarding_step,
updated.email_verified_at,
updated.registration_version,
updated.last_registered_at,
updated.version,
updated.created_at,
updated.updated_at
FROM updated
`
type AdvanceUserRegistrationParams struct {
RegisteredAt pgtype.Timestamptz
ID pgtype.UUID
ExpectedVersion int64
}
type AdvanceUserRegistrationRow struct {
ID pgtype.UUID
Email string
EmailNormalized string
PasswordHash string
Scenario string
OnboardingStep string
EmailVerifiedAt pgtype.Timestamptz
RegistrationVersion int64
LastRegisteredAt pgtype.Timestamptz
Version int64
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
// ends every earlier token, and deletes the registration C1 of the earlier
// registrant like UpdateUserRegistration does.
func (q *Queries) AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error) {
row := q.db.QueryRow(ctx, advanceUserRegistration, arg.RegisteredAt, arg.ID, arg.ExpectedVersion)
var i AdvanceUserRegistrationRow
err := row.Scan(
&i.ID,
&i.Email,
&i.EmailNormalized,
&i.PasswordHash,
&i.Scenario,
&i.OnboardingStep,
&i.EmailVerifiedAt,
&i.RegistrationVersion,
&i.LastRegisteredAt,
&i.Version,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const consumeEmailToken = `-- name: ConsumeEmailToken :one
UPDATE email_tokens AS token
SET consumed_at = $1
@@ -32,7 +130,10 @@ RETURNING
token.created_at,
token.expires_at,
token.consumed_at,
token.invalidated_at
token.invalidated_at,
token.pending_password_hash,
token.pending_scenario,
token.pending_onboarding_step
`
type ConsumeEmailTokenParams struct {
@@ -63,6 +164,9 @@ func (q *Queries) ConsumeEmailToken(ctx context.Context, arg ConsumeEmailTokenPa
&i.ExpiresAt,
&i.ConsumedAt,
&i.InvalidatedAt,
&i.PendingPasswordHash,
&i.PendingScenario,
&i.PendingOnboardingStep,
)
return i, err
}
@@ -273,6 +377,71 @@ func (q *Queries) GetEmailTokenState(ctx context.Context, arg GetEmailTokenState
return i, err
}
const getLatestPendingRegistration = `-- name: GetLatestPendingRegistration :one
SELECT
pending_password_hash,
pending_scenario,
pending_onboarding_step
FROM email_tokens
WHERE
user_id = $1
AND purpose = $2
AND registration_version = $3
AND pending_password_hash IS NOT NULL
ORDER BY created_at DESC, id DESC
LIMIT 1
`
type GetLatestPendingRegistrationParams struct {
UserID pgtype.UUID
Purpose string
RegistrationVersion int64
}
type GetLatestPendingRegistrationRow struct {
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
// The pending credentials of the newest token of a registration, for a
// resend, which issues its token with the same credentials.
func (q *Queries) GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error) {
row := q.db.QueryRow(ctx, getLatestPendingRegistration, arg.UserID, arg.Purpose, arg.RegistrationVersion)
var i GetLatestPendingRegistrationRow
err := row.Scan(&i.PendingPasswordHash, &i.PendingScenario, &i.PendingOnboardingStep)
return i, err
}
const getLiveIdempotencyRecord = `-- name: GetLiveIdempotencyRecord :one
SELECT
scope_hash,
fingerprint,
created_at,
expires_at
FROM idempotency_records
WHERE
scope_hash = $1
AND expires_at > $2
`
type GetLiveIdempotencyRecordParams struct {
ScopeHash []byte
At pgtype.Timestamptz
}
func (q *Queries) GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error) {
row := q.db.QueryRow(ctx, getLiveIdempotencyRecord, arg.ScopeHash, arg.At)
var i IdempotencyRecord
err := row.Scan(
&i.ScopeHash,
&i.Fingerprint,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
const getUserByEmailNormalized = `-- name: GetUserByEmailNormalized :one
SELECT
id,
@@ -357,7 +526,10 @@ INSERT INTO email_tokens (
token_hash,
registration_version,
created_at,
expires_at
expires_at,
pending_password_hash,
pending_scenario,
pending_onboarding_step
) VALUES (
$1,
$2,
@@ -365,18 +537,24 @@ INSERT INTO email_tokens (
$4,
$5,
$6,
$7
$7,
$8,
$9,
$10
)
`
type InsertEmailTokenParams struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenParams) error {
@@ -388,6 +566,9 @@ func (q *Queries) InsertEmailToken(ctx context.Context, arg InsertEmailTokenPara
arg.RegistrationVersion,
arg.CreatedAt,
arg.ExpiresAt,
arg.PendingPasswordHash,
arg.PendingScenario,
arg.PendingOnboardingStep,
)
return err
}
@@ -496,7 +677,12 @@ func (q *Queries) InsertUser(ctx context.Context, arg InsertUserParams) error {
const invalidateActiveEmailTokens = `-- name: InvalidateActiveEmailTokens :execrows
UPDATE email_tokens
SET invalidated_at = $1
SET
invalidated_at = $1,
-- An invalidated token keeps no password hash: it can never be confirmed.
pending_password_hash = NULL,
pending_scenario = NULL,
pending_onboarding_step = NULL
WHERE
user_id = $2
AND purpose = $3
@@ -571,6 +757,83 @@ func (q *Queries) MarkUserEmailVerified(ctx context.Context, arg MarkUserEmailVe
return i, err
}
const purgeExpiredIdempotencyRecords = `-- name: PurgeExpiredIdempotencyRecords :execrows
DELETE FROM idempotency_records
WHERE scope_hash IN (
SELECT stale.scope_hash
FROM idempotency_records AS stale
WHERE stale.expires_at <= $1
ORDER BY stale.expires_at
LIMIT $2
FOR UPDATE SKIP LOCKED
)
`
type PurgeExpiredIdempotencyRecordsParams struct {
At pgtype.Timestamptz
BatchLimit int32
}
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
func (q *Queries) PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error) {
result, err := q.db.Exec(ctx, purgeExpiredIdempotencyRecords, arg.At, arg.BatchLimit)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const reserveIdempotencyRecord = `-- name: ReserveIdempotencyRecord :one
INSERT INTO idempotency_records (
scope_hash,
fingerprint,
created_at,
expires_at
) VALUES (
$1,
$2,
$3,
$4
)
ON CONFLICT (scope_hash) DO UPDATE
SET
fingerprint = excluded.fingerprint,
created_at = excluded.created_at,
expires_at = excluded.expires_at
WHERE idempotency_records.expires_at <= excluded.created_at
RETURNING scope_hash, fingerprint, created_at, expires_at
`
type ReserveIdempotencyRecordParams struct {
ScopeHash []byte
Fingerprint []byte
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
}
// Stores the replay record of a command. A record whose retention has passed
// is replaced, so the key is accepted as new after the retention. A live
// record is left as it is and nothing is returned; the caller then reads it
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
// on the row of the first one until its transaction ends.
func (q *Queries) ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error) {
row := q.db.QueryRow(ctx, reserveIdempotencyRecord,
arg.ScopeHash,
arg.Fingerprint,
arg.CreatedAt,
arg.ExpiresAt,
)
var i IdempotencyRecord
err := row.Scan(
&i.ScopeHash,
&i.Fingerprint,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
const revokeSession = `-- name: RevokeSession :execrows
UPDATE sessions
SET revoked_at = $1
@@ -163,15 +163,25 @@ type DeliveryAttempt struct {
}
type EmailToken struct {
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
ID pgtype.UUID
UserID pgtype.UUID
Purpose string
TokenHash []byte
RegistrationVersion int64
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
ConsumedAt pgtype.Timestamptz
InvalidatedAt pgtype.Timestamptz
PendingPasswordHash pgtype.Text
PendingScenario pgtype.Text
PendingOnboardingStep pgtype.Text
}
type IdempotencyRecord struct {
ScopeHash []byte
Fingerprint []byte
CreatedAt pgtype.Timestamptz
ExpiresAt pgtype.Timestamptz
}
type MailQuotaReservation struct {
@@ -22,6 +22,12 @@ type Querier interface {
// returns for a stale version or for an account without a profile, which the
// caller answers as a version conflict.
AdvanceCandidateProfileVersion(ctx context.Context, arg AdvanceCandidateProfileVersionParams) (CandidateProfile, error)
// Starts a new registration of an unverified account without touching its
// credentials, scenario, or onboarding step: the new registration carries
// them on its verification token. Advances the registration version, which
// ends every earlier token, and deletes the registration C1 of the earlier
// registrant like UpdateUserRegistration does.
AdvanceUserRegistration(ctx context.Context, arg AdvanceUserRegistrationParams) (AdvanceUserRegistrationRow, error)
// Cancels a job that has not finished. A job whose handler transaction is
// in progress holds its row lock, so the statement waits for it: after the
// handler committed the job is done and nothing is canceled; otherwise the
@@ -163,7 +169,11 @@ type Querier interface {
// for the account's own view of its mail. It selects no address and no
// content. The recipient index narrows the scan to the account's rows.
GetLatestDeliveryStatus(ctx context.Context, arg GetLatestDeliveryStatusParams) (GetLatestDeliveryStatusRow, error)
// The pending credentials of the newest token of a registration, for a
// resend, which issues its token with the same credentials.
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
// Reads the usage of the day and the month window without locking.
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
// Reads the membership of one account in one organization, in any state.
@@ -366,6 +376,9 @@ type Querier interface {
// the publication time set by the guard trigger. No row means the version
// was not a draft any more.
PublishAssessmentFamily(ctx context.Context, arg PublishAssessmentFamilyParams) (AssessmentFamily, error)
// Deletes at most batch_limit expired records. Locked rows are skipped, so
// the statement never waits for a concurrent reservation.
PurgeExpiredIdempotencyRecords(ctx context.Context, arg PurgeExpiredIdempotencyRecordsParams) (int64, error)
// Reads the profile row of an account together with every claim in one
// statement, so the version and the claims come from one snapshot: a save that
// commits between two separate reads could pair version N with the claims of
@@ -419,6 +432,12 @@ type Querier interface {
// the job did not cause the failure. The same guard as the completion
// applies, one (id, attempt) pair per job. It returns the IDs it released.
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
// Stores the replay record of a command. A record whose retention has passed
// is replaced, so the key is accepted as new after the retention. A live
// record is left as it is and nothing is returned; the caller then reads it
// with GetLiveIdempotencyRecord. Concurrent callers with the same scope wait
// on the row of the first one until its transaction ends.
ReserveIdempotencyRecord(ctx context.Context, arg ReserveIdempotencyRecordParams) (IdempotencyRecord, error)
RetireAssessmentFamily(ctx context.Context, arg RetireAssessmentFamilyParams) (AssessmentFamily, error)
// Revokes every unrevoked record of a purpose other than C4, superseded ones
// included, and returns them. A revocation time before the grant time, from
@@ -39,6 +39,10 @@ type mailMetrics struct {
// senderCancelled counts deliveries that the sending worker ended without
// sending, by cancel reason, a closed set from the domain.
senderCancelled *client.CounterVec
// identityRateLimited counts registration and resend requests that the
// identity limiter refused, by scope: address or client. No address,
// email, or key is ever a label.
identityRateLimited *client.CounterVec
}
// deliveryKinds and deliveryStatuses list the series that always exist, so a
@@ -89,6 +93,10 @@ func newMailMetrics() mailMetrics {
Name: "lincodex_mail_sender_cancelled_total",
Help: "Deliveries that the mail sending worker of this process ended without sending, by cancel reason. content_invalid and processing_failed mean a broken row or a defect.",
}, []string{"reason"}),
identityRateLimited: client.NewCounterVec(client.CounterOpts{
Name: "lincodex_identity_rate_limit_refusals_total",
Help: "Registration and verification resend requests refused with 429 by the identity limiter, by scope: address (per email address) or client (per network address). A large share of client refusals hints at a broken proxy chain, where many clients share one address; a rise of address refusals can mean a targeted lockout of one address.",
}, []string{"scope"}),
senderRunning: client.NewGauge(client.GaugeOpts{
Name: "lincodex_mail_sender_running",
Help: "1 while the mail sending loop of this process runs, 0 while it does not, for example with EMAIL_PROVIDER=disabled or after shutdown began.",
@@ -99,14 +107,32 @@ func newMailMetrics() mailMetrics {
for _, reason := range domain.DeliveryCancelReasons() {
metrics.senderCancelled.WithLabelValues(string(reason))
}
for _, scope := range []string{IdentityScopeAddress, IdentityScopeClient} {
metrics.identityRateLimited.WithLabelValues(scope)
}
return metrics
}
// The scopes of the identity rate limit refusal counter.
const (
IdentityScopeAddress = "address"
IdentityScopeClient = "client"
)
// ObserveIdentityRateLimited counts one refused identity request. A scope
// outside the two known ones counts as address, so the label stays bounded.
func (metrics *Metrics) ObserveIdentityRateLimited(scope string) {
if scope != IdentityScopeClient {
scope = IdentityScopeAddress
}
metrics.mail.identityRateLimited.WithLabelValues(scope).Inc()
}
func (mail mailMetrics) collectors() []client.Collector {
return []client.Collector{
mail.deliveries, mail.oldestDuePendingAge, mail.lastSuccess,
mail.quotaUsed, mail.quotaLimit, mail.quotaProviderExhausted,
mail.senderRunning, mail.senderCancelled,
mail.senderRunning, mail.senderCancelled, mail.identityRateLimited,
}
}
@@ -39,3 +39,16 @@ func TestMetricsHandlerCountsCancelledMailByABoundedReason(t *testing.T) {
t.Fatal("an arbitrary reason became a label")
}
}
func TestIdentityRateLimitRefusalsAreCountedByBoundedScope(t *testing.T) {
metrics := New()
metrics.ObserveIdentityRateLimited(IdentityScopeClient)
metrics.ObserveIdentityRateLimited(IdentityScopeAddress)
metrics.ObserveIdentityRateLimited("203.0.113.9")
body := scrape(t, metrics)
requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="client"} 1`)
requireSeries(t, body, `lincodex_identity_rate_limit_refusals_total{scope="address"} 2`)
if strings.Contains(body, "203.0.113.9") {
t.Fatal("an unknown scope became a label value")
}
}
@@ -0,0 +1,86 @@
package redis
import (
"context"
"fmt"
"strconv"
"time"
"github.com/redis/go-redis/v9"
"lincodex/backend/internal/port/outbound"
)
// takeScript counts one request against every rule atomically. KEYS holds one
// counter per rule and ARGV holds the limit and the window in milliseconds of
// each rule, in the same order. It returns 0 when the request was counted and
// otherwise the milliseconds until every refusing rule admits it again; a
// refused request changes nothing, so it does not extend a window. A counter
// without an expiry, which a crash outside this script could never leave,
// still gets one, and a counter with 0 ms left counts as 1 ms, so a refusal
// never reports a zero wait.
var takeScript = redis.NewScript(`
local retry = 0
for index, key in ipairs(KEYS) do
local limit = tonumber(ARGV[2 * index - 1])
local window = tonumber(ARGV[2 * index])
local used = tonumber(redis.call('GET', key) or '0')
if used >= limit then
local remaining = redis.call('PTTL', key)
if remaining < 0 then
redis.call('PEXPIRE', key, window)
remaining = window
elseif remaining == 0 then
remaining = 1
end
if remaining > retry then
retry = remaining
end
end
end
if retry > 0 then
return retry
end
for index, key in ipairs(KEYS) do
local count = redis.call('INCR', key)
if count == 1 or redis.call('PTTL', key) < 0 then
redis.call('PEXPIRE', key, ARGV[2 * index])
end
end
return 0
`)
const rateLimitKeyPrefix = "ratelimit:"
var _ outbound.RateLimiter = (*Cache)(nil)
// Take implements outbound.RateLimiter with one fixed-window counter per
// rule, named by the key and the window length, so two rules of one key never
// share a counter.
func (cache *Cache) Take(ctx context.Context, key string, rules ...outbound.RateLimitRule) (outbound.RateLimitDecision, error) {
if key == "" || len(rules) == 0 {
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - key and at least one rule are required: %w", outbound.ErrInvalidRateLimitRule)
}
keys := make([]string, 0, len(rules))
arguments := make([]any, 0, 2*len(rules))
for _, rule := range rules {
if rule.Limit <= 0 || rule.Window < time.Millisecond {
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - limit must be positive and window at least 1ms: %w", outbound.ErrInvalidRateLimitRule)
}
windowMillis := rule.Window.Milliseconds()
// The key is a hash tag, so every counter of one caller maps to one
// cluster slot, as a multi-key script needs.
keys = append(keys, rateLimitKeyPrefix+"{"+key+"}:"+strconv.FormatInt(windowMillis, 10))
arguments = append(arguments, rule.Limit, windowMillis)
}
ctx, cancel := context.WithTimeout(ctx, cache.timeout)
defer cancel()
retryMillis, err := takeScript.Run(ctx, cache.client, keys, arguments...).Int64()
if err != nil {
return outbound.RateLimitDecision{}, fmt.Errorf("Cache.Take - run script: %w", err)
}
if retryMillis == 0 {
return outbound.RateLimitDecision{Allowed: true}, nil
}
return outbound.RateLimitDecision{RetryAfter: time.Duration(retryMillis) * time.Millisecond}, nil
}
@@ -33,6 +33,7 @@ func consumerTestConfig(t *testing.T) config.Config {
settings, err := config.LoadFromEnv(func(key string) (string, bool) {
value, ok := map[string]string{
"SEAWEEDFS_ACCESS_KEY": "test-access",
"IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab",
"SEAWEEDFS_SECRET_KEY": "test-secret",
"EMAIL_PROVIDER": "disabled",
"EMAIL_FROM": "no-reply@example.com",
+119
View File
@@ -0,0 +1,119 @@
package bootstrap
import (
"context"
"crypto/rand"
"fmt"
"log/slog"
"net/netip"
"time"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/primary/http/problem"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
"lincodex/backend/internal/adapter/secondary/argon2id"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
redisadapter "lincodex/backend/internal/adapter/secondary/redis"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/identity"
"lincodex/backend/internal/usecase/notification"
"lincodex/backend/internal/usecase/notification/mailtemplate"
)
// identityPoolMaxConns bounds the connections of the registration requests:
// each holds one for a short transaction, after the password hash is done.
const identityPoolMaxConns = 8
// newTrustedProxies hands the configured reverse proxies to the router.
func newTrustedProxies(settings config.Config) []netip.Prefix { return settings.TrustedProxyCIDRs }
// newAPIHandler composes the handler of the public API from the business
// areas that are built. An area without a handler answers 501.
func newAPIHandler(health *v1.HealthHandler, problems *problem.Responder, identityHandler *v1.IdentityHandler) *v1.Handler {
return v1.NewHandler(health, problems, v1.WithIdentity(identityHandler))
}
// newIdentityHandler builds the registration operations and the PostgreSQL
// pool they own. Nothing connects here, so an unavailable database never
// blocks startup. It returns no handler when DATABASE_URL is unset, and the
// operations then answer 501. The application clock is time.Now.
func newIdentityHandler(
ctx context.Context,
settings config.Config,
logger *slog.Logger,
cache *redisadapter.Cache,
metrics *prometheus.Metrics,
) (*v1.IdentityHandler, func(), error) {
if settings.DatabaseURL == "" {
logger.Warn("registration is not served because DATABASE_URL is not set")
return nil, func() {}, nil
}
keyring, err := newIdentityKeyring(settings, logger)
if err != nil {
return nil, nil, err
}
renderer, err := mailtemplate.NewRenderer(settings.AppPublicURL)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create mail renderer: %w", err)
}
// New deliveries are pinned to the transport and account configured now.
account, err := domain.NewMailProviderAccount(string(settings.EmailProvider), settings.EmailAccount)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - mail provider account: %w", err)
}
hasher, err := argon2id.NewHasher(settings.PasswordHashConcurrency)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create password hasher: %w", err)
}
pool, err := postgres.NewSizedPool(ctx, settings.DatabaseURL, identityPoolMaxConns)
if err != nil {
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create pool: %w", err)
}
transactor := postgres.NewTransactor(pool)
registration, err := identity.NewRegistration(identity.RegistrationDependencies{
Transactor: transactor,
ConsentTexts: postgres.NewConsentStore(pool),
Idempotency: postgres.NewIdentityStore(pool).IdempotencyRecords(),
Consents: consent.NewService(transactor, time.Now),
Credentials: identity.NewCredentials(hasher),
Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(renderer), account, time.Now),
Limiter: cache,
Keyring: keyring,
Clock: time.Now,
Metrics: metrics,
}, identity.RegistrationSettings{
MailMinInterval: settings.VerificationMailMinInterval,
MailDailyLimit: int64(settings.VerificationMailDailyLimit),
ClientHourlyLimit: int64(settings.IdentityClientHourlyLimit),
})
if err != nil {
pool.Close()
return nil, nil, fmt.Errorf("bootstrap.newIdentityHandler - create registration: %w", err)
}
// The HTTP server stops before this cleanup runs, so no request uses the
// pool while it closes.
return v1.NewIdentityHandler(registration), pool.Close, nil
}
// newIdentityKeyring keys the idempotency scopes and rate limit buckets with
// IDENTITY_KEY_SECRET. Only with IDENTITY_ALLOW_EPHEMERAL_KEY, which the
// configuration check demands for an unset secret, a random one is drawn for
// this process: idempotency records and counters written before a restart no
// longer match, and instances of one deployment do not agree.
func newIdentityKeyring(settings config.Config, logger *slog.Logger) (*identity.Keyring, error) {
secret := []byte(settings.IdentityKeySecret)
if len(secret) == 0 {
secret = make([]byte, identity.MinKeySecretBytes)
if _, err := rand.Read(secret); err != nil {
return nil, fmt.Errorf("bootstrap.newIdentityKeyring - generate secret: %w", err)
}
logger.Warn("IDENTITY_ALLOW_EPHEMERAL_KEY is set and IDENTITY_KEY_SECRET is not; a random secret is used, so idempotency records and rate limits do not survive a restart")
}
keyring, err := identity.NewKeyring(secret)
if err != nil {
return nil, fmt.Errorf("bootstrap.newIdentityKeyring - create keyring: %w", err)
}
return keyring, nil
}
+1
View File
@@ -30,6 +30,7 @@ func loadMailConfig(t *testing.T, mail map[string]string) config.Config {
t.Helper()
values := map[string]string{
"SEAWEEDFS_ACCESS_KEY": "test-access",
"IDENTITY_KEY_SECRET": "test-identity-key-secret-0123456789ab",
"SEAWEEDFS_SECRET_KEY": "test-secret",
"EMAIL_FROM": "Lincodex <" + testSenderAddress + ">",
"APP_PUBLIC_URL": "http://localhost:8080",
+3 -1
View File
@@ -44,7 +44,9 @@ func initialize(
metrics.New,
newHealthHandler,
problem.NewResponder,
v1.NewHandler,
newAPIHandler,
newTrustedProxies,
newIdentityHandler,
v1.NewDenyAllSecurity,
httpadapter.NewRouter,
newOutboxRelay,
+29 -14
View File
@@ -45,24 +45,18 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
readiness := newReadiness(healthChecker, cache, storage)
healthHandler := newHealthHandler(readiness, config2)
responder := problem.NewResponder(logger)
handler := v1.NewHandler(healthHandler, responder)
denyAllSecurity := v1.NewDenyAllSecurity()
metrics := prometheus.New()
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger)
identityHandler, cleanup4, err := newIdentityHandler(ctx, config2, logger, cache, metrics)
if err != nil {
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
relay, cleanup4, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup5, err := newEventConsumers(ctx, config2, logger, metrics)
handler := newAPIHandler(healthHandler, responder, identityHandler)
denyAllSecurity := v1.NewDenyAllSecurity()
v := newTrustedProxies(config2)
httpHandler, err := httpadapter.NewRouter(healthHandler, handler, denyAllSecurity, responder, metrics, logger, v)
if err != nil {
cleanup4()
cleanup3()
@@ -70,7 +64,15 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
worker, cleanup6, err := newJobWorker(ctx, config2, logger, metrics)
relay, cleanup5, err := newOutboxRelay(ctx, config2, logger, metrics)
if err != nil {
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
bootstrapEventConsumers, cleanup6, err := newEventConsumers(ctx, config2, logger, metrics)
if err != nil {
cleanup5()
cleanup4()
@@ -79,7 +81,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
mailsenderWorker, cleanup7, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
worker, cleanup7, err := newJobWorker(ctx, config2, logger, metrics)
if err != nil {
cleanup6()
cleanup5()
@@ -89,7 +91,7 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup8, err := newDeliveryMetrics(ctx, config2, logger, metrics)
mailsenderWorker, cleanup8, err := newMailSenderWorker(ctx, config2, logger, metrics, mailSender)
if err != nil {
cleanup7()
cleanup6()
@@ -100,8 +102,21 @@ func initialize(ctx context.Context, config2 config.Config, logger *slog.Logger,
cleanup()
return nil, nil, err
}
sampler, cleanup9, err := newDeliveryMetrics(ctx, config2, logger, metrics)
if err != nil {
cleanup8()
cleanup7()
cleanup6()
cleanup5()
cleanup4()
cleanup3()
cleanup2()
cleanup()
return nil, nil, err
}
application := NewApplication(config2, httpHandler, metrics, logger, mailSender, relay, bootstrapEventConsumers, worker, mailsenderWorker, sampler)
return application, func() {
cleanup9()
cleanup8()
cleanup7()
cleanup6()
+29
View File
@@ -32,6 +32,29 @@ func ParseEmailTokenPurpose(value string) (EmailTokenPurpose, error) {
}
}
// PendingRegistration holds the credentials of one registration, which wait
// on the verification token issued for it. A registration of an unverified
// address never changes the account row; confirming a token applies its own
// pending credentials, and only to a caller who proves the password of that
// registration. Nothing here is valid for login before the confirmation.
type PendingRegistration struct {
PasswordHash PasswordHash
Scenario Scenario
OnboardingStep OnboardingStep
}
// NewPendingRegistration builds the pending credentials of a registration
// with the first onboarding step of its scenario.
func NewPendingRegistration(hash PasswordHash, scenario Scenario) (PendingRegistration, error) {
if hash.IsZero() {
return PendingRegistration{}, invalidEmailToken("pending password hash must be built by NewPasswordHash")
}
if _, err := ParseScenario(string(scenario)); err != nil {
return PendingRegistration{}, fmt.Errorf("domain.NewPendingRegistration - validate scenario: %w", err)
}
return PendingRegistration{PasswordHash: hash, Scenario: scenario, OnboardingStep: scenario.InitialOnboardingStep()}, nil
}
// EmailToken is the stored record of a one-time token sent by email. It holds
// only the hash of the raw token. A token ends at most once: it is either
// consumed or invalidated, and it stops working at ExpiresAt.
@@ -45,6 +68,9 @@ type EmailToken struct {
ExpiresAt time.Time
ConsumedAt *time.Time
InvalidatedAt *time.Time
// Pending is set on the verification token of a registration and nil on
// a token that carries no credentials.
Pending *PendingRegistration
}
// NewEmailTokenInput describes a token to issue. RegistrationVersion is the
@@ -56,6 +82,8 @@ type NewEmailTokenInput struct {
RegistrationVersion int64
IssuedAt time.Time
Lifetime time.Duration
// Pending is optional; see PendingRegistration.
Pending *PendingRegistration
}
// NewEmailToken validates input and assigns a UUIDv7 identifier.
@@ -87,6 +115,7 @@ func NewEmailToken(input NewEmailTokenInput) (EmailToken, error) {
RegistrationVersion: input.RegistrationVersion,
CreatedAt: input.IssuedAt,
ExpiresAt: input.IssuedAt.Add(input.Lifetime),
Pending: input.Pending,
}, nil
}
+9 -1
View File
@@ -184,7 +184,15 @@ func (registration Registration) validate(location string) error {
return nil
}
// User is an account. Storage reconstructs it from trusted rows; new accounts
// User is an account. The PasswordHash, Scenario, and OnboardingStep of an
// unverified account are not authoritative: they hold what the first
// registration of the address stored only because the columns are mandatory.
// A repeat registration never changes them; the credentials that count are the
// pending ones on the verification token, and confirming that token applies
// them. No code may authenticate with, or trust the scenario of, an
// unverified account row.
//
// Storage reconstructs it from trusted rows; new accounts
// come from NewUser and changes from its methods.
type User struct {
ID uuid.UUID
@@ -67,6 +67,7 @@ type IdentityRepositories interface {
Users() UserRepository
EmailTokens() EmailTokenRepository
Sessions() SessionRepository
IdempotencyRecords() IdempotencyRepository
}
// UserRepository stores accounts. Lookups by email use the normalized form.
@@ -97,6 +98,18 @@ type UserRepository interface {
// deletes nothing.
UpdateRegistration(ctx context.Context, user domain.User) (domain.User, error)
// AdvanceRegistration starts a new registration of an unverified account
// without changing its password hash, scenario, or onboarding step: the
// new registration carries them on its token (see
// domain.PendingRegistration). It applies only when the stored version
// still equals expectedVersion and the email is unverified, advances
// Version and RegistrationVersion by one in the same statement, sets the
// registration time, and deletes the C1 records with the source
// registration of the earlier registration like UpdateRegistration does;
// the caller grants the new C1 strictly after it. Otherwise it returns
// ErrUserVersionConflict.
AdvanceRegistration(ctx context.Context, id uuid.UUID, expectedVersion int64, at time.Time) (domain.User, error)
// MarkEmailVerified sets the verification time when the account is still
// unverified and still has registrationVersion, and returns the stored
// account. Otherwise it returns ErrUserVersionConflict. A confirmation
@@ -124,6 +137,11 @@ type EmailTokenRepository interface {
// ErrTokenHashConflict for a duplicate hash.
Insert(ctx context.Context, token domain.EmailToken) error
// LatestPending returns the pending credentials of the newest token that
// the registration version of the user has, or false when none carries
// any. A resend copies them to its new token.
LatestPending(ctx context.Context, userID uuid.UUID, registrationVersion int64) (domain.PendingRegistration, bool, error)
// InvalidateActive marks every unconsumed, not yet invalidated token of
// the user and purpose as invalidated at the given time, and returns how
// many it marked.
@@ -174,3 +192,51 @@ type SessionRepository interface {
// how many it revoked.
RevokeAllForUser(ctx context.Context, userID uuid.UUID, at time.Time) (int64, error)
}
// IdempotencyRetention is how long the replay record of a command with an
// Idempotency-Key lives, as the public contract states. After it the key may
// be accepted as new.
const IdempotencyRetention = 24 * time.Hour
// IdempotencyDigestSize is the size of the HMAC-SHA-256 values that identify
// and fingerprint a command.
const IdempotencyDigestSize = 32
// IdempotencyRecord is the replay record of a committed command. Both digests
// are HMAC-SHA-256 values computed with a server secret; the record holds
// neither the key, the email, nor the request body.
type IdempotencyRecord struct {
// Scope identifies the operation, the key, and the principal; for an
// anonymous operation the principal is the normalized email.
Scope [IdempotencyDigestSize]byte
// Fingerprint identifies the request that the key was first used with.
Fingerprint [IdempotencyDigestSize]byte
CreatedAt time.Time
ExpiresAt time.Time
}
// IdempotencyRepository stores the replay records of commands. Reserve runs
// in the transaction of the command it guards, so a stored record always
// belongs to a committed command.
type IdempotencyRepository interface {
// Reserve stores record unless a live record with the same scope exists.
// For a stored record it returns it with created true. For a live record
// it returns that record with created false and stores nothing; the
// caller compares the fingerprints to decide between a replay and a
// reused key. A concurrent Reserve with the same scope waits until the
// transaction of the first ends. A record past ExpiresAt is replaced.
// Every method that takes a time rejects the zero time.
Reserve(ctx context.Context, record IdempotencyRecord) (stored IdempotencyRecord, created bool, err error)
// Find returns the live record with the scope at the given time, or
// ErrIdempotencyRecordNotFound.
Find(ctx context.Context, scope [IdempotencyDigestSize]byte, at time.Time) (IdempotencyRecord, error)
// PurgeExpired deletes at most limit records that expired at or before
// the given time and returns how many it deleted. It never waits for a
// locked record.
PurgeExpired(ctx context.Context, at time.Time, limit int32) (int64, error)
}
// ErrIdempotencyRecordNotFound reports that no live record has the scope.
var ErrIdempotencyRecordNotFound = errors.New("idempotency record not found")
@@ -0,0 +1,39 @@
package outbound
import (
"context"
"errors"
"time"
)
// ErrInvalidRateLimitRule reports a rule without a positive window or limit,
// or a take without a key or a rule.
var ErrInvalidRateLimitRule = errors.New("invalid rate limit rule")
// RateLimitRule allows at most Limit takes per fixed Window. The window of a
// key starts with its first take and ends Window later.
type RateLimitRule struct {
Window time.Duration
Limit int64
}
// RateLimitDecision is the outcome of Take.
type RateLimitDecision struct {
// Allowed reports that the take was counted against every rule.
Allowed bool
// RetryAfter is, for a refused take, how long until every rule that
// refused it admits another one. It is zero for an allowed take.
RetryAfter time.Duration
}
// RateLimiter counts requests of one caller key against fixed windows. The
// counters are ephemeral: a restart or a flush of the store resets them, so
// a limiter is an abuse brake, never a record of what happened.
type RateLimiter interface {
// Take counts one request of key against every rule at once. It counts
// nothing when any rule refuses, so refused requests do not extend a
// window. The key is an opaque string that must not hold personal data
// in clear form; callers pass a keyed digest. A store failure returns
// an error and the caller decides how to fail.
Take(ctx context.Context, key string, rules ...RateLimitRule) (RateLimitDecision, error)
}
@@ -0,0 +1,51 @@
package identity
import (
"errors"
"fmt"
"time"
)
var (
// ErrRateLimited reports a request refused by the per-address limit.
// errors.As with *RateLimitedError yields the wait.
ErrRateLimited = errors.New("rate limit exceeded")
// ErrIdempotencyKeyReused reports a key that was first used with another
// request body for the same address.
ErrIdempotencyKeyReused = errors.New("idempotency key reused with a different request")
// ErrInvalidField reports a request value outside its rules.
// errors.As with *InvalidFieldError yields the JSON Pointer of the field.
ErrInvalidField = errors.New("invalid request field")
)
// RateLimitedError carries how long the caller waits before a repeat can be
// accepted. It matches ErrRateLimited.
type RateLimitedError struct {
RetryAfter time.Duration
}
func (err *RateLimitedError) Error() string {
return fmt.Sprintf("rate limit exceeded, retry after %s", err.RetryAfter)
}
func (err *RateLimitedError) Unwrap() error { return ErrRateLimited }
// InvalidFieldError names the body field that failed and why, without the
// value. Pointer is the JSON Pointer of the field in the request body. It
// matches ErrInvalidField and also the domain error it wraps.
type InvalidFieldError struct {
Pointer string
Err error
}
func (err *InvalidFieldError) Error() string {
return fmt.Sprintf("invalid request field %s: %v", err.Pointer, err.Err)
}
func (err *InvalidFieldError) Unwrap() []error { return []error{ErrInvalidField, err.Err} }
func invalidField(pointer string, cause error) error {
return &InvalidFieldError{Pointer: pointer, Err: cause}
}
@@ -0,0 +1,90 @@
package identity
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"lincodex/backend/internal/port/outbound"
)
// MinKeySecretBytes is the shortest secret that NewKeyring accepts.
const MinKeySecretBytes = 32
// Domain-separation labels. Each purpose gets its own key derived from the
// one secret, so a digest made for one purpose never matches another.
const (
labelIdempotencyScope = "lincodex/identity/idempotency-scope/v1"
labelFingerprint = "lincodex/identity/request-fingerprint/v1"
labelEmailBucket = "lincodex/identity/email-bucket/v1"
labelClientBucket = "lincodex/identity/client-bucket/v1"
)
// Keyring computes the keyed digests of the anonymous identity operations:
// the idempotency scope, the request fingerprint, and the rate limit bucket
// of an email address. All of them are HMAC-SHA-256 values, so what the
// stores hold can neither confirm that an address is registered nor serve as
// an offline check of a password without the server secret.
type Keyring struct {
scopeKey []byte
fingerprintKey []byte
bucketKey []byte
clientKey []byte
}
// NewKeyring derives the purpose keys from secret.
func NewKeyring(secret []byte) (*Keyring, error) {
if len(secret) < MinKeySecretBytes {
return nil, fmt.Errorf("identity.NewKeyring - secret must have at least %d bytes", MinKeySecretBytes)
}
return &Keyring{
scopeKey: derive(secret, labelIdempotencyScope),
fingerprintKey: derive(secret, labelFingerprint),
bucketKey: derive(secret, labelEmailBucket),
clientKey: derive(secret, labelClientBucket),
}, nil
}
func derive(secret []byte, label string) []byte {
mac := hmac.New(sha256.New, secret)
mac.Write([]byte(label))
return mac.Sum(nil)
}
// IdempotencyScope scopes a key by the operation, the key, and the
// normalized email. The parts are joined with NUL, which none of them can
// contain: operation names and keys are limited to printable ASCII and the
// email is printable ASCII.
func (keyring *Keyring) IdempotencyScope(operation, key, normalizedEmail string) [outbound.IdempotencyDigestSize]byte {
mac := hmac.New(sha256.New, keyring.scopeKey)
mac.Write([]byte(operation))
mac.Write([]byte{0})
mac.Write([]byte(key))
mac.Write([]byte{0})
mac.Write([]byte(normalizedEmail))
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
}
// Fingerprint identifies a request by its canonical body.
func (keyring *Keyring) Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte {
mac := hmac.New(sha256.New, keyring.fingerprintKey)
mac.Write(canonicalBody)
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
}
// EmailBucket names the rate limit counters of one address, whether or not
// an account exists for it, so a refusal does not reveal an account.
func (keyring *Keyring) EmailBucket(normalizedEmail string) string {
mac := hmac.New(sha256.New, keyring.bucketKey)
mac.Write([]byte(normalizedEmail))
return "identity:email:" + hex.EncodeToString(mac.Sum(nil))
}
// ClientBucket names the rate limit counters of one client from its opaque
// key, so the store never holds a network address in clear form.
func (keyring *Keyring) ClientBucket(clientKey string) string {
mac := hmac.New(sha256.New, keyring.clientKey)
mac.Write([]byte(clientKey))
return "identity:client:" + hex.EncodeToString(mac.Sum(nil))
}
@@ -0,0 +1,520 @@
package identity
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/usecase/consent"
"lincodex/backend/internal/usecase/notification"
)
const (
// registerOperation names RegisterAccount in the idempotency scope.
registerOperation = "RegisterAccount"
// maxIdempotencyKeyLength is the longest Idempotency-Key of the contract.
maxIdempotencyKeyLength = 255
// maxTransactionAttempts bounds the retries of a registration or a resend
// after a lost race: a concurrent registration of the same address, a
// concurrent re-registration, or a deadlock. Each retry reads the account
// again, so it takes the branch that matches the winner.
maxTransactionAttempts = 3
// purgeBatch is how many expired idempotency records one registration
// removes, so the table stays bounded without a separate job.
purgeBatch = 10
idempotencyKeyPointer = "/Idempotency-Key"
consentTextVersionPointer = "/consent_c1/text_version"
emailPointer = "/email"
passwordPointer = "/password"
scenarioPointer = "/scenario"
)
// RegistrationSettings holds the limits of the verification mail to one
// address. The registration and every resend count against both rules, so
// registering again and then resending cannot send more than the daily limit.
type RegistrationSettings struct {
// MailMinInterval is the shortest time between two verification messages
// to one address.
MailMinInterval time.Duration
// MailDailyLimit is the number of verification messages to one address in
// a window of 24 hours that starts with the first of them.
MailDailyLimit int64
// ClientHourlyLimit is the number of registrations and resends per client
// in a window of one hour. It applies only to a request that carries a
// client key.
ClientHourlyLimit int64
}
const (
// mailDailyWindow is the window of RegistrationSettings.MailDailyLimit.
mailDailyWindow = 24 * time.Hour
// clientWindow is the window of RegistrationSettings.ClientHourlyLimit.
clientWindow = time.Hour
)
func (settings RegistrationSettings) mailRules() []outbound.RateLimitRule {
return []outbound.RateLimitRule{
{Window: settings.MailMinInterval, Limit: 1},
{Window: mailDailyWindow, Limit: settings.MailDailyLimit},
}
}
func (settings RegistrationSettings) validate() error {
switch {
case settings.MailMinInterval < time.Millisecond || settings.MailMinInterval >= mailDailyWindow:
return errors.New("mail minimum interval must be at least one millisecond and shorter than the daily window")
case settings.MailDailyLimit < 1:
return errors.New("mail daily limit must be positive")
case settings.ClientHourlyLimit < 1:
return errors.New("client hourly limit must be positive")
}
return nil
}
// RegistrationDependencies are the collaborators of Registration. Every
// field is required.
type RegistrationDependencies struct {
Transactor outbound.Transactor
// ConsentTexts and Idempotency read outside a transaction: the consent
// text check and the replay check run before the registration
// transaction starts.
ConsentTexts outbound.ConsentRepositories
Idempotency outbound.IdempotencyRepository
Consents *consent.Service
Credentials *Credentials
Mailer *notification.ServiceMailer
Limiter outbound.RateLimiter
Keyring *Keyring
Clock func() time.Time
// Metrics receives the refusals of the limiter. Optional.
Metrics RateLimitMetrics
}
// Scopes of a limiter refusal, as the metric labels them.
const (
ScopeAddress = "address"
ScopeClient = "client"
)
// RateLimitMetrics counts refused requests by scope, never by address.
type RateLimitMetrics interface {
ObserveIdentityRateLimited(scope string)
}
// Registration registers accounts and resends the verification message. It
// holds no state; the same instance serves concurrent callers.
//
// Neither operation reveals whether an address belongs to an account: the
// outcome, the response, and the rate limit depend on the request alone,
// never on the stored accounts. Registration also computes the password hash
// on every branch before it reads the account.
type Registration struct {
deps RegistrationDependencies
settings RegistrationSettings
}
// NewRegistration checks the dependencies and settings once, so a wiring
// mistake fails at startup and not at the first request.
func NewRegistration(deps RegistrationDependencies, settings RegistrationSettings) (*Registration, error) {
switch {
case deps.Transactor == nil, deps.ConsentTexts == nil, deps.Idempotency == nil, deps.Consents == nil,
deps.Credentials == nil, deps.Mailer == nil, deps.Limiter == nil, deps.Keyring == nil, deps.Clock == nil:
return nil, errors.New("identity.NewRegistration - every dependency must be set")
}
if err := settings.validate(); err != nil {
return nil, fmt.Errorf("identity.NewRegistration - validate settings: %w", err)
}
return &Registration{deps: deps, settings: settings}, nil
}
// RegisterCommand is the content of a registration request, unvalidated.
type RegisterCommand struct {
IdempotencyKey string
Email string
Password string
Scenario string
// ConsentTextVersion is the version of the C1 text the user accepted.
ConsentTextVersion string
// ClientKey identifies the client for the per-client limit, for example
// the limiter key of its network address. Empty skips that limit. It is
// opaque, is only ever keyed-hashed here, and is never stored or logged.
ClientKey string
}
// ResendCommand is the content of a resend request, unvalidated.
type ResendCommand struct {
Email string
// ClientKey is as in RegisterCommand.
ClientKey string
}
// registerInput is a validated command.
type registerInput struct {
email domain.EmailAddress
scenario domain.Scenario
version domain.ConsentTextVersion
hash domain.PasswordHash
record outbound.IdempotencyRecord
fingerprint [outbound.IdempotencyDigestSize]byte
}
// Register handles one registration request. A nil result means the neutral
// acceptance, whatever the state of the address: a new account was created, a
// pending registration was replaced, a verified account was left alone, or
// the request replays an earlier identical one.
//
// Errors: *InvalidFieldError for a value outside its rules, including a C1
// text version that is no longer current; ErrIdempotencyKeyReused;
// *RateLimitedError; anything else is an internal failure.
//
// Order: validation, replay check, rate limit, password hash, transaction.
// A replay does not consume the limit, so a client that retries a lost
// answer is not refused for it.
func (registration *Registration) Register(ctx context.Context, command RegisterCommand) error {
const location = "Registration.Register"
input, err := registration.validateRegister(ctx, command)
if err != nil {
return fmt.Errorf("%s - validate request: %w", location, err)
}
existing, err := registration.deps.Idempotency.Find(ctx, input.record.Scope, registration.deps.Clock())
switch {
case err == nil:
return replayOrReject(location, existing, input.fingerprint)
case !errors.Is(err, outbound.ErrIdempotencyRecordNotFound):
return fmt.Errorf("%s - read idempotency record: %w", location, err)
}
if err := registration.takeMailSlot(ctx, input.email, command.ClientKey); err != nil {
return fmt.Errorf("%s - limit verification mail: %w", location, err)
}
// The hash is computed on every branch, before the account is read, so
// the time of the response does not tell a new address from a known one.
input.hash, err = registration.deps.Credentials.HashNewPassword(ctx, command.Password)
if err != nil {
return fmt.Errorf("%s - hash password: %w", location, err)
}
err = registration.inTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return registration.registerInTransaction(ctx, unit, input)
})
if err != nil {
return fmt.Errorf("%s - register in transaction: %w", location, err)
}
return nil
}
func (registration *Registration) validateRegister(ctx context.Context, command RegisterCommand) (registerInput, error) {
if command.IdempotencyKey == "" || len(command.IdempotencyKey) > maxIdempotencyKeyLength {
return registerInput{}, invalidField(idempotencyKeyPointer, errors.New("key must have 1 to 255 characters"))
}
email, err := domain.NewEmailAddress(command.Email)
if err != nil {
return registerInput{}, invalidField(emailPointer, err)
}
if _, err := domain.NewPassword(command.Password); err != nil {
return registerInput{}, invalidField(passwordPointer, err)
}
scenario, err := domain.ParseScenario(command.Scenario)
if err != nil {
return registerInput{}, invalidField(scenarioPointer, err)
}
version, err := domain.ParseConsentTextVersion(command.ConsentTextVersion)
if err != nil {
return registerInput{}, invalidField(consentTextVersionPointer, err)
}
// The check runs before any lookup of the address, so a stale version
// fails the same way for a new and for a known address.
_, err = registration.deps.Consents.CheckTextVersion(ctx, registration.deps.ConsentTexts, domain.ConsentPurposePersonalData, version)
if errors.Is(err, consent.ErrStaleConsentText) {
return registerInput{}, invalidField(consentTextVersionPointer, err)
}
if err != nil {
return registerInput{}, fmt.Errorf("check consent text version: %w", err)
}
fingerprint, err := registration.fingerprint(command)
if err != nil {
return registerInput{}, err
}
now := registration.deps.Clock()
return registerInput{
email: email,
scenario: scenario,
version: version,
fingerprint: fingerprint,
record: outbound.IdempotencyRecord{
Scope: registration.deps.Keyring.IdempotencyScope(registerOperation, command.IdempotencyKey, email.Normalized()),
Fingerprint: fingerprint,
CreatedAt: now,
ExpiresAt: now.Add(outbound.IdempotencyRetention),
},
}, nil
}
// fingerprint is the HMAC of the canonical body: a JSON array of the fields
// in a fixed order, with the values as the client sent them.
func (registration *Registration) fingerprint(command RegisterCommand) ([outbound.IdempotencyDigestSize]byte, error) {
canonical, err := json.Marshal([]string{command.Email, command.Password, command.Scenario, command.ConsentTextVersion})
if err != nil {
return [outbound.IdempotencyDigestSize]byte{}, fmt.Errorf("encode canonical body: %w", err)
}
return registration.deps.Keyring.Fingerprint(canonical), nil
}
func replayOrReject(location string, existing outbound.IdempotencyRecord, fingerprint [outbound.IdempotencyDigestSize]byte) error {
if existing.Fingerprint != fingerprint {
return fmt.Errorf("%s - compare fingerprints: %w", location, ErrIdempotencyKeyReused)
}
return nil
}
// registerInTransaction applies one registration. The idempotency record is
// reserved first: a concurrent request with the same scope then waits for
// this transaction and replays its outcome.
func (registration *Registration) registerInTransaction(ctx context.Context, unit outbound.UnitOfWork, input registerInput) error {
const location = "Registration.registerInTransaction"
now := registration.deps.Clock()
stored, created, err := unit.IdempotencyRecords().Reserve(ctx, input.record)
if err != nil {
return fmt.Errorf("%s - reserve idempotency record: %w", location, err)
}
if !created {
return replayOrReject(location, stored, input.fingerprint)
}
if _, err := unit.IdempotencyRecords().PurgeExpired(ctx, now, purgeBatch); err != nil {
return fmt.Errorf("%s - purge expired idempotency records: %w", location, err)
}
user, err := unit.Users().GetByEmail(ctx, input.email)
switch {
case errors.Is(err, outbound.ErrUserNotFound):
return registration.createAccount(ctx, unit, input, now)
case err != nil:
return fmt.Errorf("%s - read account: %w", location, err)
case user.EmailVerified():
// A verified account never changes and nothing is sent: the notice
// "you already have an account" is not implemented, see the
// architecture document.
return nil
default:
return registration.reRegister(ctx, unit, input, user, now)
}
}
func (registration *Registration) createAccount(ctx context.Context, unit outbound.UnitOfWork, input registerInput, now time.Time) error {
const location = "Registration.createAccount"
user, err := domain.NewUser(domain.Registration{
Email: input.email,
PasswordHash: input.hash,
Scenario: input.scenario,
RegisteredAt: now,
})
if err != nil {
return fmt.Errorf("%s - build account: %w", location, err)
}
if err := unit.Users().Create(ctx, user); err != nil {
return fmt.Errorf("%s - store account: %w", location, err)
}
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, user.ID, input.version); err != nil {
return fmt.Errorf("%s - record C1: %w", location, err)
}
pending, err := domain.NewPendingRegistration(input.hash, input.scenario)
if err != nil {
return fmt.Errorf("%s - build pending registration: %w", location, err)
}
return registration.issueVerification(ctx, unit, user, now, &pending)
}
// reRegister starts a new registration of an unverified address. It never
// changes the credentials, scenario, or onboarding step of the account row:
// the new registration carries its own on its verification token, and
// confirming a token applies only the credentials of that token (TASK-054).
// So neither the first nor the latest registrant of an address can make its
// owner adopt a password the owner did not choose. The lock order of the
// identity repositories applies: tokens first, then the account.
// AdvanceRegistration deletes the earlier C1 of this account, so the new C1 is
// granted strictly after it.
func (registration *Registration) reRegister(
ctx context.Context,
unit outbound.UnitOfWork,
input registerInput,
user domain.User,
now time.Time,
) error {
const location = "Registration.reRegister"
if _, err := unit.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, now); err != nil {
return fmt.Errorf("%s - invalidate earlier tokens: %w", location, err)
}
advanced, err := unit.Users().AdvanceRegistration(ctx, user.ID, user.Version, now)
if err != nil {
return fmt.Errorf("%s - advance registration: %w", location, err)
}
if _, err := registration.deps.Consents.GrantAtRegistration(ctx, unit, advanced.ID, input.version); err != nil {
return fmt.Errorf("%s - record C1: %w", location, err)
}
pending, err := domain.NewPendingRegistration(input.hash, input.scenario)
if err != nil {
return fmt.Errorf("%s - build pending registration: %w", location, err)
}
return registration.issueVerification(ctx, unit, advanced, now, &pending)
}
// issueVerification stores a new token bound to the current registration
// version and queues its message, in the caller's transaction.
func (registration *Registration) issueVerification(
ctx context.Context,
unit outbound.UnitOfWork,
user domain.User,
now time.Time,
pending *domain.PendingRegistration,
) error {
const location = "Registration.issueVerification"
policy, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, now)
if err != nil {
return fmt.Errorf("%s - read product policy: %w", location, err)
}
lifetime := policy.Policy().Identity.VerificationTokenLifetime
raw, err := domain.NewSecretToken()
if err != nil {
return fmt.Errorf("%s - generate token: %w", location, err)
}
token, err := domain.NewEmailToken(domain.NewEmailTokenInput{
UserID: user.ID,
Purpose: domain.EmailTokenPurposeEmailVerification,
TokenHash: raw.Hash(),
RegistrationVersion: user.RegistrationVersion,
IssuedAt: now,
Lifetime: lifetime.Duration(),
Pending: pending,
})
if err != nil {
return fmt.Errorf("%s - build token: %w", location, err)
}
if err := unit.EmailTokens().Insert(ctx, token); err != nil {
return fmt.Errorf("%s - store token: %w", location, err)
}
_, err = registration.deps.Mailer.EnqueueVerification(ctx, unit, notification.TokenMailRequest{
Recipient: user.Email,
Token: token,
RawToken: raw,
Lifetime: lifetime,
})
if err != nil {
return fmt.Errorf("%s - queue message: %w", location, err)
}
return nil
}
// ResendVerification issues a new verification token for an unverified
// account and queues its message. The explicit replacement policy: every
// unused token of the account is invalidated before the new one is stored, so
// at most one verification link works at a time, and the registration
// version of the account does not change.
//
// A nil result is the neutral acceptance, for an unknown address, a verified
// one, and an unverified one alike. The rate limit counts the request before
// the account is read, so a refusal says nothing about the account; it
// returns *RateLimitedError.
func (registration *Registration) ResendVerification(ctx context.Context, command ResendCommand) error {
const location = "Registration.ResendVerification"
email, err := domain.NewEmailAddress(command.Email)
if err != nil {
return fmt.Errorf("%s - validate request: %w", location, invalidField(emailPointer, err))
}
if err := registration.takeMailSlot(ctx, email, command.ClientKey); err != nil {
return fmt.Errorf("%s - limit verification mail: %w", location, err)
}
err = registration.inTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
return registration.resendInTransaction(ctx, unit, email)
})
if err != nil {
return fmt.Errorf("%s - resend in transaction: %w", location, err)
}
return nil
}
func (registration *Registration) resendInTransaction(ctx context.Context, unit outbound.UnitOfWork, email domain.EmailAddress) error {
const location = "Registration.resendInTransaction"
user, err := unit.Users().GetByEmail(ctx, email)
switch {
case errors.Is(err, outbound.ErrUserNotFound):
return nil
case err != nil:
return fmt.Errorf("%s - read account: %w", location, err)
case user.EmailVerified():
return nil
}
now := registration.deps.Clock()
// A resend keeps the credentials of the registration it resends for.
var pending *domain.PendingRegistration
latest, found, err := unit.EmailTokens().LatestPending(ctx, user.ID, user.RegistrationVersion)
if err != nil {
return fmt.Errorf("%s - read pending credentials: %w", location, err)
}
if found {
pending = &latest
}
if pending == nil {
// No token of this registration carries credentials, which only a
// token that was invalidated concurrently can cause. A token without
// them could never be confirmed, so none is issued; the next
// registration of the address starts over.
return nil
}
if _, err := unit.EmailTokens().InvalidateActive(ctx, user.ID, domain.EmailTokenPurposeEmailVerification, now); err != nil {
return fmt.Errorf("%s - invalidate earlier tokens: %w", location, err)
}
return registration.issueVerification(ctx, unit, user, now, pending)
}
// takeMailSlot counts the request against the per-client rule, when the
// request has a client key, and then against the per-address rules. The
// address counters see every request, whether or not an account exists, so a
// refusal does not reveal an account. A refused request counts nothing in the
// rule that refused it.
func (registration *Registration) takeMailSlot(ctx context.Context, email domain.EmailAddress, clientKey string) error {
if clientKey != "" {
err := registration.take(ctx, ScopeClient, registration.deps.Keyring.ClientBucket(clientKey),
outbound.RateLimitRule{Window: clientWindow, Limit: registration.settings.ClientHourlyLimit})
if err != nil {
return err
}
}
return registration.take(ctx, ScopeAddress, registration.deps.Keyring.EmailBucket(email.Normalized()), registration.settings.mailRules()...)
}
func (registration *Registration) take(ctx context.Context, scope, bucket string, rules ...outbound.RateLimitRule) error {
decision, err := registration.deps.Limiter.Take(ctx, bucket, rules...)
if err != nil {
return fmt.Errorf("take rate limit: %w", err)
}
if !decision.Allowed {
if registration.deps.Metrics != nil {
registration.deps.Metrics.ObserveIdentityRateLimited(scope)
}
return &RateLimitedError{RetryAfter: decision.RetryAfter}
}
return nil
}
// inTransaction runs work and repeats it, up to maxTransactionAttempts times
// in total, after a lost race. Every repeat reads the account again, so it is
// safe: the first attempt rolled back completely.
func (registration *Registration) inTransaction(ctx context.Context, work func(context.Context, outbound.UnitOfWork) error) error {
for attempt := 1; ; attempt++ {
err := registration.deps.Transactor.WithinTransaction(ctx, work)
if err == nil || !retryable(err) || attempt >= maxTransactionAttempts || ctx.Err() != nil {
return err
}
}
}
func retryable(err error) bool {
return errors.Is(err, outbound.ErrEmailTaken) ||
errors.Is(err, outbound.ErrUserVersionConflict) ||
errors.Is(err, outbound.ErrTransactionConflict)
}