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

+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")