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

@@ -0,0 +1,209 @@
//go:build integration
package integration_test
import (
"context"
"errors"
"testing"
"github.com/testcontainers/testcontainers-go"
)
const rootlessPortBindFailureMessage = "Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp4 0.0.0.0:32912: bind: address already in use"
type retryTestContainer struct {
testcontainers.Container
terminateCalls int
terminateErr error
}
func (container *retryTestContainer) Terminate(context.Context, ...testcontainers.TerminateOption) error {
container.terminateCalls++
return container.terminateErr
}
func TestIsRootlessPortBindFailure(t *testing.T) {
tests := []struct {
name string
err error
want bool
}{
{name: "rootless host port collision", err: errors.New(rootlessPortBindFailureMessage), want: true},
{name: "unrelated address collision", err: errors.New("listen tcp4 0.0.0.0:32912: bind: address already in use")},
{name: "rootless service bind failure", err: errors.New("Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp4 0.0.0.0:32912: bind: permission denied")},
{name: "rootless IPv6 bind failure", err: errors.New("Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint lincodex (0123456789abcdef): error while calling RootlessKit PortManager.AddPort(): listen tcp6 [::]:32912: bind: address already in use")},
{name: "nil error", err: nil},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := isRootlessPortBindFailure(test.err); got != test.want {
t.Fatalf("isRootlessPortBindFailure(%v) = %t, want %t", test.err, got, test.want)
}
})
}
}
func TestStartWithRootlessPortRetryCleansPartialContainer(t *testing.T) {
first := &retryTestContainer{}
second := &retryTestContainer{}
attempts := 0
container, err := startWithRootlessPortRetry(
context.Background(),
func(context.Context) (testcontainers.Container, error) {
attempts++
if attempts == 1 {
return first, errors.New(rootlessPortBindFailureMessage)
}
return second, nil
},
func(ctx context.Context, container testcontainers.Container) error {
return container.Terminate(ctx)
},
)
if err != nil {
t.Fatalf("startWithRootlessPortRetry() error = %v", err)
}
if container != second {
t.Fatalf("startWithRootlessPortRetry() container = %v, want second container", container)
}
if attempts != 2 {
t.Fatalf("start attempts = %d, want 2", attempts)
}
if first.terminateCalls != 1 {
t.Fatalf("first container cleanup calls = %d, want 1", first.terminateCalls)
}
if second.terminateCalls != 0 {
t.Fatalf("successful container cleanup calls = %d, want 0", second.terminateCalls)
}
}
func TestStartWithRootlessPortRetryStopsAtLimit(t *testing.T) {
startErr := errors.New(rootlessPortBindFailureMessage)
attempts := 0
containers := make([]*retryTestContainer, 0, rootlessPortStartLimit)
container, err := startWithRootlessPortRetry(
context.Background(),
func(context.Context) (testcontainers.Container, error) {
attempts++
partial := &retryTestContainer{}
containers = append(containers, partial)
return partial, startErr
},
func(ctx context.Context, container testcontainers.Container) error {
return container.Terminate(ctx)
},
)
if err == nil {
t.Fatal("startWithRootlessPortRetry() error = nil, want attempt limit error")
}
if !errors.Is(err, startErr) {
t.Fatalf("startWithRootlessPortRetry() error = %v, want startup cause", err)
}
if container != containers[len(containers)-1] {
t.Fatalf("startWithRootlessPortRetry() container = %v, want final partial container", container)
}
if attempts != rootlessPortStartLimit {
t.Fatalf("start attempts = %d, want %d", attempts, rootlessPortStartLimit)
}
for index, partial := range containers[:len(containers)-1] {
if partial.terminateCalls != 1 {
t.Fatalf("retried container %d cleanup calls = %d, want 1", index, partial.terminateCalls)
}
}
final := containers[len(containers)-1]
if final.terminateCalls != 0 {
t.Fatalf("final container cleanup calls = %d, want caller-owned cleanup", final.terminateCalls)
}
if err := final.Terminate(context.Background()); err != nil {
t.Fatalf("caller cleanup of final container: %v", err)
}
if final.terminateCalls != 1 {
t.Fatalf("final container cleanup calls after caller cleanup = %d, want 1", final.terminateCalls)
}
}
func TestStartWithRootlessPortRetryPreservesCleanupFailure(t *testing.T) {
startErr := errors.New(rootlessPortBindFailureMessage)
cleanupErr := errors.New("container remove failed")
partial := &retryTestContainer{}
attempts := 0
container, err := startWithRootlessPortRetry(
context.Background(),
func(context.Context) (testcontainers.Container, error) {
attempts++
return partial, startErr
},
func(context.Context, testcontainers.Container) error {
return cleanupErr
},
)
if !errors.Is(err, startErr) || !errors.Is(err, cleanupErr) {
t.Fatalf("startWithRootlessPortRetry() error = %v, want start and cleanup causes", err)
}
if container != partial {
t.Fatalf("startWithRootlessPortRetry() container = %v, want partial container for final cleanup", container)
}
if attempts != 1 {
t.Fatalf("start attempts = %d, want 1 after cleanup failure", attempts)
}
}
func TestStartWithRootlessPortRetryDoesNotRetryStartupFailure(t *testing.T) {
startErr := errors.New("service readiness failed")
partial := &retryTestContainer{}
attempts := 0
container, err := startWithRootlessPortRetry(
context.Background(),
func(context.Context) (testcontainers.Container, error) {
attempts++
return partial, startErr
},
func(ctx context.Context, container testcontainers.Container) error {
return container.Terminate(ctx)
},
)
if !errors.Is(err, startErr) {
t.Fatalf("startWithRootlessPortRetry() error = %v, want startup error", err)
}
if container != partial {
t.Fatalf("startWithRootlessPortRetry() container = %v, want partial container for caller cleanup", container)
}
if attempts != 1 {
t.Fatalf("start attempts = %d, want 1", attempts)
}
if partial.terminateCalls != 0 {
t.Fatalf("partial container cleanup calls = %d, want caller-owned cleanup", partial.terminateCalls)
}
}
func TestStartWithRootlessPortRetryStopsWhenContextIsCanceled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
startErr := errors.New(rootlessPortBindFailureMessage)
partial := &retryTestContainer{}
attempts := 0
container, err := startWithRootlessPortRetry(
ctx,
func(context.Context) (testcontainers.Container, error) {
attempts++
cancel()
return partial, startErr
},
func(ctx context.Context, container testcontainers.Container) error {
return container.Terminate(ctx)
},
)
if !errors.Is(err, context.Canceled) || !errors.Is(err, startErr) {
t.Fatalf("startWithRootlessPortRetry() error = %v, want cancellation and startup cause", err)
}
if container != nil {
t.Fatalf("startWithRootlessPortRetry() container = %v, want nil after cleanup", container)
}
if attempts != 1 {
t.Fatalf("start attempts = %d, want 1", attempts)
}
if partial.terminateCalls != 1 {
t.Fatalf("partial container cleanup calls = %d, want 1", partial.terminateCalls)
}
}
+140 -61
View File
@@ -7,9 +7,11 @@ import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"regexp"
"strings"
"testing"
"time"
@@ -47,6 +49,7 @@ const (
cleanupTimeout = 30 * time.Second
stopTimeout = 15 * time.Second
shutdownTimeout = 5 * time.Second
rootlessPortStartLimit = 3
seaweedfsStartupTimeout = time.Minute
storageReadyTimeout = 30 * time.Second
readinessInterval = 100 * time.Millisecond
@@ -74,6 +77,8 @@ const (
kafkaClusterIDSize = 16
)
var rootlessPortBindFailure = regexp.MustCompile(`Error response from daemon: failed to set up container networking: driver failed programming external connectivity on endpoint [^\s]+ \([^)]*\): error while calling RootlessKit PortManager\.AddPort\(\): listen tcp4 0\.0\.0\.0:[1-9][0-9]{0,4}: bind: address already in use$`)
type service uint8
const (
@@ -181,6 +186,64 @@ func (env *testEnvironment) cleanupContainer(ctx context.Context, container test
})
}
// startWithRootlessPortRetry retries only the daemon's rootless host-port bind
// collision. Docker reports this remote failure as text rather than syscall.Errno.
func startWithRootlessPortRetry(
ctx context.Context,
start func(context.Context) (testcontainers.Container, error),
terminate func(context.Context, testcontainers.Container) error,
) (testcontainers.Container, error) {
for attempt := 1; attempt <= rootlessPortStartLimit; attempt++ {
container, err := start(ctx)
if err == nil {
return container, nil
}
if attempt == rootlessPortStartLimit || !isRootlessPortBindFailure(err) {
return container, fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err)
}
if container != nil {
if cleanupErr := terminateFailedStart(ctx, container, terminate); cleanupErr != nil {
return container, errors.Join(
fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err),
fmt.Errorf("integration_test.startWithRootlessPortRetry - clean up failed container: %w", cleanupErr),
)
}
}
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, errors.Join(
fmt.Errorf("integration_test.startWithRootlessPortRetry - start attempt %d: %w", attempt, err),
fmt.Errorf("integration_test.startWithRootlessPortRetry - retry canceled: %w", ctxErr),
)
}
}
return nil, errors.New("integration_test.startWithRootlessPortRetry - attempt limit reached")
}
func terminateFailedStart(
ctx context.Context,
container testcontainers.Container,
terminate func(context.Context, testcontainers.Container) error,
) error {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
defer cancel()
return terminate(cleanupCtx, container)
}
func terminateTestContainer(ctx context.Context, container testcontainers.Container) error {
return testcontainers.TerminateContainer(
container,
testcontainers.StopContext(ctx),
testcontainers.StopTimeout(shutdownTimeout),
)
}
func isRootlessPortBindFailure(err error) bool {
return err != nil && rootlessPortBindFailure.MatchString(err.Error())
}
// logContainerTail prints the end of a container log after a failed start,
// so a startup timeout shows what the service was doing.
func logContainerTail(ctx context.Context, t *testing.T, container testcontainers.Container, name string) {
@@ -208,17 +271,27 @@ func logContainerTail(ctx context.Context, t *testing.T, container testcontainer
func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) {
t.Helper()
container, err := postgres.Run(ctx, postgresImage,
postgres.WithDatabase(postgresDatabase),
postgres.WithUsername(postgresUser),
postgres.WithPassword(postgresPassword),
postgres.BasicWaitStrategies(),
)
container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) {
postgresContainer, err := postgres.Run(ctx, postgresImage,
postgres.WithDatabase(postgresDatabase),
postgres.WithUsername(postgresUser),
postgres.WithPassword(postgresPassword),
postgres.BasicWaitStrategies(),
)
if postgresContainer == nil {
return nil, err
}
return postgresContainer, err
}, terminateTestContainer)
env.cleanupContainer(ctx, container, "PostgreSQL")
if err != nil {
t.Fatalf("start PostgreSQL container: %v", err)
}
databaseURL, err := container.ConnectionString(ctx, "sslmode=disable")
postgresContainer, ok := container.(*postgres.PostgresContainer)
if !ok {
t.Fatalf("start PostgreSQL container: unexpected container type %T", container)
}
databaseURL, err := postgresContainer.ConnectionString(ctx, "sslmode=disable")
if err != nil {
t.Fatalf("get PostgreSQL connection string: %v", err)
}
@@ -237,15 +310,17 @@ func (env *testEnvironment) startPostgres(ctx context.Context, t *testing.T) {
func (env *testEnvironment) startRedis(ctx context.Context, t *testing.T) {
t.Helper()
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: redisImage,
ExposedPorts: []string{"6379/tcp"},
Cmd: []string{"redis-server", "--requirepass", env.Config.RedisPassword, "--save", "", "--appendonly", "no"},
WaitingFor: wait.ForLog("Ready to accept connections"),
},
Started: true,
})
container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) {
return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: redisImage,
ExposedPorts: []string{"6379/tcp"},
Cmd: []string{"redis-server", "--requirepass", env.Config.RedisPassword, "--save", "", "--appendonly", "no"},
WaitingFor: wait.ForLog("Ready to accept connections"),
},
Started: true,
})
}, terminateTestContainer)
env.cleanupContainer(ctx, container, "Redis")
if err != nil {
t.Fatalf("start Redis container: %v", err)
@@ -300,29 +375,31 @@ func (env *testEnvironment) prepareStorageVolume() {
func (env *testEnvironment) startSeaweedFS(ctx context.Context, t *testing.T) {
t.Helper()
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: seaweedfsImage,
// Only the S3 port is used by the adapter. The internal ports are
// published so tests can prove they refuse unauthenticated access.
ExposedPorts: []string{seaweedfsS3Port, seaweedfsFilerPort, seaweedfsMasterPort, seaweedfsVolumePort},
Entrypoint: seaweedfsEntrypoint,
Env: map[string]string{
"AWS_ACCESS_KEY_ID": env.Config.SeaweedFSAccessKey,
"AWS_SECRET_ACCESS_KEY": env.Config.SeaweedFSSecretKey,
"S3_BUCKET": env.Config.SeaweedFSBucket,
container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) {
return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: seaweedfsImage,
// Only the S3 port is used by the adapter. The internal ports are
// published so tests can prove they refuse unauthenticated access.
ExposedPorts: []string{seaweedfsS3Port, seaweedfsFilerPort, seaweedfsMasterPort, seaweedfsVolumePort},
Entrypoint: seaweedfsEntrypoint,
Env: map[string]string{
"AWS_ACCESS_KEY_ID": env.Config.SeaweedFSAccessKey,
"AWS_SECRET_ACCESS_KEY": env.Config.SeaweedFSSecretKey,
"S3_BUCKET": env.Config.SeaweedFSBucket,
},
Cmd: []string{
"mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0", "-whiteList=127.0.0.1,@",
"-webdav=false", "-admin.ui=false", "-s3.iam=false",
"-s3.port.iceberg=0", "-s3.port.lance=0", "-s3.autoCreateBucket=false",
"-s3.allowDeleteBucketNotEmpty=false", "-master.telemetry=false",
},
Mounts: testcontainers.ContainerMounts{testcontainers.VolumeMount(env.seaweedfsVolume, "/data")},
WaitingFor: wait.ForHTTP("/healthz").WithPort(seaweedfsS3Port).WithStartupTimeout(seaweedfsStartupTimeout),
},
Cmd: []string{
"mini", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=0.0.0.0", "-whiteList=127.0.0.1,@",
"-webdav=false", "-admin.ui=false", "-s3.iam=false",
"-s3.port.iceberg=0", "-s3.port.lance=0", "-s3.autoCreateBucket=false",
"-s3.allowDeleteBucketNotEmpty=false", "-master.telemetry=false",
},
Mounts: testcontainers.ContainerMounts{testcontainers.VolumeMount(env.seaweedfsVolume, "/data")},
WaitingFor: wait.ForHTTP("/healthz").WithPort(seaweedfsS3Port).WithStartupTimeout(seaweedfsStartupTimeout),
},
Started: true,
})
Started: true,
})
}, terminateTestContainer)
env.cleanupContainer(ctx, container, "SeaweedFS")
if err != nil {
t.Fatalf("start SeaweedFS container: %v", err)
@@ -404,30 +481,32 @@ func (env *testEnvironment) startKafka(ctx context.Context, t *testing.T) {
if _, err := rand.Read(clusterID); err != nil {
t.Fatalf("generate Kafka cluster ID: %v", err)
}
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: kafkaImage,
ExposedPorts: []string{kafkaClientPort},
Env: kafkaEnvironment(base64.RawURLEncoding.EncodeToString(clusterID)),
// The advertised client address contains the host port, which is
// known only after the container starts.
Entrypoint: []string{"sh", "-c", "while [ ! -s " + kafkaListenersFile + " ]; do sleep 0.1; done; " +
"KAFKA_ADVERTISED_LISTENERS=\"$(cat " + kafkaListenersFile + ")\" exec /__cacert_entrypoint.sh /etc/kafka/docker/run"},
// The image declares these paths as volumes. Compose keeps data in a
// named volume; a test broker needs no persistence, so tmpfs for all
// three leaves no anonymous volumes behind.
Tmpfs: map[string]string{
"/var/lib/kafka/data": "rw,size=256m,mode=1777",
"/etc/kafka/secrets": "rw,size=1m,mode=0755",
"/mnt/shared/config": "rw,size=1m,mode=0755",
container, err := startWithRootlessPortRetry(ctx, func(ctx context.Context) (testcontainers.Container, error) {
return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: kafkaImage,
ExposedPorts: []string{kafkaClientPort},
Env: kafkaEnvironment(base64.RawURLEncoding.EncodeToString(clusterID)),
// The advertised client address contains the host port, which is
// known only after the container starts.
Entrypoint: []string{"sh", "-c", "while [ ! -s " + kafkaListenersFile + " ]; do sleep 0.1; done; " +
"KAFKA_ADVERTISED_LISTENERS=\"$(cat " + kafkaListenersFile + ")\" exec /__cacert_entrypoint.sh /etc/kafka/docker/run"},
// The image declares these paths as volumes. Compose keeps data in a
// named volume; a test broker needs no persistence, so tmpfs for all
// three leaves no anonymous volumes behind.
Tmpfs: map[string]string{
"/var/lib/kafka/data": "rw,size=256m,mode=1777",
"/etc/kafka/secrets": "rw,size=1m,mode=0755",
"/mnt/shared/config": "rw,size=1m,mode=0755",
},
LifecycleHooks: []testcontainers.ContainerLifecycleHooks{{
PostStarts: []testcontainers.ContainerHook{advertiseKafkaListeners},
}},
WaitingFor: wait.ForLog("Kafka Server started").WithStartupTimeout(kafkaStartupTimeout),
},
LifecycleHooks: []testcontainers.ContainerLifecycleHooks{{
PostStarts: []testcontainers.ContainerHook{advertiseKafkaListeners},
}},
WaitingFor: wait.ForLog("Kafka Server started").WithStartupTimeout(kafkaStartupTimeout),
},
Started: true,
})
Started: true,
})
}, terminateTestContainer)
env.cleanupContainer(ctx, container, "Kafka")
if err != nil {
logContainerTail(ctx, t, container, "Kafka")
@@ -373,7 +373,8 @@ func TestConsentLedger(t *testing.T) {
{"C4 with a repeated field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"email", "email"}, nil), consentCheckViolation, "consent_records_c4_scope"},
{"C4 with an unknown field", insert("c4", "c4-2026-10-01", publicationHash[:], "invitation_acceptance", &organization, []string{"address"}, nil), consentCheckViolation, "consent_records_c4_scope"},
{"C2 with a scope", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", &organization, []string{"email"}, nil), consentCheckViolation, "consent_records_c4_scope"},
{"C2 from the registration", insert("c2", "c2-2026-10-01", publicationHash[:], "registration", nil, nil, nil), consentCheckViolation, "consent_records_source_of_purpose"},
{"C2 from the registration", insert("c2", "c2-2026-10-01", publicationHash[:], "registration", nil, nil, nil), consentCheckViolation, "consent_records_registration_version"},
{"C2 from an invitation", insert("c2", "c2-2026-10-01", publicationHash[:], "invitation_acceptance", nil, nil, nil), consentCheckViolation, "consent_records_source_of_purpose"},
{"revocation without a source", insert("c2", "c2-2026-10-01", publicationHash[:], "consent_settings", nil, nil, &empty), consentCheckViolation, "consent_records_revocation_stamp"},
{"hash of another text", insert("c3", "c3-2026-10-01", publicationHash[:], "consent_settings", nil, nil, nil), consentForeignKeyViolation, "consent_records_published_text_fkey"},
} {
@@ -658,11 +659,14 @@ func TestConsentLedger(t *testing.T) {
t.Fatalf("ReRegister() error = %v", err)
}
var replacement domain.ConsentRecord
var registered domain.User
err = fixture.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
if _, err := unit.Users().UpdateRegistration(ctx, changed); err != nil {
var err error
registered, err = unit.Users().UpdateRegistration(ctx, changed)
if err != nil {
return err
}
grant := fixture.newGrant(t, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now)
grant := fixture.newGrant(t, first.ID, domain.ConsentPurposePersonalData, "c1-2026-10-01", domain.ConsentSourceRegistration, now, registered.RegistrationVersion)
var created bool
replacement, created, err = unit.ConsentLedger().Grant(ctx, grant)
if err == nil && !created {
@@ -678,6 +682,9 @@ func TestConsentLedger(t *testing.T) {
if replacement.ID() == earlier.ID() {
t.Fatal("the earlier registrant's C1 survived the re-registration")
}
if replacement.RegistrationVersion() != registered.RegistrationVersion {
t.Fatalf("replacement C1 registration version = %d, want %d", replacement.RegistrationVersion(), registered.RegistrationVersion)
}
// A stale re-registration changes nothing and deletes nothing.
if _, err := fixture.identity.store.Users().UpdateRegistration(ctx, changed); !errors.Is(err, outbound.ErrUserVersionConflict) {
@@ -836,14 +843,26 @@ func (fixture consentFixture) newGrant(
version domain.ConsentTextVersion,
source domain.ConsentSource,
at time.Time,
registrationVersions ...int64,
) domain.ConsentGrant {
t.Helper()
registrationVersion := int64(0)
if source == domain.ConsentSourceRegistration {
registrationVersion = 1
}
if len(registrationVersions) > 1 {
t.Fatal("newGrant received more than one registration version")
}
if len(registrationVersions) == 1 {
registrationVersion = registrationVersions[0]
}
text, err := fixture.store.ConsentTexts().Get(fixture.ctx, purpose, version)
if err != nil {
t.Fatalf("ConsentTexts().Get(%s, %s) error = %v", purpose, version, err)
}
grant, err := domain.NewConsentGrant(domain.ConsentGrantInput{
SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(), Source: source, GrantedAt: at,
SubjectID: subject, Purpose: purpose, TextVersion: text.Version(), TextHash: text.Hash(),
Source: source, RegistrationVersion: registrationVersion, GrantedAt: at,
})
if err != nil {
t.Fatalf("NewConsentGrant() error = %v", err)
@@ -66,12 +66,12 @@ func (fixture consentGrantsFixture) grantInput(t *testing.T, subject uuid.UUID,
// registerC1 records the registration C1 of an existing account in its own
// transaction.
func (fixture consentGrantsFixture) registerC1(t *testing.T, subject uuid.UUID) domain.ConsentRecord {
func (fixture consentGrantsFixture) registerC1(t *testing.T, user domain.User) domain.ConsentRecord {
t.Helper()
var result consent.GrantResult
err := fixture.transactor.WithinTransaction(fixture.ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
result, err = fixture.service.GrantAtRegistration(ctx, unit, subject, fixture.currentVersion(t, domain.ConsentPurposePersonalData))
result, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, fixture.currentVersion(t, domain.ConsentPurposePersonalData))
return err
})
if err != nil || !result.Created {
@@ -170,7 +170,7 @@ func TestConsentGrants(t *testing.T) {
return err
}
var err error
registered, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, c1)
registered, err = fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, c1)
return err
})
if err != nil || !registered.Created {
@@ -180,6 +180,7 @@ func TestConsentGrants(t *testing.T) {
assertRowCount(ctx, t, pool, sessionsTable, 0)
assertRowCount(ctx, t, pool, consentRecordsTable, 1)
if record := registered.Record; record.SubjectID() != user.ID || record.Source() != domain.ConsentSourceRegistration ||
record.RegistrationVersion() != user.RegistrationVersion ||
record.TextVersion() != consentSecondC1Version || !record.GrantedAt().Equal(start) {
t.Fatalf("registration C1 = %s %s %v, want the current text at the application time", record.Source(), record.TextVersion(), record.GrantedAt())
}
@@ -228,7 +229,7 @@ func TestConsentGrants(t *testing.T) {
if err := unit.Users().Create(ctx, user); err != nil {
return err
}
if _, err := fixture.service.GrantAtRegistration(ctx, unit, user.ID, c1); err != nil {
if _, err := fixture.service.GrantAtRegistration(ctx, unit, user.ID, user.RegistrationVersion, c1); err != nil {
return err
}
return errForcedRollback
@@ -242,7 +243,7 @@ func TestConsentGrants(t *testing.T) {
// A grant for a subject that has no account is refused by the ledger
// and stores nothing.
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
_, err := fixture.service.GrantAtRegistration(ctx, unit, uuid.New(), c1)
_, err := fixture.service.GrantAtRegistration(ctx, unit, uuid.New(), 1, c1)
return err
})
if !errors.Is(err, outbound.ErrUserNotFound) {
@@ -379,30 +380,31 @@ func TestConsentGrants(t *testing.T) {
reregister := func(t *testing.T, rawEmail string, grantFirst bool) (granted consent.GrantResult, earlier domain.ConsentRecord) {
t.Helper()
first := fixture.identity.createUser(t, rawEmail, domain.ScenarioCandidate, start.Add(-72*time.Hour))
earlier = fixture.registerC1(t, first.ID)
earlier = fixture.registerC1(t, first)
changed, err := first.ReRegister(fixture.identity.registration(t, rawEmail, domain.ScenarioEmployer, start))
if err != nil {
t.Fatalf("ReRegister() error = %v", err)
}
version := fixture.currentVersion(t, domain.ConsentPurposePersonalData)
err = transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
grant := func() error {
grant := func(registrationVersion int64) error {
var err error
granted, err = fixture.service.GrantAtRegistration(ctx, unit, first.ID, version)
granted, err = fixture.service.GrantAtRegistration(ctx, unit, first.ID, registrationVersion, version)
return err
}
if grantFirst {
if err := grant(); err != nil {
if err := grant(first.RegistrationVersion); err != nil {
return err
}
}
if _, err := unit.Users().UpdateRegistration(ctx, changed); err != nil {
registered, err := unit.Users().UpdateRegistration(ctx, changed)
if err != nil {
return err
}
if grantFirst {
return nil
}
return grant()
return grant(registered.RegistrationVersion)
})
if err != nil {
t.Fatalf("re-registration transaction error = %v", err)
@@ -498,7 +500,7 @@ func TestConsentGrants(t *testing.T) {
reset(t)
user := fixture.identity.createUser(t, "restart@example.com", domain.ScenarioCandidate, start.Add(-72*time.Hour))
grantedAt := map[uuid.UUID]time.Time{}
c1 := fixture.registerC1(t, user.ID)
c1 := fixture.registerC1(t, user)
grantedAt[c1.ID()] = fixture.now()
fixture.advance(time.Minute)
c2 := fixture.grant(t, fixture.grantInput(t, user.ID, domain.ConsentPurposePublication))
@@ -0,0 +1,677 @@
//go:build integration
package integration_test
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"mime"
"net/http"
"strconv"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5"
)
const (
confirmationTestTimeout = 5 * time.Minute
confirmationRetryWindow = time.Hour
confirmationSecondPassword = "another correct horse battery staple"
confirmationWrongPassword = "this is the wrong password"
confirmationUnknownToken = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
confirmationFailureFunction = "integration_reject_email_confirmation"
confirmationFailureTrigger = "integration_reject_email_confirmation_event"
)
type confirmationState struct {
scenario string
onboardingStep string
passwordHash string
emailVerifiedAt *time.Time
registrationVersion int64
userVersion int64
tokenRegistrationVersion int64
tokenConsumedAt *time.Time
tokenInvalidatedAt *time.Time
pendingPasswordHash *string
pendingScenario *string
pendingOnboardingStep *string
c1RegistrationVersion *int64
tokenCount int
sessionCount int
confirmationEventCount int
}
func TestEmailVerificationOverHTTP(t *testing.T) {
env := bootstrap(t, postgresService, redisService)
ctx, cancel := context.WithTimeout(t.Context(), confirmationTestTimeout)
defer cancel()
harness := newRegistrationHarness(ctx, t, env, 1000)
reset := func(t *testing.T) {
t.Helper()
harness.truncate(ctx, t)
harness.clock.Set(harness.start)
}
publicOrigin := env.Config.AppPublicURL
t.Run("a candidate and employer confirm the registration received by mail", func(t *testing.T) {
for _, test := range []struct {
name string
email string
scenario string
step string
}{
{name: "candidate", email: "confirm.candidate@example.com", scenario: "candidate", step: "candidate_consents"},
{name: "employer", email: "confirm.employer@example.com", scenario: "employer", step: "employer_company"},
} {
t.Run(test.name, func(t *testing.T) {
reset(t)
token := harness.registerAndSendVerification(ctx, t, test.email, test.scenario, registrationPassword)
before := readConfirmationState(ctx, t, harness, test.email, token)
if before.pendingPasswordHash == nil || before.c1RegistrationVersion == nil ||
*before.c1RegistrationVersion != before.tokenRegistrationVersion {
t.Fatal("registration did not bind its C1 record and pending password to the emailed token")
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireConfirmationSuccess(t, response, test.scenario, test.step)
after := readConfirmationState(ctx, t, harness, test.email, token)
assertConfirmationApplied(t, before, after, test.scenario, test.step)
assertSingleConfirmationEvent(ctx, t, harness, test.email)
if after.sessionCount != 0 {
t.Fatalf("confirmation created %d sessions, want none", after.sessionCount)
}
harness.assertLogsHoldNoSecrets(t, test.email, registrationPassword, token)
// A consumed link cannot be replayed and leaves the committed account alone.
replay := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, replay, http.StatusBadRequest, "verification_token_invalid")
if replay.setCookie != "" || !sameConfirmationState(after, readConfirmationState(ctx, t, harness, test.email, token)) {
t.Fatal("replaying a consumed token changed the account or set a cookie")
}
})
}
})
t.Run("an unknown token is refused without creating identity state", func(t *testing.T) {
reset(t)
response := harness.confirm(t, confirmationUnknownToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.retryAfter != "" || response.setCookie != "" ||
harness.count(ctx, t, `SELECT count(*) FROM users`) != 0 ||
harness.count(ctx, t, `SELECT count(*) FROM email_tokens`) != 0 ||
harness.count(ctx, t, `SELECT count(*) FROM sessions`) != 0 ||
harness.count(ctx, t, `SELECT count(*) FROM outbox_events WHERE event_type = 'identity.email_verified'`) != 0 {
t.Fatal("an unknown token changed identity state or returned rate-limit/session headers")
}
harness.assertLogsHoldNoSecrets(t, confirmationUnknownToken, registrationPassword)
})
t.Run("an expired token remains unconsumed", func(t *testing.T) {
reset(t)
const email = "confirm.expired@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
expiresAt := tokenExpiresAt(ctx, t, harness, token)
harness.clock.Set(expiresAt.Add(time.Second))
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_expired")
if response.retryAfter != "" || response.setCookie != "" ||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("an expired token changed the account or returned rate-limit/session headers")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("an expired active token from an earlier registration version is invalid", func(t *testing.T) {
reset(t)
const email = "confirm.stale-active-version@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
hash := sha256.Sum256([]byte(token))
deadline := harness.clock.Now().Add(time.Second)
harness.exec(ctx, t, `UPDATE email_tokens SET expires_at = $1 WHERE token_hash = $2`, deadline, hash[:])
harness.clock.Set(deadline.Add(time.Second))
harness.exec(ctx, t, `UPDATE users SET registration_version = registration_version + 1, version = version + 1, updated_at = $1 WHERE email_normalized = $2`,
harness.clock.Now(), strings.ToLower(email))
before := readConfirmationState(ctx, t, harness, email, token)
if before.tokenInvalidatedAt != nil || before.pendingPasswordHash == nil ||
before.registrationVersion == before.tokenRegistrationVersion || !deadline.Before(harness.clock.Now()) {
t.Fatal("fixture does not contain an expired, active token for an earlier account version")
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.retryAfter != "" || response.setCookie != "" ||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("an expired active token from an earlier account version changed identity state")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("expiry is checked after confirmation waits for token, consent, or user locks", func(t *testing.T) {
for _, target := range []struct {
name string
query string
}{
{name: "token", query: `SELECT 1 FROM email_tokens WHERE token_hash = $1 FOR UPDATE`},
{name: "registration consent", query: `
SELECT 1 FROM consent_records AS consent
JOIN users AS account ON account.id = consent.subject_id
WHERE account.email_normalized = $1 AND consent.purpose = 'c1'
AND consent.source = 'registration' AND consent.revoked_at IS NULL
FOR UPDATE OF consent`},
{name: "user", query: `SELECT 1 FROM users WHERE email_normalized = $1 FOR UPDATE`},
} {
t.Run(target.name, func(t *testing.T) {
reset(t)
email := "confirm.lock-expiry-" + strings.ReplaceAll(target.name, " ", "-") + "@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
expiresAt := tokenExpiresAt(ctx, t, harness, token)
monitorPool := env.newPool(ctx, t)
holder, err := harness.pool.Begin(ctx)
if err != nil {
t.Fatalf("begin %s lock: %v", target.name, err)
}
defer func() {
if err := holder.Rollback(context.WithoutCancel(ctx)); err != nil && !errors.Is(err, pgx.ErrTxClosed) {
t.Errorf("release %s lock: %v", target.name, err)
}
}()
var lockKey any = strings.ToLower(email)
if target.name == "token" {
hash := sha256.Sum256([]byte(token))
lockKey = hash[:]
}
var locked int
if err := holder.QueryRow(ctx, target.query, lockKey).Scan(&locked); err != nil {
t.Fatalf("lock the emailed %s row: %v", target.name, err)
}
type confirmationReply struct{ response registrationResponse }
reply := make(chan confirmationReply, 1)
go func() {
reply <- confirmationReply{response: harness.confirm(t, token, registrationPassword, &publicOrigin)}
}()
waitEvent, observed := waitForLockWait(ctx, monitorPool, registrationApplication)
if !observed {
_ = holder.Rollback(context.WithoutCancel(ctx))
<-reply
t.Fatalf("confirmation did not wait on the %s row lock (last wait event %q)", target.name, waitEvent)
}
harness.clock.Set(expiresAt.Add(time.Second))
if err := holder.Commit(ctx); err != nil {
t.Fatalf("release the %s lock: %v", target.name, err)
}
response := (<-reply).response
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_expired")
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatalf("a request queued on the %s lock consumed the token after its deadline", target.name)
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
}
})
t.Run("missing, null, and foreign Origin values are rejected without consuming the token", func(t *testing.T) {
reset(t)
const email = "confirm.origin@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
for _, test := range []struct {
name string
origin *string
}{
{name: "missing"},
{name: "null", origin: stringPointer("null")},
{name: "foreign", origin: stringPointer("https://foreign.example")},
} {
t.Run(test.name, func(t *testing.T) {
response := harness.confirm(t, token, registrationPassword, test.origin)
requireProblemStatus(t, response, http.StatusForbidden, "csrf_check_failed")
if response.retryAfter != "" || response.setCookie != "" ||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("an invalid Origin changed the account or returned rate-limit/session headers")
}
})
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("the second registrant confirms only with its own password and token", func(t *testing.T) {
reset(t)
const email = "confirm.replaced@example.com"
firstToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
firstHash := sha256.Sum256([]byte(firstToken))
firstDeadline := harness.clock.Now().Add(time.Second)
harness.exec(ctx, t, `UPDATE email_tokens SET expires_at = $1 WHERE token_hash = $2`, firstDeadline, firstHash[:])
harness.clock.Set(firstDeadline.Add(time.Second))
time.Sleep(registrationMinInterval + 100*time.Millisecond)
secondToken := harness.registerAndSendVerification(ctx, t, email, "employer", confirmationSecondPassword)
oldBefore := readConfirmationState(ctx, t, harness, email, firstToken)
if oldBefore.tokenInvalidatedAt == nil || oldBefore.pendingPasswordHash != nil {
t.Fatal("re-registration did not invalidate the old token and clear its pending credentials")
}
old := harness.confirm(t, firstToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, old, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(oldBefore, readConfirmationState(ctx, t, harness, email, firstToken)) {
t.Fatal("an expired token from a replaced registration changed account or token rows")
}
currentBefore := readConfirmationState(ctx, t, harness, email, secondToken)
wrong := harness.confirm(t, secondToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, wrong, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(currentBefore, readConfirmationState(ctx, t, harness, email, secondToken)) {
t.Fatal("a wrong password consumed the current token or changed the account")
}
accepted := harness.confirm(t, secondToken, confirmationSecondPassword, &publicOrigin)
requireConfirmationSuccess(t, accepted, "employer", "employer_company")
after := readConfirmationState(ctx, t, harness, email, secondToken)
assertConfirmationApplied(t, currentBefore, after, "employer", "employer_company")
assertSingleConfirmationEvent(ctx, t, harness, email)
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationSecondPassword, firstToken, secondToken)
})
t.Run("the original registrant can replace a second registrant before confirmation", func(t *testing.T) {
reset(t)
const email = "confirm.owner-first@example.com"
firstToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
time.Sleep(registrationMinInterval + 100*time.Millisecond)
secondToken := harness.registerAndSendVerification(ctx, t, email, "employer", confirmationSecondPassword)
firstAfterReplacement := readConfirmationState(ctx, t, harness, email, firstToken)
if firstAfterReplacement.tokenInvalidatedAt == nil || firstAfterReplacement.pendingPasswordHash != nil {
t.Fatal("the second registration did not invalidate the original token and clear its pending credentials")
}
old := harness.confirm(t, firstToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, old, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(firstAfterReplacement, readConfirmationState(ctx, t, harness, email, firstToken)) {
t.Fatal("the original registrant's replaced token changed account or token rows")
}
secondBefore := readConfirmationState(ctx, t, harness, email, secondToken)
wrong := harness.confirm(t, secondToken, registrationPassword, &publicOrigin)
requireProblemStatus(t, wrong, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(secondBefore, readConfirmationState(ctx, t, harness, email, secondToken)) {
t.Fatal("the original password consumed the second registrant's token or changed the account")
}
time.Sleep(registrationMinInterval + 100*time.Millisecond)
harness.clock.Advance(registrationMinInterval + time.Second)
thirdToken := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
secondAfterReplacement := readConfirmationState(ctx, t, harness, email, secondToken)
if secondAfterReplacement.tokenInvalidatedAt == nil || secondAfterReplacement.pendingPasswordHash != nil {
t.Fatal("the original registrant's new registration did not invalidate the second token")
}
superseded := harness.confirm(t, secondToken, confirmationSecondPassword, &publicOrigin)
requireProblemStatus(t, superseded, http.StatusBadRequest, "verification_token_invalid")
if !sameConfirmationState(secondAfterReplacement, readConfirmationState(ctx, t, harness, email, secondToken)) {
t.Fatal("confirming the superseded second registration changed account or token rows")
}
thirdBefore := readConfirmationState(ctx, t, harness, email, thirdToken)
accepted := harness.confirm(t, thirdToken, registrationPassword, &publicOrigin)
requireConfirmationSuccess(t, accepted, "candidate", "candidate_consents")
after := readConfirmationState(ctx, t, harness, email, thirdToken)
assertConfirmationApplied(t, thirdBefore, after, "candidate", "candidate_consents")
assertSingleConfirmationEvent(ctx, t, harness, email)
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationSecondPassword, firstToken, secondToken, thirdToken)
})
t.Run("a confirmed registration stays current if another registration follows", func(t *testing.T) {
reset(t)
const email = "confirm.before-reregistration@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
confirmed := readConfirmationState(ctx, t, harness, email, token)
assertConfirmationApplied(t, before, confirmed, "candidate", "candidate_consents")
time.Sleep(registrationMinInterval + 100*time.Millisecond)
registrationResponse := harness.registerBody(t, registrationBody(email, "employer", confirmationSecondPassword, registrationC1), "")
requireAccepted(t, registrationResponse)
if registrationResponse.setCookie != "" || !sameConfirmationState(confirmed, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a registration after confirmation changed the verified account")
}
assertSingleConfirmationEvent(ctx, t, harness, email)
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token, confirmationSecondPassword)
})
t.Run("a token cannot use the C1 record of another registration version", func(t *testing.T) {
reset(t)
const email = "confirm.c1-version@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
if before.c1RegistrationVersion == nil || *before.c1RegistrationVersion != before.tokenRegistrationVersion {
t.Fatal("initial C1 record is not bound to the token registration version")
}
hash := sha256.Sum256([]byte(token))
harness.exec(ctx, t, `UPDATE users SET registration_version = registration_version + 1, version = version + 1, updated_at = $1 WHERE email_normalized = $2`,
harness.clock.Now().Add(time.Second), strings.ToLower(email))
harness.exec(ctx, t, `UPDATE email_tokens SET registration_version = registration_version + 1 WHERE token_hash = $1`, hash[:])
stale := readConfirmationState(ctx, t, harness, email, token)
if stale.registrationVersion != stale.tokenRegistrationVersion || stale.c1RegistrationVersion == nil ||
*stale.c1RegistrationVersion == stale.tokenRegistrationVersion {
t.Fatal("fixture did not create a token and account version newer than its C1 record")
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.setCookie != "" || !sameConfirmationState(stale, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a token without current-version C1 changed the account or token")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("a token without pending registration credentials cannot be confirmed", func(t *testing.T) {
reset(t)
const email = "confirm.no-pending@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
hash := sha256.Sum256([]byte(token))
harness.exec(ctx, t, `UPDATE email_tokens SET pending_password_hash = NULL, pending_scenario = NULL, pending_onboarding_step = NULL WHERE token_hash = $1`, hash[:])
before := readConfirmationState(ctx, t, harness, email, token)
if before.pendingPasswordHash != nil || before.pendingScenario != nil || before.pendingOnboardingStep != nil {
t.Fatal("test token still has pending registration data")
}
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a token without pending registration data changed the account or token")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("confirmation rate limits refusals and reports Retry-After", func(t *testing.T) {
reset(t)
const email = "confirm.rate-limit@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
for range 2 {
response := harness.confirm(t, token, confirmationWrongPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
if response.retryAfter != "" || response.setCookie != "" ||
!sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a refused password attempt changed identity state or returned rate-limit/session headers")
}
}
limited := harness.confirm(t, token, confirmationWrongPassword, &publicOrigin)
requireProblemStatus(t, limited, http.StatusTooManyRequests, "rate_limited")
requirePositiveRetryAfter(t, limited)
if limited.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a rate-limited confirmation changed identity state or set a cookie")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, confirmationWrongPassword, token)
})
t.Run("an outbox failure rolls back token consumption and account confirmation", func(t *testing.T) {
reset(t)
const email = "confirm.rollback@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
installConfirmationOutboxFailure(ctx, t, harness)
response := harness.confirm(t, token, registrationPassword, &publicOrigin)
requireProblemStatus(t, response, http.StatusInternalServerError, "internal")
if response.setCookie != "" || !sameConfirmationState(before, readConfirmationState(ctx, t, harness, email, token)) {
t.Fatal("a failed confirmation outbox insert did not roll back all account and token changes")
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
t.Run("two concurrent HTTP confirmations produce one success and one event", func(t *testing.T) {
reset(t)
const email = "confirm.concurrent@example.com"
token := harness.registerAndSendVerification(ctx, t, email, "candidate", registrationPassword)
before := readConfirmationState(ctx, t, harness, email, token)
responses := make([]registrationResponse, 2)
start := make(chan struct{})
finished := make(chan int, len(responses))
for index := range responses {
go func(index int) {
<-start
responses[index] = harness.confirm(t, token, registrationPassword, &publicOrigin)
finished <- index
}(index)
}
close(start)
<-finished
<-finished
successes := 0
refusals := 0
for _, response := range responses {
switch response.status {
case http.StatusOK:
successes++
requireConfirmationSuccess(t, response, "candidate", "candidate_consents")
case http.StatusBadRequest:
refusals++
requireProblemStatus(t, response, http.StatusBadRequest, "verification_token_invalid")
default:
t.Fatalf("concurrent confirmation returned status %d, want one success and one invalid-token refusal", response.status)
}
if response.setCookie != "" {
t.Fatal("confirmation set a cookie")
}
}
if successes != 1 || refusals != 1 {
t.Fatalf("concurrent confirmations had %d successes and %d refusals, want one each", successes, refusals)
}
after := readConfirmationState(ctx, t, harness, email, token)
assertConfirmationApplied(t, before, after, "candidate", "candidate_consents")
assertSingleConfirmationEvent(ctx, t, harness, email)
if after.sessionCount != 0 {
t.Fatalf("concurrent confirmation created %d sessions, want none", after.sessionCount)
}
harness.assertLogsHoldNoSecrets(t, email, registrationPassword, token)
})
}
func (harness *registrationHarness) confirm(t *testing.T, token, password string, origin *string) registrationResponse {
t.Helper()
headers := make(map[string]string)
if origin != nil {
headers["Origin"] = *origin
}
body, err := json.Marshal(struct {
Token string `json:"token"`
Password string `json:"password"`
}{Token: token, Password: password})
if err != nil {
t.Fatalf("encode confirmation request: %v", err)
}
return harness.post(t, emailVerificationPath, string(body), headers)
}
func readConfirmationState(ctx context.Context, t *testing.T, harness *registrationHarness, email, rawToken string) confirmationState {
t.Helper()
hash := sha256.Sum256([]byte(rawToken))
var state confirmationState
err := harness.pool.QueryRow(ctx, `
SELECT account.scenario, account.onboarding_step, account.password_hash,
account.email_verified_at, account.registration_version, account.version,
token.registration_version, token.consumed_at, token.invalidated_at,
token.pending_password_hash, token.pending_scenario, token.pending_onboarding_step,
consent.registration_version,
(SELECT count(*)::integer FROM email_tokens WHERE user_id = account.id),
(SELECT count(*)::integer FROM sessions WHERE user_id = account.id),
(SELECT count(*)::integer FROM outbox_events
WHERE aggregate_id = account.id AND event_type = 'identity.email_verified')
FROM users AS account
JOIN email_tokens AS token ON token.user_id = account.id AND token.token_hash = $1
LEFT JOIN LATERAL (
SELECT registration_version FROM consent_records
WHERE subject_id = account.id AND purpose = 'c1' AND source = 'registration' AND revoked_at IS NULL
ORDER BY granted_at DESC, id DESC LIMIT 1
) AS consent ON TRUE
WHERE account.email_normalized = $2`, hash[:], strings.ToLower(email)).Scan(
&state.scenario, &state.onboardingStep, &state.passwordHash,
&state.emailVerifiedAt, &state.registrationVersion, &state.userVersion,
&state.tokenRegistrationVersion, &state.tokenConsumedAt, &state.tokenInvalidatedAt,
&state.pendingPasswordHash, &state.pendingScenario, &state.pendingOnboardingStep,
&state.c1RegistrationVersion, &state.tokenCount, &state.sessionCount, &state.confirmationEventCount,
)
if err != nil {
t.Fatalf("read confirmation state: %v", err)
}
return state
}
func tokenExpiresAt(ctx context.Context, t *testing.T, harness *registrationHarness, rawToken string) time.Time {
t.Helper()
hash := sha256.Sum256([]byte(rawToken))
var expiresAt time.Time
if err := harness.pool.QueryRow(ctx, `SELECT expires_at FROM email_tokens WHERE token_hash = $1`, hash[:]).Scan(&expiresAt); err != nil {
t.Fatalf("read emailed token deadline: %v", err)
}
return expiresAt
}
func sameConfirmationState(left, right confirmationState) bool {
return left.scenario == right.scenario && left.onboardingStep == right.onboardingStep &&
left.passwordHash == right.passwordHash && sameOptionalTime(left.emailVerifiedAt, right.emailVerifiedAt) &&
left.registrationVersion == right.registrationVersion && left.userVersion == right.userVersion &&
left.tokenRegistrationVersion == right.tokenRegistrationVersion &&
sameOptionalTime(left.tokenConsumedAt, right.tokenConsumedAt) &&
sameOptionalTime(left.tokenInvalidatedAt, right.tokenInvalidatedAt) &&
sameOptionalString(left.pendingPasswordHash, right.pendingPasswordHash) &&
sameOptionalString(left.pendingScenario, right.pendingScenario) &&
sameOptionalString(left.pendingOnboardingStep, right.pendingOnboardingStep) &&
sameOptionalInt64(left.c1RegistrationVersion, right.c1RegistrationVersion) &&
left.tokenCount == right.tokenCount && left.sessionCount == right.sessionCount &&
left.confirmationEventCount == right.confirmationEventCount
}
func assertConfirmationApplied(t *testing.T, before, after confirmationState, scenario, step string) {
t.Helper()
if after.scenario != scenario || after.onboardingStep != step || after.emailVerifiedAt == nil ||
after.registrationVersion != before.tokenRegistrationVersion ||
after.userVersion != before.userVersion+1 || after.tokenConsumedAt == nil ||
after.tokenInvalidatedAt != nil || after.pendingPasswordHash != nil ||
after.pendingScenario != nil || after.pendingOnboardingStep != nil ||
after.c1RegistrationVersion == nil || *after.c1RegistrationVersion != after.tokenRegistrationVersion ||
before.pendingPasswordHash == nil || after.passwordHash != *before.pendingPasswordHash ||
after.tokenCount != before.tokenCount || after.sessionCount != 0 || after.confirmationEventCount != 1 {
t.Fatal("confirmation did not atomically apply the emailed registration and consume its token")
}
}
func assertSingleConfirmationEvent(ctx context.Context, t *testing.T, harness *registrationHarness, email string) {
t.Helper()
var userID string
if err := harness.pool.QueryRow(ctx, `SELECT id::text FROM users WHERE email_normalized = $1`, strings.ToLower(email)).Scan(&userID); err != nil {
t.Fatalf("read confirmed account ID: %v", err)
}
var count int
var eventType, aggregateType, aggregateID, payload string
var aggregateVersion int64
rows, err := harness.pool.Query(ctx, `SELECT event_type, aggregate_type, aggregate_id::text, aggregate_version, payload::text
FROM outbox_events WHERE event_type = 'identity.email_verified' AND aggregate_id = $1`, userID)
if err != nil {
t.Fatalf("read confirmation outbox event: %v", err)
}
for rows.Next() {
count++
if err := rows.Scan(&eventType, &aggregateType, &aggregateID, &aggregateVersion, &payload); err != nil {
rows.Close()
t.Fatalf("scan confirmation outbox event: %v", err)
}
}
if err := rows.Err(); err != nil {
rows.Close()
t.Fatalf("read confirmation outbox events: %v", err)
}
rows.Close()
var userVersion int64
if err := harness.pool.QueryRow(ctx, `SELECT version FROM users WHERE id = $1::uuid`, userID).Scan(&userVersion); err != nil {
t.Fatalf("read confirmed account version: %v", err)
}
if count != 1 || eventType != "identity.email_verified" || aggregateType != "user" ||
aggregateID != userID || aggregateVersion != userVersion || payload != "{}" {
t.Fatal("confirmation outbox event count or contents do not match the confirmed account")
}
}
func requireConfirmationSuccess(t *testing.T, response registrationResponse, scenario, step string) {
t.Helper()
want := fmt.Sprintf(`{"email_verified":true,"scenario":%q,"onboarding_step":%q}`, scenario, step)
mediaType, _, contentTypeErr := mime.ParseMediaType(response.contentType)
if response.status != http.StatusOK || response.body != want || contentTypeErr != nil || mediaType != "application/json" ||
response.setCookie != "" || response.retryAfter != "" {
t.Fatalf("confirmation response = %d %q (content type %q, Set-Cookie present %t, Retry-After %q), want 200 %q with JSON media type and no session or rate-limit headers",
response.status, response.body, response.contentType, response.setCookie != "", response.retryAfter, want)
}
}
func requirePositiveRetryAfter(t *testing.T, response registrationResponse) {
t.Helper()
seconds, err := strconv.Atoi(response.retryAfter)
if err != nil || seconds < 1 || seconds > int(confirmationRetryWindow/time.Second) {
t.Fatalf("Retry-After = %q, want 1 to %d seconds", response.retryAfter, int(confirmationRetryWindow/time.Second))
}
}
func installConfirmationOutboxFailure(ctx context.Context, t *testing.T, harness *registrationHarness) {
t.Helper()
harness.exec(ctx, t, fmt.Sprintf(`CREATE FUNCTION %s() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NEW.event_type = 'identity.email_verified' THEN
RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'test confirmation outbox failure';
END IF;
RETURN NEW;
END;
$$`, pgx.Identifier{confirmationFailureFunction}.Sanitize()))
harness.exec(ctx, t, fmt.Sprintf(`CREATE TRIGGER %s BEFORE INSERT ON outbox_events
FOR EACH ROW EXECUTE FUNCTION %s()`,
pgx.Identifier{confirmationFailureTrigger}.Sanitize(),
pgx.Identifier{confirmationFailureFunction}.Sanitize()))
t.Cleanup(func() {
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cleanupTimeout)
defer cancel()
if _, err := harness.pool.Exec(cleanupCtx, fmt.Sprintf(`DROP TRIGGER IF EXISTS %s ON outbox_events`,
pgx.Identifier{confirmationFailureTrigger}.Sanitize())); err != nil {
t.Errorf("drop confirmation outbox trigger: %v", err)
}
if _, err := harness.pool.Exec(cleanupCtx, fmt.Sprintf(`DROP FUNCTION IF EXISTS %s()`,
pgx.Identifier{confirmationFailureFunction}.Sanitize())); err != nil {
t.Errorf("drop confirmation outbox trigger function: %v", err)
}
})
}
func stringPointer(value string) *string { return &value }
func sameOptionalString(left, right *string) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return *left == *right
}
func sameOptionalTime(left, right *time.Time) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return left.Equal(*right)
}
func sameOptionalInt64(left, right *int64) bool {
if left == nil || right == nil {
return left == nil && right == nil
}
return *left == *right
}
@@ -0,0 +1,262 @@
//go:build integration
package integration_test
import (
"context"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
const registrationConsentMigrationName = "00016_bind_registration_consent.sql"
func TestRegistrationConsentMigration(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), migrationTestTimeout)
defer cancel()
t.Run("binds legacy C1 rows and survives down and up", func(t *testing.T) {
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("apply migrations before preparing legacy data: %v", err)
}
rolledBack, err := migrator.DownOne(ctx)
if err != nil || rolledBack.Name != registrationConsentMigrationName {
t.Fatalf("roll back the registration-consent migration = %+v, %v", rolledBack, err)
}
assertRegistrationConsentColumn(ctx, t, pool, false)
const userID = "018f0000-0000-7000-8000-000000000001"
const registrationConsentID = "018f0000-0000-7000-8000-000000000002"
const settingsConsentID = "018f0000-0000-7000-8000-000000000003"
const otherConsentID = "018f0000-0000-7000-8000-000000000004"
const c1SettingsVersion = "c1-migration-settings"
createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
registrationAt := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
settingsAt := time.Date(2026, 10, 5, 12, 0, 0, 0, time.UTC)
seedRegistrationConsentFixture(ctx, t, pool, userID, createdAt, registrationAt, registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion, settingsAt)
applied, err := migrator.Up(ctx)
if err != nil || len(applied) != 1 || applied[0].Name != registrationConsentMigrationName {
t.Fatalf("apply registration-consent migration = %+v, %v", applied, err)
}
assertConsentRegistrationVersion(ctx, t, pool, registrationConsentID, 2)
assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID)
// Model a later registration after its former C1 was discarded. Old
// binaries omit registration_version; the insert trigger must bind the
// new C1 to the account version in effect at insert time.
if _, err := pool.Exec(ctx, `DELETE FROM consent_records WHERE id = $1::uuid`, registrationConsentID); err != nil {
t.Fatalf("remove the previous unverified registration C1: %v", err)
}
nextRegistrationAt := registrationAt.Add(24 * time.Hour)
if _, err := pool.Exec(ctx, `UPDATE users SET registration_version = 3, last_registered_at = $2, version = version + 1, updated_at = $2 WHERE id = $1::uuid`, userID, nextRegistrationAt); err != nil {
t.Fatalf("advance the synthetic registration: %v", err)
}
const compatibilityConsentID = "018f0000-0000-7000-8000-000000000005"
insertLegacyRegistrationC1(ctx, t, pool, compatibilityConsentID, userID, "c1-2026-10-01", nextRegistrationAt)
assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3)
beforeMismatch := countConsentRecords(ctx, t, pool)
const mismatchedConsentID = "018f0000-0000-7000-8000-000000000006"
_, err = pool.Exec(ctx, `
INSERT INTO consent_records (
id, subject_id, purpose, text_version, text_hash, source, granted_at, registration_version
)
SELECT $1::uuid, $2::uuid, text.purpose, text.version, text.body_sha256,
'registration', $3, 2
FROM consent_texts AS text
WHERE text.purpose = 'c1' AND text.version = 'c1-2026-10-01'`, mismatchedConsentID, userID, nextRegistrationAt)
assertSQLError(t, "registration C1 with an explicitly mismatched version", err, "23514", "consent_records_registration_version_matches_user")
if countConsentRecords(ctx, t, pool) != beforeMismatch {
t.Fatal("a registration C1 with a mismatched account version was inserted")
}
_, err = pool.Exec(ctx, `UPDATE consent_records
SET registration_version = 4, revoked_at = granted_at, revocation_source = 'support_request'
WHERE id = $1::uuid`, compatibilityConsentID)
assertSQLError(t, "changing a bound registration C1 version during revocation", err, "23000", "consent_records_immutable")
var version int64
var revokedAt *time.Time
if err := pool.QueryRow(ctx, `SELECT registration_version, revoked_at FROM consent_records WHERE id = $1::uuid`, compatibilityConsentID).Scan(&version, &revokedAt); err != nil {
t.Fatalf("read C1 after refused version change: %v", err)
}
if version != 3 || revokedAt != nil {
t.Fatal("a refused registration C1 version change altered its version or revocation state")
}
rolledBack, err = migrator.DownOne(ctx)
if err != nil || rolledBack.Name != registrationConsentMigrationName {
t.Fatalf("roll back registration-consent migration = %+v, %v", rolledBack, err)
}
assertRegistrationConsentColumn(ctx, t, pool, false)
if countConsentRecords(ctx, t, pool) != beforeMismatch {
t.Fatal("rolling back the registration-consent migration changed the consent ledger")
}
applied, err = migrator.Up(ctx)
if err != nil || len(applied) != 1 || applied[0].Name != registrationConsentMigrationName {
t.Fatalf("reapply registration-consent migration = %+v, %v", applied, err)
}
assertRegistrationConsentColumn(ctx, t, pool, true)
assertConsentRegistrationVersion(ctx, t, pool, compatibilityConsentID, 3)
assertConsentRegistrationVersionNull(ctx, t, pool, settingsConsentID, otherConsentID)
})
t.Run("refuses stale legacy registration C1 without a partial migration", func(t *testing.T) {
databaseURL := env.createIsolatedDatabase(ctx, t)
migrator := newMigrator(t, databaseURL)
pool := newPoolFor(ctx, t, databaseURL)
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("apply migrations before preparing stale legacy data: %v", err)
}
rolledBack, err := migrator.DownOne(ctx)
if err != nil || rolledBack.Name != registrationConsentMigrationName {
t.Fatalf("roll back the registration-consent migration = %+v, %v", rolledBack, err)
}
assertRegistrationConsentColumn(ctx, t, pool, false)
const userID = "018f0000-0000-7000-8000-000000000101"
const consentID = "018f0000-0000-7000-8000-000000000102"
createdAt := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
grantAt := time.Date(2026, 10, 6, 12, 0, 0, 0, time.UTC)
lastRegisteredAt := grantAt.Add(24 * time.Hour)
seedRegistrationMigrationUser(ctx, t, pool, userID, createdAt, lastRegisteredAt, 1)
insertLegacyRegistrationC1(ctx, t, pool, consentID, userID, "c1-2026-10-01", grantAt)
if _, err := migrator.Up(ctx); err == nil {
t.Fatal("migration accepted a registration C1 older than the account's latest registration")
}
assertRegistrationConsentColumn(ctx, t, pool, false)
if countConsentRecords(ctx, t, pool) != 1 {
t.Fatal("a failed migration partially changed the legacy consent record")
}
statuses, err := migrator.Status(ctx)
if err != nil {
t.Fatalf("read migration status after failed migration: %v", err)
}
for _, status := range statuses {
if status.Name == registrationConsentMigrationName && status.Applied {
t.Fatal("failed migration was recorded as applied")
}
}
if _, err := pool.Exec(ctx, `UPDATE users SET last_registered_at = $2, updated_at = $2 WHERE id = $1::uuid`, userID, grantAt); err != nil {
t.Fatalf("correct the synthetic legacy registration timestamp: %v", err)
}
if _, err := migrator.Up(ctx); err != nil {
t.Fatalf("migration did not succeed after the legacy data was corrected: %v", err)
}
assertRegistrationConsentColumn(ctx, t, pool, true)
assertConsentRegistrationVersion(ctx, t, pool, consentID, 1)
})
}
func seedRegistrationConsentFixture(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
userID string,
createdAt, registrationAt time.Time,
registrationConsentID, settingsConsentID, otherConsentID, c1SettingsVersion string,
settingsAt time.Time,
) {
t.Helper()
seedRegistrationMigrationUser(ctx, t, pool, userID, createdAt, registrationAt, 2)
if _, err := pool.Exec(ctx, `
INSERT INTO consent_texts (purpose, version, body, body_sha256, kind, published_at)
SELECT purpose, $1, body, sha256(convert_to(body, 'UTF8')), kind, $2
FROM consent_texts WHERE purpose = 'c1' AND version = 'c1-2026-10-01'`, c1SettingsVersion, createdAt.Add(24*time.Hour)); err != nil {
t.Fatalf("insert synthetic C1 text for a settings consent: %v", err)
}
insertLegacyRegistrationC1(ctx, t, pool, registrationConsentID, userID, "c1-2026-10-01", registrationAt)
insertLegacyConsent(ctx, t, pool, settingsConsentID, userID, "c1", c1SettingsVersion, "consent_settings", settingsAt)
insertLegacyConsent(ctx, t, pool, otherConsentID, userID, "c2", "c2-2026-10-01", "consent_settings", settingsAt)
}
func seedRegistrationMigrationUser(
ctx context.Context,
t *testing.T,
pool *pgxpool.Pool,
userID string,
createdAt, lastRegisteredAt time.Time,
registrationVersion int64,
) {
t.Helper()
const passwordHash = "$argon2id$v=19$m=1,t=1,p=1$c2FsdA$cGFzcw"
if _, err := pool.Exec(ctx, `
INSERT INTO users (
id, email, email_normalized, password_hash, scenario, onboarding_step,
registration_version, last_registered_at, version, created_at, updated_at
) VALUES ($1::uuid, 'migration.owner@example.test', 'migration.owner@example.test', $2,
'candidate', 'candidate_consents', $3, $4, 1, $5, $4)`,
userID, passwordHash, registrationVersion, lastRegisteredAt, createdAt); err != nil {
t.Fatalf("insert synthetic account before migration: %v", err)
}
}
func insertLegacyRegistrationC1(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID, userID, version string, grantedAt time.Time) {
t.Helper()
insertLegacyConsent(ctx, t, pool, consentID, userID, "c1", version, "registration", grantedAt)
}
func insertLegacyConsent(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID, userID, purpose, version, source string, grantedAt time.Time) {
t.Helper()
if _, err := pool.Exec(ctx, `
INSERT INTO consent_records (id, subject_id, purpose, text_version, text_hash, source, granted_at)
SELECT $1::uuid, $2::uuid, text.purpose, text.version, text.body_sha256, $5, $6
FROM consent_texts AS text WHERE text.purpose = $3 AND text.version = $4`,
consentID, userID, purpose, version, source, grantedAt); err != nil {
t.Fatalf("insert synthetic legacy consent: %v", err)
}
}
func assertRegistrationConsentColumn(ctx context.Context, t *testing.T, pool *pgxpool.Pool, want bool) {
t.Helper()
var exists bool
if err := pool.QueryRow(ctx, `SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'consent_records' AND column_name = 'registration_version'
)`).Scan(&exists); err != nil {
t.Fatalf("check registration-version column: %v", err)
}
if exists != want {
t.Fatalf("registration-version column exists = %t, want %t", exists, want)
}
}
func assertConsentRegistrationVersion(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentID string, want int64) {
t.Helper()
var got int64
if err := pool.QueryRow(ctx, `SELECT registration_version FROM consent_records WHERE id = $1::uuid`, consentID).Scan(&got); err != nil {
t.Fatalf("read bound consent version: %v", err)
}
if got != want {
t.Fatalf("consent registration version = %d, want %d", got, want)
}
}
func assertConsentRegistrationVersionNull(ctx context.Context, t *testing.T, pool *pgxpool.Pool, consentIDs ...string) {
t.Helper()
for _, consentID := range consentIDs {
var version *int64
if err := pool.QueryRow(ctx, `SELECT registration_version FROM consent_records WHERE id = $1::uuid`, consentID).Scan(&version); err != nil {
t.Fatalf("read unbound consent version: %v", err)
}
if version != nil {
t.Fatalf("non-registration consent has registration version %d", *version)
}
}
}
func countConsentRecords(ctx context.Context, t *testing.T, pool *pgxpool.Pool) int {
t.Helper()
var count int
if err := pool.QueryRow(ctx, `SELECT count(*)::integer FROM consent_records`).Scan(&count); err != nil {
t.Fatalf("count consent records: %v", err)
}
return count
}
+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.