//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" emailVerificationPath = "/api/v1/identity/email-verifications" 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 // registrationEmailHourlyLimit is the production default of the login // limit per address, which code confirmation shares. registrationEmailHourlyLimit = 10 registrationSecret = "integration-test-identity-key-secret-0123456789" registrationApplication = "registration_http" ) var ( registrationTables = slices.Concat( mailSenderTables, usersDependentTables, []pgx.Identifier{{"idempotency_records"}, {"outbox_events"}}, ) // 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 origin string // 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() poolConfig, err := pgxpool.ParseConfig(env.Config.DatabaseURL) if err != nil { t.Fatalf("parse bootstrap database URL: %v", err) } poolConfig.MaxConns = 16 poolConfig.ConnConfig.RuntimeParams["application_name"] = registrationApplication pool, err := pgxpool.NewWithConfig(ctx, poolConfig) if err != nil { t.Fatalf("create registration PostgreSQL pool: %v", err) } t.Cleanup(pool.Close) // 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) credentials := identity.NewCredentials(hasher) metrics := prometheus.New() registration, err := identity.NewRegistration(identity.RegistrationDependencies{ Transactor: transactor, ConsentTexts: postgresadapter.NewConsentStore(pool), Idempotency: identityStore.IdempotencyRecords(), Consents: consent.NewService(transactor, clock.Now), Credentials: credentials, Mailer: notification.NewServiceMailer(notification.NewTemplateRenderer(templates), account, clock.Now), Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, Metrics: metrics, }, identity.RegistrationSettings{ MailMinInterval: registrationMinInterval, MailDailyLimit: registrationDailyLimit, ClientHourlyLimit: clientHourlyLimit, }) if err != nil { t.Fatalf("NewRegistration() error = %v", err) } confirmation, err := identity.NewEmailConfirmation(identity.ConfirmationDependencies{ Transactor: transactor, Tokens: identityStore.EmailTokens(), Credentials: credentials, Limiter: env.Redis, Keyring: keyring, Clock: clock.Now, Metrics: metrics, }, identity.ConfirmationSettings{ TokenHourlyLimit: 2, ClientHourlyLimit: clientHourlyLimit, EmailHourlyLimit: registrationEmailHourlyLimit, }) if err != nil { t.Fatalf("NewEmailConfirmation() 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, v1.WithEmailConfirmation(confirmation), v1.WithPublicOrigin(env.Config.AppPublicURL), ))) router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, metrics, 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 ®istrationHarness{ start: start, pool: pool, router: router, sender: sender, fixture: fixture, clock: clock, logs: logs, identity: identityStore, origin: env.Config.AppPublicURL, 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 setCookie string } func (harness *registrationHarness) post(t *testing.T, path, body string, headers map[string]string) registrationResponse { return harness.postWithOriginDefault(t, path, body, headers, true) } func (harness *registrationHarness) postWithoutDefaultOrigin(t *testing.T, path, body string, headers map[string]string) registrationResponse { return harness.postWithOriginDefault(t, path, body, headers, false) } func (harness *registrationHarness) postWithOriginDefault(t *testing.T, path, body string, headers map[string]string, setDefaultOrigin bool) registrationResponse { t.Helper() request := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) request.Header.Set("Content-Type", "application/json") if setDefaultOrigin { request.Header.Set("Origin", harness.origin) } 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"), setCookie: recorder.Header().Get("Set-Cookie"), } } 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 } // registerAndSendVerification follows the real registration message through // the local Resend receiver and returns the token from the received link. func (harness *registrationHarness) registerAndSendVerification( ctx context.Context, t *testing.T, email, scenario, password string, ) string { t.Helper() link := verificationLinkToken.FindStringSubmatch(harness.registerAndReceiveVerification(ctx, t, email, scenario, password)) if link == nil { t.Fatal("the received verification message has no token in its link fragment") } return link[1] } // registerAndReceiveVerification registers the address, delivers the queued // message through the fixture, and returns the text of the message. func (harness *registrationHarness) registerAndReceiveVerification( ctx context.Context, t *testing.T, email, scenario, password string, ) string { t.Helper() requestCount := len(harness.fixture.Requests()) response := harness.registerBody(t, registrationBody(email, scenario, password, registrationC1), "") requireAccepted(t, response) return harness.receiveVerificationText(ctx, t, email, requestCount) } // receiveVerificationText drains the sending worker and returns the text of the // one message the fixture received after requestCount requests. func (harness *registrationHarness) receiveVerificationText(ctx context.Context, t *testing.T, email string, requestCount int) string { t.Helper() if settled := harness.drain(ctx, t); settled != 1 { t.Fatalf("settled %d deliveries, want 1", settled) } received := harness.fixture.Requests()[requestCount:] if len(received) != 1 || !slices.Equal(received[0].To, []string{email}) { t.Fatalf("fixture received %d messages, want one to the registered address", len(received)) } return received[0].Text } // 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 TestPublicIdentityOriginRefusalDoesNotMutateAccountsOrMailState(t *testing.T) { env := bootstrap(t, postgresService, redisService) ctx, cancel := context.WithTimeout(t.Context(), registrationTestTimeout) defer cancel() harness := newRegistrationHarness(ctx, t, env, 1000) harness.truncate(ctx, t) harness.clock.Set(harness.start) const verifiedFlowEmail = "origin-check@example.test" token := harness.registerAndSendVerification(ctx, t, verifiedFlowEmail, "candidate", registrationPassword) stateCounts := func() map[string]int { t.Helper() counts := make(map[string]int) for _, table := range []string{"users", "consent_records", "email_tokens", "idempotency_records", "outbox_events", "deliveries"} { counts[table] = harness.count(ctx, t, "SELECT count(*) FROM "+table) } return counts } assertCountsUnchanged := func(want map[string]int) { t.Helper() for table, expected := range want { if got := harness.count(ctx, t, "SELECT count(*) FROM "+table); got != expected { t.Errorf("%s count = %d after Origin refusal, want unchanged at %d", table, got, expected) } } } before := stateCounts() register := harness.post(t, registrationPath, registrationBody("rejected@example.test", "candidate", registrationPassword, registrationC1), map[string]string{"Idempotency-Key": "origin-refused-registration", "Origin": "https://attacker.example"}, ) requireProblemStatus(t, register, http.StatusForbidden, "csrf_check_failed") assertCountsUnchanged(before) resend := harness.post(t, resendPath, `{"email":"`+verifiedFlowEmail+`"}`, map[string]string{"Origin": "https://attacker.example"}) requireProblemStatus(t, resend, http.StatusForbidden, "csrf_check_failed") assertCountsUnchanged(before) confirmation := harness.post(t, emailVerificationPath, `{"token":"`+token+`","password":"`+registrationPassword+`"}`, map[string]string{"Origin": "https://attacker.example"}, ) requireProblemStatus(t, confirmation, http.StatusForbidden, "csrf_check_failed") assertCountsUnchanged(before) var verifiedAt *time.Time var registrationVersion int64 if err := harness.pool.QueryRow(ctx, `SELECT email_verified_at, registration_version FROM users WHERE email_normalized = $1`, verifiedFlowEmail, ).Scan(&verifiedAt, ®istrationVersion); err != nil { t.Fatalf("read account after Origin refusals: %v", err) } if verifiedAt != nil || registrationVersion != 1 { t.Fatalf("account state after refused operations: verified=%v registration version=%d", verifiedAt, registrationVersion) } var consumedAt, invalidatedAt *time.Time if err := harness.pool.QueryRow(ctx, `SELECT consumed_at, invalidated_at FROM email_tokens WHERE user_id = (SELECT id FROM users WHERE email_normalized = $1)`, verifiedFlowEmail, ).Scan(&consumedAt, &invalidatedAt); err != nil { t.Fatalf("read verification token state after Origin refusals: %v", err) } if consumedAt != nil || invalidatedAt != nil { t.Fatalf("verification token changed after Origin refusals: consumed=%v invalidated=%v", consumedAt, invalidatedAt) } } 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) }