feat(identity): confirm registration email atomically

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

No files matched your search

+68 -5
View File
@@ -42,6 +42,7 @@ 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
@@ -50,10 +51,15 @@ const (
registrationMinInterval = 3 * time.Second
registrationDailyLimit = 3
registrationSecret = "integration-test-identity-key-secret-0123456789"
registrationApplication = "registration_http"
)
var (
registrationTables = slices.Concat(mailSenderTables, usersDependentTables, []pgx.Identifier{{"idempotency_records"}})
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})`)
@@ -77,7 +83,17 @@ type registrationHarness struct {
func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironment, clientHourlyLimit int64) *registrationHarness {
t.Helper()
pool := env.newPoolWithMaxConns(ctx, t, 16)
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)}
@@ -114,16 +130,19 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
}
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: identity.NewCredentials(hasher),
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,
@@ -132,11 +151,28 @@ func newRegistrationHarness(ctx context.Context, t *testing.T, env *testEnvironm
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,
})
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)))
router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, prometheus.New(), logger, nil)
handler := v1.NewHandler(healthHandler, responder, v1.WithIdentity(v1.NewIdentityHandler(
registration, v1.WithEmailConfirmation(confirmation, env.Config.AppPublicURL),
)))
router, err := httpadapter.NewRouter(healthHandler, handler, v1.NewDenyAllSecurity(), responder, metrics, logger, nil)
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
@@ -170,6 +206,7 @@ type registrationResponse struct {
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 {
@@ -186,6 +223,7 @@ func (harness *registrationHarness) post(t *testing.T, path, body string, header
body: recorder.Body.String(),
retryAfter: recorder.Header().Get("Retry-After"),
contentType: recorder.Header().Get("Content-Type"),
setCookie: recorder.Header().Get("Set-Cookie"),
}
}
@@ -242,6 +280,31 @@ func (harness *registrationHarness) drain(ctx context.Context, t *testing.T) int
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()
requestCount := len(harness.fixture.Requests())
response := harness.registerBody(t, registrationBody(email, scenario, password, registrationC1), "")
requireAccepted(t, response)
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 for the registration, want one to the registered address", len(received))
}
link := verificationLinkToken.FindStringSubmatch(received[0].Text)
if link == nil {
t.Fatal("the received verification message has no token in its link fragment")
}
return link[1]
}
// 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.