Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: switched to a more robust test pipeline

=17ab30930867
diff --git a/backend-go/Makefile b/backend-go/Makefile
index 45172894ae..560682f56d 100644
--- a/backend-go/Makefile
+++ b/backend-go/Makefile
@@ -1,12 +1,14 @@
-# Run integration tests — testcontainers handles docker lifecycle automatically
+# Run unit tests (no infra required)
test:
- TESTCONTAINERS_DEBUG=true go test -v ./internal/... -count=1 -race -timeout 300s
+ go test -v ./internal/... -count=1 -race -timeout 120s
-# Tear down shared test containers and remove state file.
-# Use this if tests misbehave or to free up ports.
-test-cleanup:
- rm -f .test-infra-state.json .test-infra.lock
- docker compose -f docker-compose.test.yml down -v --remove-orphans 2>/dev/null || true
+# Run integration tests — testcontainers spins up isolated containers per package
+test-integration:
+ go test -v -tags integration ./internal/... -count=1 -race -timeout 300s
+
+# Run all tests (unit + integration)
+test-all:
+ go test -v -tags integration ./internal/... -count=1 -race -timeout 300s
# Generate Goa code from design DSL
gen-goa:
diff --git a/backend-go/internal/services/platform/projects/projects_test.go b/backend-go/internal/services/platform/projects/projects_integration_test.go
similarity index 81%
rename from backend-go/internal/services/platform/projects/projects_test.go
rename to backend-go/internal/services/platform/projects/projects_integration_test.go
index f70481affc..f2fa0202f9 100644
--- a/backend-go/internal/services/platform/projects/projects_test.go
+++ b/backend-go/internal/services/platform/projects/projects_integration_test.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package projects_test
import (
@@ -10,15 +12,21 @@ import (
"github.com/infisical/api/internal/services/platform/projects"
"github.com/infisical/api/internal/services/shared/permission"
"github.com/infisical/api/internal/testutil"
+ "github.com/infisical/api/internal/testutil/infra"
"github.com/stretchr/testify/require"
)
-var infra *testutil.TestInfra
+var stack *infra.Stack
func TestMain(m *testing.M) {
- infra = testutil.SetupInfra()
+ stack = infra.New().
+ WithPostgres().
+ WithRedis().
+ WithNodeJSApi().
+ MustStart()
+
code := m.Run()
- infra.Teardown()
+ stack.Stop()
os.Exit(code)
}
@@ -52,16 +60,16 @@ func TestCreateProject(t *testing.T) {
var result map[string]any
mux.Request(t, http.MethodPost, "/api/v1/platform/projects").
- WithAuth(infra.IdentityToken).
+ WithAuth(stack.NodeJS().IdentityToken()).
WithBody(map[string]any{
"name": "my-new-project",
- "orgId": infra.OrgID,
+ "orgId": stack.NodeJS().OrgID(),
}).
Do().
ExpectStatus(http.StatusCreated).
ParseJSON(&result)
require.Equal(t, "my-new-project", result["name"])
- require.Equal(t, infra.OrgID, result["orgId"])
+ require.Equal(t, stack.NodeJS().OrgID(), result["orgId"])
require.NotEmpty(t, result["id"])
}
diff --git a/backend-go/internal/services/secretmanager/secrets/secrets_test.go b/backend-go/internal/services/secretmanager/secrets/secrets_integration_test.go
similarity index 84%
rename from backend-go/internal/services/secretmanager/secrets/secrets_test.go
rename to backend-go/internal/services/secretmanager/secrets/secrets_integration_test.go
index 05bdfb9074..bae2cd3535 100644
--- a/backend-go/internal/services/secretmanager/secrets/secrets_test.go
+++ b/backend-go/internal/services/secretmanager/secrets/secrets_integration_test.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package secrets_test
import (
@@ -11,19 +13,25 @@ import (
"github.com/infisical/api/internal/services/shared/permission"
smShared "github.com/infisical/api/internal/services/shared/secretmanager"
"github.com/infisical/api/internal/testutil"
+ "github.com/infisical/api/internal/testutil/infra"
"github.com/stretchr/testify/require"
)
var (
- infra *testutil.TestInfra
- project *testutil.ProjectSeed
+ stack *infra.Stack
+ project *infra.ProjectSeed
)
func TestMain(m *testing.M) {
- infra = testutil.SetupInfra()
- project = infra.MustCreateProject("secrets-test")
+ stack = infra.New().
+ WithPostgres().
+ WithRedis().
+ WithNodeJSApi().
+ MustStart()
+
+ project = stack.NodeJS().MustCreateProject("secrets-test")
code := m.Run()
- infra.Teardown()
+ stack.Stop()
os.Exit(code)
}
@@ -34,7 +42,7 @@ func setupMux(t *testing.T) *testutil.TestMux {
permDAL := permission.NewDAL()
permLib := permission.NewSharedService(permDAL)
- smSharedSvcs := smShared.NewSharedServices(smShared.SharedServicesDeps{DB: infra.DB})
+ smSharedSvcs := smShared.NewSharedServices(smShared.SharedServicesDeps{DB: stack.DB()})
svc := secrets.NewService(testutil.NopLogger(), permLib, smSharedSvcs.SecretFolder)
@@ -59,7 +67,7 @@ func TestCreateSecret(t *testing.T) {
var result map[string]any
mux.Request(t, http.MethodPost, "/api/v1/secret-manager/secrets").
- WithAuth(infra.IdentityToken).
+ WithAuth(stack.NodeJS().IdentityToken()).
WithBody(map[string]any{
"key": "DB_PASSWORD",
"value": "s3cret",
@@ -79,7 +87,7 @@ func TestGetSecret(t *testing.T) {
var result map[string]any
mux.Request(t, http.MethodGet, "/api/v1/secret-manager/secrets/test-id-123").
- WithAuth(infra.IdentityToken).
+ WithAuth(stack.NodeJS().IdentityToken()).
Do().
ExpectStatus(http.StatusOK).
ParseJSON(&result)
@@ -92,7 +100,7 @@ func TestUpdateSecret(t *testing.T) {
var result map[string]any
mux.Request(t, http.MethodPatch, "/api/v1/secret-manager/secrets/test-id-456").
- WithAuth(infra.IdentityToken).
+ WithAuth(stack.NodeJS().IdentityToken()).
WithBody(map[string]any{
"key": "UPDATED_KEY",
"value": "updated_value",
@@ -108,7 +116,7 @@ func TestDeleteSecret(t *testing.T) {
mux := setupMux(t)
mux.Request(t, http.MethodDelete, "/api/v1/secret-manager/secrets/test-id-789").
- WithAuth(infra.IdentityToken).
+ WithAuth(stack.NodeJS().IdentityToken()).
Do().
ExpectStatus(http.StatusNoContent)
}
@@ -118,7 +126,7 @@ func TestListSecrets(t *testing.T) {
var result []map[string]any
mux.Request(t, http.MethodGet, "/api/v1/secret-manager/secrets?projectId="+project.ID+"&environment="+project.EnvSlug).
- WithAuth(infra.IdentityToken).
+ WithAuth(stack.NodeJS().IdentityToken()).
Do().
ExpectStatus(http.StatusOK).
ParseJSON(&result)
diff --git a/backend-go/internal/services/shared/kms/kms_test.go b/backend-go/internal/services/shared/kms/kms_integration_test.go
similarity index 91%
rename from backend-go/internal/services/shared/kms/kms_test.go
rename to backend-go/internal/services/shared/kms/kms_integration_test.go
index dea12e06ae..e3d9bdaee2 100644
--- a/backend-go/internal/services/shared/kms/kms_test.go
+++ b/backend-go/internal/services/shared/kms/kms_integration_test.go
@@ -1,3 +1,5 @@
+//go:build integration
+
package kms_test
import (
@@ -13,24 +15,29 @@ import (
"github.com/infisical/api/internal/keystore"
"github.com/infisical/api/internal/services/shared/kms"
- "github.com/infisical/api/internal/testutil"
+ "github.com/infisical/api/internal/testutil/infra"
)
-var orgID uuid.UUID
-
-var infra *testutil.TestInfra
+var (
+ stack *infra.Stack
+ orgID uuid.UUID
+)
func TestMain(m *testing.M) {
- infra = testutil.SetupInfra()
+ stack = infra.New().
+ WithPostgres().
+ WithRedis().
+ WithNodeJSApi().
+ MustStart()
var err error
- orgID, err = uuid.Parse(infra.OrgID)
+ orgID, err = uuid.Parse(stack.NodeJS().OrgID())
if err != nil {
log.Fatalf("kms_test: parsing org ID: %v", err)
}
code := m.Run()
- infra.Teardown()
+ stack.Stop()
os.Exit(code)
}
@@ -38,15 +45,15 @@ func TestMain(m *testing.M) {
func setupService(t *testing.T) *kms.SharedService {
t.Helper()
- opts, err := redis.ParseURL(infra.RedisURL)
+ opts, err := redis.ParseURL(stack.Redis().URL())
require.NoError(t, err)
redisClient := redis.NewClient(opts)
t.Cleanup(func() { redisClient.Close() })
- ks := keystore.NewKeyStore(redisClient, infra.DB.Primary())
- dal := kms.NewDAL(infra.DB, ks)
+ ks := keystore.NewKeyStore(redisClient, stack.DB().Primary())
+ dal := kms.NewDAL(stack.DB(), ks)
- svc, err := kms.NewSharedService(dal, nil, infra.Config)
+ svc, err := kms.NewSharedService(dal, nil, stack.Config())
require.NoError(t, err)
return svc
}
@@ -208,7 +215,7 @@ func TestProjectCipherPair_CreatesFromScratch(t *testing.T) {
svc := startedService(t)
ctx := context.Background()
- proj := infra.CreateProject(t, "kms-scratch")
+ proj := stack.NodeJS().CreateProject(t, "kms-scratch")
pair, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
Type: kms.DataKeyProject,
@@ -230,7 +237,7 @@ func TestProjectCipherPair_Idempotent(t *testing.T) {
svc := startedService(t)
ctx := context.Background()
- proj := infra.CreateProject(t, "kms-idempotent")
+ proj := stack.NodeJS().CreateProject(t, "kms-idempotent")
dto := kms.CreateCipherPairDTO{
Type: kms.DataKeyProject,
@@ -258,7 +265,7 @@ func TestProjectCipherPair_Concurrent(t *testing.T) {
ctx := context.Background()
// All goroutines race on the same fresh project.
- proj := infra.CreateProject(t, "kms-concurrent")
+ proj := stack.NodeJS().CreateProject(t, "kms-concurrent")
const n = 10
plaintext := []byte("concurrent project test")
@@ -308,8 +315,8 @@ func TestProjectCipherPair_IsolatedPerProject(t *testing.T) {
svc := startedService(t)
ctx := context.Background()
- proj1 := infra.CreateProject(t, "kms-iso-1")
- proj2 := infra.CreateProject(t, "kms-iso-2")
+ proj1 := stack.NodeJS().CreateProject(t, "kms-iso-1")
+ proj2 := stack.NodeJS().CreateProject(t, "kms-iso-2")
pair1, err := svc.CreateCipherPairWithDataKey(ctx, kms.CreateCipherPairDTO{
Type: kms.DataKeyProject,
diff --git a/backend-go/internal/testutil/infra.go b/backend-go/internal/testutil/infra.go
deleted file mode 100644
index e086de68b1..0000000000
--- a/backend-go/internal/testutil/infra.go
+++ /dev/null
@@ -1,313 +0,0 @@
-package testutil
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log"
- "net/http"
- "os"
- "path/filepath"
- "time"
-
- "github.com/docker/go-connections/nat"
- "github.com/go-resty/resty/v2"
- "github.com/gofrs/flock"
- tc "github.com/testcontainers/testcontainers-go/modules/compose"
- "github.com/testcontainers/testcontainers-go/wait"
-
- "github.com/infisical/api/internal/config"
- "github.com/infisical/api/internal/database/pg"
-)
-
-// TestInfra holds references to the test infrastructure and bootstrapped credentials.
-type TestInfra struct {
- DBURI string
- RedisURL string
- NodeJSURL string
- DB pg.DB
- Config *config.Config
- compose tc.ComposeStack
- client *resty.Client
-
- // isOwner is true if this process started the compose stack.
- // Guests (other test packages) reuse the existing stack.
- isOwner bool
-
- // Bootstrapped credentials
- OrgID string
- UserEmail string
- UserID string
- IdentityToken string // Machine identity access token
- UserToken string // User JWT
-}
-
-// infraState is the JSON structure persisted to .test-infra-state.json
-// so that concurrent test packages can share a single compose stack.
-type infraState struct {
- DBURI string `json:"db_uri"`
- RedisURL string `json:"redis_url"`
- NodeJSURL string `json:"nodejs_url"`
- OrgID string `json:"org_id"`
- UserEmail string `json:"user_email"`
- UserID string `json:"user_id"`
- IdentityToken string `json:"identity_token"`
- UserToken string `json:"user_token"`
-}
-
-// findModuleRoot walks up from the current directory to find go.mod,
-// returning the directory that contains it.
-func findModuleRoot() (string, error) {
- dir, err := os.Getwd()
- if err != nil {
- return "", err
- }
- for {
- if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
- return dir, nil
- }
- parent := filepath.Dir(dir)
- if parent == dir {
- return "", fmt.Errorf("could not find go.mod in any parent directory")
- }
- dir = parent
- }
-}
-
-// NOTE: This shared-infra approach is a temporary workaround.
-// Because the Node.js backend is so slow
-// we can only run one instance. A file lock + state file coordinates across
-// packages so compose starts once and subsequent packages reuse it.
-//
-// Once the full Go migration is complete and the Node.js dependency is removed,
-// each test package can spin up its own isolated containers with random ports,
-// enabling true parallel execution without any cross-process coordination.
-
-// SetupInfra starts or reuses the shared test infrastructure.
-//
-// A file lock (.test-infra.lock) prevents races between parallel packages.
-// If a previous run left a healthy stack, we reuse it via .test-infra-state.json.
-// Otherwise we start a fresh compose stack and bootstrap credentials.
-//
-// Uses log.Fatalf for errors because this runs in TestMain where
-// *testing.T is not available.
-func SetupInfra() *TestInfra {
- root, err := findModuleRoot()
- if err != nil {
- log.Fatalf("testutil.SetupInfra: %v", err)
- }
-
- lockPath := filepath.Join(root, ".test-infra.lock")
- statePath := filepath.Join(root, ".test-infra-state.json")
-
- // Acquire cross-process file lock so only one package starts compose.
- fileLock := flock.New(lockPath)
- if err := fileLock.Lock(); err != nil {
- log.Fatalf("testutil.SetupInfra: failed to acquire lock: %v", err)
- }
- defer func() {
- if err := fileLock.Unlock(); err != nil {
- log.Printf("testutil.SetupInfra: failed to release lock: %v", err)
- }
- }()
-
- // Try to reuse an existing healthy stack.
- if state, err := loadState(statePath); err == nil {
- if checkHealth(state.NodeJSURL) {
- log.Println("testutil.SetupInfra: reusing existing infra")
- setTestEnv(state.DBURI, state.RedisURL)
- cfg := mustLoadConfig()
- db := mustConnectDB(cfg)
- return &TestInfra{
- DBURI: state.DBURI,
- RedisURL: state.RedisURL,
- NodeJSURL: state.NodeJSURL,
- DB: db,
- Config: cfg,
- client: resty.New().SetBaseURL(state.NodeJSURL),
- isOwner: false,
- OrgID: state.OrgID,
- UserEmail: state.UserEmail,
- UserID: state.UserID,
- IdentityToken: state.IdentityToken,
- UserToken: state.UserToken,
- }
- }
- // Stale state — remove and start fresh.
- log.Println("testutil.SetupInfra: stale state file, starting fresh")
- os.Remove(statePath)
- }
-
- // Owner path: start compose from scratch.
- infra := startCompose(root)
- infra.isOwner = true
- infra.bootstrap()
-
- // Persist state so other packages can reuse this stack.
- saveState(statePath, &infraState{
- DBURI: infra.DBURI,
- RedisURL: infra.RedisURL,
- NodeJSURL: infra.NodeJSURL,
- OrgID: infra.OrgID,
- UserEmail: infra.UserEmail,
- UserID: infra.UserID,
- IdentityToken: infra.IdentityToken,
- UserToken: infra.UserToken,
- })
-
- log.Println("testutil.SetupInfra: bootstrap complete, state saved")
-
- return infra
-}
-
-// startCompose brings up the docker-compose.test.yml stack via testcontainers.
-func startCompose(root string) *TestInfra {
- ctx := context.Background()
- composePath := filepath.Join(root, "docker-compose.test.yml")
-
- log.Printf("testutil.startCompose: starting compose from %s", composePath)
-
- compose, err := tc.NewDockerCompose(composePath)
- if err != nil {
- log.Fatalf("testutil.startCompose: failed to create compose: %v", err)
- }
-
- err = compose.
- WaitForService("db", wait.ForListeningPort("5432/tcp").WithStartupTimeout(60*time.Second)).
- WaitForService("redis", wait.ForListeningPort("6379/tcp").WithStartupTimeout(60*time.Second)).
- WaitForService("backend-nodejs", wait.ForHTTP("/api/status").WithPort("8080/tcp").WithStartupTimeout(120*time.Second)).
- Up(ctx, tc.Wait(true))
- if err != nil {
- log.Fatalf("testutil.startCompose: failed to start compose: %v", err)
- }
-
- log.Println("testutil.startCompose: all services up")
-
- // Discover mapped ports.
- dbHost, dbPort, err := getServiceHostPort(ctx, compose, "db", 5432)
- if err != nil {
- log.Fatalf("testutil.startCompose: failed to get db host/port: %v", err)
- }
-
- redisHost, redisPort, err := getServiceHostPort(ctx, compose, "redis", 6379)
- if err != nil {
- log.Fatalf("testutil.startCompose: failed to get redis host/port: %v", err)
- }
-
- nodejsHost, nodejsPort, err := getServiceHostPort(ctx, compose, "backend-nodejs", 8080)
- if err != nil {
- log.Fatalf("testutil.startCompose: failed to get nodejs host/port: %v", err)
- }
-
- dbURI := fmt.Sprintf("postgres://infisical:infisical@%s:%d/infisical?sslmode=disable", dbHost, dbPort)
- redisURL := fmt.Sprintf("redis://%s:%d", redisHost, redisPort)
- nodejsURL := fmt.Sprintf("http://%s:%d", nodejsHost, nodejsPort)
-
- log.Printf("testutil.startCompose: db=%s redis=%s nodejs=%s", dbURI, redisURL, nodejsURL)
-
- setTestEnv(dbURI, redisURL)
- cfg := mustLoadConfig()
- db := mustConnectDB(cfg)
-
- return &TestInfra{
- DBURI: dbURI,
- RedisURL: redisURL,
- NodeJSURL: nodejsURL,
- DB: db,
- Config: cfg,
- compose: compose,
- client: resty.New().SetBaseURL(nodejsURL),
- }
-}
-
-// setTestEnv sets the environment variables needed for config.LoadConfig() in tests.
-func setTestEnv(dbURI, redisURL string) {
- os.Setenv("DB_CONNECTION_URI", dbURI)
- os.Setenv("REDIS_URL", redisURL)
- os.Setenv("AUTH_SECRET", AuthSecret)
- os.Setenv("ENCRYPTION_KEY", EncryptionKey)
- os.Setenv("NODE_ENV", NodeEnv)
-}
-
-// mustLoadConfig loads the application config or fatals.
-func mustLoadConfig() *config.Config {
- cfg, err := config.LoadConfig()
- if err != nil {
- log.Fatalf("testutil.mustLoadConfig: %v", err)
- }
- return cfg
-}
-
-// mustConnectDB creates a pg.DB connection via pg.NewPostgresDB or fatals.
-func mustConnectDB(cfg *config.Config) pg.DB {
- ctx := context.Background()
-
- db, err := pg.NewPostgresDB(ctx, cfg.DBConnectionURI, cfg.DBRootCert, cfg.DBReadReplicas)
- if err != nil {
- log.Fatalf("testutil.mustConnectDB: %v", err)
- }
-
- return db
-}
-
-// Teardown cleans up resources for this test package.
-// Only closes the DB pool — does NOT tear down compose since other packages
-// may still be using the shared stack. Use `make test-cleanup` for that.
-func (infra *TestInfra) Teardown() {
- infra.DB.Close()
-}
-
-// checkHealth pings the Node.js backend to see if the stack is alive.
-func checkHealth(nodejsURL string) bool {
- client := &http.Client{Timeout: 3 * time.Second}
- resp, err := client.Get(nodejsURL + "/api/status")
- if err != nil {
- return false
- }
- resp.Body.Close()
- return resp.StatusCode == http.StatusOK
-}
-
-// loadState reads the persisted infra state from disk.
-func loadState(path string) (*infraState, error) {
- data, err := os.ReadFile(path)
- if err != nil {
- return nil, err
- }
- var state infraState
- if err := json.Unmarshal(data, &state); err != nil {
- return nil, err
- }
- return &state, nil
-}
-
-// saveState writes the infra state to disk for other packages to reuse.
-func saveState(path string, state *infraState) {
- data, err := json.MarshalIndent(state, "", " ")
- if err != nil {
- log.Fatalf("testutil.saveState: failed to marshal state: %v", err)
- }
- if err := os.WriteFile(path, data, 0644); err != nil {
- log.Fatalf("testutil.saveState: failed to write state file: %v", err)
- }
-}
-
-// getServiceHostPort returns the host and mapped port for a compose service.
-func getServiceHostPort(ctx context.Context, compose tc.ComposeStack, service string, port int) (string, int, error) {
- container, err := compose.ServiceContainer(ctx, service)
- if err != nil {
- return "", 0, fmt.Errorf("get container for %s: %w", service, err)
- }
-
- host, err := container.Host(ctx)
- if err != nil {
- return "", 0, fmt.Errorf("get host for %s: %w", service, err)
- }
-
- mappedPort, err := container.MappedPort(ctx, nat.Port(fmt.Sprintf("%d/tcp", port)))
- if err != nil {
- return "", 0, fmt.Errorf("get mapped port for %s: %w", service, err)
- }
-
- return host, mappedPort.Int(), nil
-}
diff --git a/backend-go/internal/testutil/infra/builder.go b/backend-go/internal/testutil/infra/builder.go
new file mode 100644
index 0000000000..09d721009f
--- /dev/null
+++ b/backend-go/internal/testutil/infra/builder.go
@@ -0,0 +1,116 @@
+package infra
+
+import (
+ "context"
+ "log"
+ "sync"
+
+ "github.com/testcontainers/testcontainers-go/network"
+
+ "github.com/infisical/api/internal/config"
+ "github.com/infisical/api/internal/database/pg"
+)
+
+// Builder configures which services to spin up for an integration test.
+type Builder struct {
+ wantPostgres bool
+ wantRedis bool
+ wantNodeJS bool
+}
+
+// New creates a new infrastructure builder.
+func New() *Builder { return &Builder{} }
+
+// WithPostgres adds a PostgreSQL container to the stack.
+func (b *Builder) WithPostgres() *Builder { b.wantPostgres = true; return b }
+
+// WithRedis adds a Redis container to the stack.
+func (b *Builder) WithRedis() *Builder { b.wantRedis = true; return b }
+
+// WithNodeJSApi adds the Node.js backend container.
+// Automatically enables Postgres and Redis since the backend depends on them.
+func (b *Builder) WithNodeJSApi() *Builder {
+ b.wantNodeJS = true
+ b.wantPostgres = true
+ b.wantRedis = true
+ return b
+}
+
+// MustStart spins up the configured containers and returns a ready-to-use Stack.
+// Postgres and Redis start in parallel; NodeJS waits for both.
+// Sets environment variables so config.LoadConfig() works.
+// If NodeJS is requested, bootstraps an admin user/org/identity.
+// Uses log.Fatalf on error (designed for TestMain).
+func (b *Builder) MustStart() *Stack {
+ ctx := context.Background()
+
+ // 1. Create an isolated docker network.
+ net, err := network.New(ctx)
+ if err != nil {
+ log.Fatalf("infra: create network: %v", err)
+ }
+
+ stack := &Stack{network: net}
+
+ // 2. Start Postgres and Redis in parallel.
+ var wg sync.WaitGroup
+ var pgErr, redisErr error
+
+ if b.wantPostgres {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ stack.postgres, pgErr = startPostgres(ctx, net.Name)
+ }()
+ }
+
+ if b.wantRedis {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ stack.redis, redisErr = startRedis(ctx, net.Name)
+ }()
+ }
+
+ wg.Wait()
+
+ if pgErr != nil {
+ log.Fatalf("infra: %v", pgErr)
+ }
+ if redisErr != nil {
+ log.Fatalf("infra: %v", redisErr)
+ }
+
+ // 3. Start NodeJS after Postgres and Redis are healthy.
+ if b.wantNodeJS {
+ stack.nodejs, err = startNodeJS(ctx, net.Name)
+ if err != nil {
+ log.Fatalf("infra: %v", err)
+ }
+ }
+
+ // 4. Set environment variables for config.LoadConfig().
+ stack.setEnv()
+
+ // 5. Load application config.
+ stack.cfg, err = config.LoadConfig()
+ if err != nil {
+ log.Fatalf("infra: load config: %v", err)
+ }
+
+ // 6. Connect to Postgres.
+ if b.wantPostgres {
+ stack.db, err = pg.NewPostgresDB(ctx, stack.cfg.DBConnectionURI, stack.cfg.DBRootCert, stack.cfg.DBReadReplicas)
+ if err != nil {
+ log.Fatalf("infra: connect db: %v", err)
+ }
+ }
+
+ // 7. Bootstrap admin user/org/identity via the NodeJS API.
+ if b.wantNodeJS {
+ stack.nodejs.bootstrap()
+ }
+
+ log.Println("infra: stack ready")
+ return stack
+}
diff --git a/backend-go/internal/testutil/constants.go b/backend-go/internal/testutil/infra/constants.go
similarity index 51%
rename from backend-go/internal/testutil/constants.go
rename to backend-go/internal/testutil/infra/constants.go
index 01a1b82e86..66fb3bce91 100644
--- a/backend-go/internal/testutil/constants.go
+++ b/backend-go/internal/testutil/infra/constants.go
@@ -1,8 +1,12 @@
-package testutil
+package infra
-// Test constants matching docker-compose.test.yml environment.
+// Test constants for infrastructure setup.
const (
AuthSecret = "test-auth-secret-long-enough-for-jwt"
EncryptionKey = "a984ecdf82ec779e55dbcc21303a900f"
NodeEnv = "test"
+
+ pgUser = "infisical"
+ pgPassword = "infisical"
+ pgDB = "infisical"
)
diff --git a/backend-go/internal/testutil/infra/nodejs.go b/backend-go/internal/testutil/infra/nodejs.go
new file mode 100644
index 0000000000..123b9a132a
--- /dev/null
+++ b/backend-go/internal/testutil/infra/nodejs.go
@@ -0,0 +1,238 @@
+package infra
+
+import (
+ "crypto/rand"
+ "fmt"
+ "log"
+ "testing"
+ "time"
+
+ "context"
+
+ "github.com/go-resty/resty/v2"
+ "github.com/testcontainers/testcontainers-go"
+ "github.com/testcontainers/testcontainers-go/wait"
+)
+
+// ProjectSeed contains IDs for a project created via the Node.js API.
+type ProjectSeed struct {
+ ID string
+ Slug string
+ EnvSlug string
+}
+
+// NodeJSService provides access to a running Node.js backend container
+// and the bootstrapped credentials (admin user, org, machine identity).
+type NodeJSService struct {
+ container testcontainers.Container
+ url string
+ client *resty.Client
+ orgID string
+ userID string
+ userEmail string
+ identityToken string
+ userToken string
+}
+
+func (n *NodeJSService) URL() string { return n.url }
+func (n *NodeJSService) OrgID() string { return n.orgID }
+func (n *NodeJSService) UserID() string { return n.userID }
+func (n *NodeJSService) UserEmail() string { return n.userEmail }
+func (n *NodeJSService) IdentityToken() string { return n.identityToken }
+func (n *NodeJSService) UserToken() string { return n.userToken }
+func (n *NodeJSService) Client() *resty.Client { return n.client }
+
+func startNodeJS(ctx context.Context, networkName string) (*NodeJSService, error) {
+ req := testcontainers.ContainerRequest{
+ Image: "infisical/infisical:latest",
+ ExposedPorts: []string{"8080/tcp"},
+ Networks: []string{networkName},
+ NetworkAliases: map[string][]string{
+ networkName: {"backend-nodejs"},
+ },
+ Env: map[string]string{
+ "NODE_ENV": "development",
+ "DB_CONNECTION_URI": fmt.Sprintf("postgres://%s:%s@db:5432/%s?sslmode=disable", pgUser, pgPassword, pgDB),
+ "REDIS_URL": "redis://redis:6379",
+ "ENCRYPTION_KEY": EncryptionKey,
+ "AUTH_SECRET": AuthSecret,
+ "SITE_URL": "http://localhost:8080",
+ "TELEMETRY_ENABLED": "false",
+ },
+ WaitingFor: wait.ForHTTP("/api/status").WithPort("8080/tcp").WithStartupTimeout(120 * time.Second),
+ }
+
+ container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
+ ContainerRequest: req,
+ Started: true,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("starting nodejs: %w", err)
+ }
+
+ host, err := container.Host(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("getting nodejs host: %w", err)
+ }
+
+ mappedPort, err := container.MappedPort(ctx, "8080/tcp")
+ if err != nil {
+ return nil, fmt.Errorf("getting nodejs port: %w", err)
+ }
+
+ url := fmt.Sprintf("http://%s:%d", host, mappedPort.Int())
+
+ return &NodeJSService{
+ container: container,
+ url: url,
+ client: resty.New().SetBaseURL(url),
+ }, nil
+}
+
+// bootstrap creates the initial admin user, org, and machine identity,
+// then logs in to obtain a user JWT. Uses log.Fatalf since it runs in TestMain.
+func (n *NodeJSService) bootstrap() {
+ var bootstrapResp map[string]any
+ resp, err := n.client.R().
+ SetBody(map[string]any{
+ "email": "[email protected]",
+ "password": "testpassword123",
+ "organization": "test-org",
+ }).
+ SetResult(&bootstrapResp).
+ Post("/api/v1/admin/bootstrap")
+ if err != nil {
+ log.Fatalf("infra.bootstrap: request failed: %v", err)
+ }
+ if resp.IsError() {
+ log.Fatalf("infra.bootstrap: returned %d: %s", resp.StatusCode(), resp.String())
+ }
+
+ n.orgID = jsonStr(bootstrapResp, "organization.id")
+ n.identityToken = jsonStr(bootstrapResp, "identity.credentials.token")
+ n.userEmail = jsonStr(bootstrapResp, "user.email")
+ n.userID = jsonStr(bootstrapResp, "user.id")
+
+ var loginResp map[string]any
+ resp, err = n.client.R().
+ SetBody(map[string]any{
+ "email": n.userEmail,
+ "password": "testpassword123",
+ }).
+ SetResult(&loginResp).
+ Post("/api/v3/auth/login")
+ if err != nil {
+ log.Fatalf("infra.bootstrap: login request failed: %v", err)
+ }
+ if resp.IsError() {
+ log.Fatalf("infra.bootstrap: login returned %d: %s", resp.StatusCode(), resp.String())
+ }
+ n.userToken = jsonStr(loginResp, "accessToken")
+}
+
+// MustCreateProject creates a new project via the Node.js API.
+// Safe to call from TestMain — uses log.Fatalf on error.
+func (n *NodeJSService) MustCreateProject(name string) *ProjectSeed {
+ var projectResp map[string]any
+ resp, err := n.client.R().
+ SetAuthToken(n.identityToken).
+ SetBody(map[string]any{
+ "projectName": name,
+ "slug": fmt.Sprintf("test-%s", name),
+ "type": "secret-manager",
+ }).
+ SetResult(&projectResp).
+ Post("/api/v1/projects")
+ if err != nil {
+ log.Fatalf("infra.MustCreateProject: request failed: %v", err)
+ }
+ if resp.IsError() {
+ log.Fatalf("infra.MustCreateProject: returned %d: %s", resp.StatusCode(), resp.String())
+ }
+
+ return &ProjectSeed{
+ ID: jsonStr(projectResp, "project.id"),
+ Slug: jsonStr(projectResp, "project.slug"),
+ EnvSlug: "dev",
+ }
+}
+
+// CreateProject creates a new project via the Node.js API and returns its metadata.
+func (n *NodeJSService) CreateProject(t *testing.T, name string) *ProjectSeed {
+ t.Helper()
+
+ b := make([]byte, 4)
+ rand.Read(b)
+ slug := fmt.Sprintf("t-%s-%x", name, b)
+ if len(slug) > 36 {
+ slug = slug[:36]
+ }
+
+ var projectResp map[string]any
+ resp, err := n.client.R().
+ SetAuthToken(n.identityToken).
+ SetBody(map[string]any{
+ "projectName": name,
+ "slug": slug,
+ "type": "secret-manager",
+ }).
+ SetResult(&projectResp).
+ Post("/api/v1/projects")
+ if err != nil {
+ t.Fatalf("infra.CreateProject: request failed: %v", err)
+ }
+ if resp.IsError() {
+ t.Fatalf("infra.CreateProject: returned %d: %s", resp.StatusCode(), resp.String())
+ }
+
+ return &ProjectSeed{
+ ID: jsonStr(projectResp, "project.id"),
+ Slug: jsonStr(projectResp, "project.slug"),
+ EnvSlug: "dev",
+ }
+}
+
+// DeleteProject deletes a project via the Node.js API.
+func (n *NodeJSService) DeleteProject(t *testing.T, projectID string) {
+ t.Helper()
+
+ resp, err := n.client.R().
+ SetAuthToken(n.identityToken).
+ Delete("/api/v1/projects/" + projectID)
+ if err != nil {
+ t.Fatalf("infra.DeleteProject: request failed: %v", err)
+ }
+ if resp.IsError() {
+ t.Fatalf("infra.DeleteProject: returned %d: %s", resp.StatusCode(), resp.String())
+ }
+}
+
+// jsonStr extracts a string value from a nested JSON map using dot-separated path.
+func jsonStr(m map[string]any, path string) string {
+ keys := splitDotPath(path)
+ current := any(m)
+
+ for _, key := range keys {
+ obj, ok := current.(map[string]any)
+ if !ok {
+ return ""
+ }
+ current = obj[key]
+ }
+
+ s, _ := current.(string)
+ return s
+}
+
+func splitDotPath(path string) []string {
+ var keys []string
+ start := 0
+ for i := 0; i < len(path); i++ {
+ if path[i] == '.' {
+ keys = append(keys, path[start:i])
+ start = i + 1
+ }
+ }
+ keys = append(keys, path[start:])
+ return keys
+}
diff --git a/backend-go/internal/testutil/infra/postgres.go b/backend-go/internal/testutil/infra/postgres.go
new file mode 100644
index 0000000000..cad3748517
--- /dev/null
+++ b/backend-go/internal/testutil/infra/postgres.go
@@ -0,0 +1,67 @@
+package infra
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/testcontainers/testcontainers-go"
+ "github.com/testcontainers/testcontainers-go/wait"
+)
+
+// PostgresService provides access to a running PostgreSQL container.
+type PostgresService struct {
+ container testcontainers.Container
+ uri string
+ host string
+ port int
+}
+
+func (p *PostgresService) URI() string { return p.uri }
+func (p *PostgresService) Host() string { return p.host }
+func (p *PostgresService) Port() int { return p.port }
+
+func startPostgres(ctx context.Context, networkName string) (*PostgresService, error) {
+ req := testcontainers.ContainerRequest{
+ Image: "postgres:14-alpine",
+ ExposedPorts: []string{"5432/tcp"},
+ Networks: []string{networkName},
+ NetworkAliases: map[string][]string{
+ networkName: {"db"},
+ },
+ Env: map[string]string{
+ "POSTGRES_USER": pgUser,
+ "POSTGRES_PASSWORD": pgPassword,
+ "POSTGRES_DB": pgDB,
+ },
+ WaitingFor: wait.ForListeningPort("5432/tcp").WithStartupTimeout(60 * time.Second),
+ }
+
+ container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
+ ContainerRequest: req,
+ Started: true,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("starting postgres: %w", err)
+ }
+
+ host, err := container.Host(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("getting postgres host: %w", err)
+ }
+
+ mappedPort, err := container.MappedPort(ctx, "5432/tcp")
+ if err != nil {
+ return nil, fmt.Errorf("getting postgres port: %w", err)
+ }
+
+ port := mappedPort.Int()
+ uri := fmt.Sprintf("postgres://%s:%s@%s:%d/%s?sslmode=disable", pgUser, pgPassword, host, port, pgDB)
+
+ return &PostgresService{
+ container: container,
+ uri: uri,
+ host: host,
+ port: port,
+ }, nil
+}
diff --git a/backend-go/internal/testutil/infra/redis.go b/backend-go/internal/testutil/infra/redis.go
new file mode 100644
index 0000000000..aae7db6ad4
--- /dev/null
+++ b/backend-go/internal/testutil/infra/redis.go
@@ -0,0 +1,55 @@
+package infra
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/testcontainers/testcontainers-go"
+ "github.com/testcontainers/testcontainers-go/wait"
+)
+
+// RedisService provides access to a running Redis container.
+type RedisService struct {
+ container testcontainers.Container
+ url string
+}
+
+func (r *RedisService) URL() string { return r.url }
+
+func startRedis(ctx context.Context, networkName string) (*RedisService, error) {
+ req := testcontainers.ContainerRequest{
+ Image: "redis:7-alpine",
+ ExposedPorts: []string{"6379/tcp"},
+ Networks: []string{networkName},
+ NetworkAliases: map[string][]string{
+ networkName: {"redis"},
+ },
+ WaitingFor: wait.ForListeningPort("6379/tcp").WithStartupTimeout(60 * time.Second),
+ }
+
+ container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
+ ContainerRequest: req,
+ Started: true,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("starting redis: %w", err)
+ }
+
+ host, err := container.Host(ctx)
+ if err != nil {
+ return nil, fmt.Errorf("getting redis host: %w", err)
+ }
+
+ mappedPort, err := container.MappedPort(ctx, "6379/tcp")
+ if err != nil {
+ return nil, fmt.Errorf("getting redis port: %w", err)
+ }
+
+ url := fmt.Sprintf("redis://%s:%d", host, mappedPort.Int())
+
+ return &RedisService{
+ container: container,
+ url: url,
+ }, nil
+}
diff --git a/backend-go/internal/testutil/infra/stack.go b/backend-go/internal/testutil/infra/stack.go
new file mode 100644
index 0000000000..9dfa6e27c4
--- /dev/null
+++ b/backend-go/internal/testutil/infra/stack.go
@@ -0,0 +1,72 @@
+package infra
+
+import (
+ "context"
+ "log"
+ "os"
+
+ "github.com/testcontainers/testcontainers-go"
+
+ "github.com/infisical/api/internal/config"
+ "github.com/infisical/api/internal/database/pg"
+)
+
+// Stack holds references to running containers and provides accessors
+// for connection info, config, and DB pools.
+type Stack struct {
+ postgres *PostgresService
+ redis *RedisService
+ nodejs *NodeJSService
+ network testcontainers.Network
+ cfg *config.Config
+ db pg.DB
+}
+
+func (s *Stack) Postgres() *PostgresService { return s.postgres }
+func (s *Stack) Redis() *RedisService { return s.redis }
+func (s *Stack) NodeJS() *NodeJSService { return s.nodejs }
+func (s *Stack) Config() *config.Config { return s.cfg }
+func (s *Stack) DB() pg.DB { return s.db }
+
+// Stop tears down all containers, the network, and closes the DB pool.
+func (s *Stack) Stop() {
+ ctx := context.Background()
+
+ if s.db != nil {
+ s.db.Close()
+ }
+ if s.nodejs != nil {
+ if err := s.nodejs.container.Terminate(ctx); err != nil {
+ log.Printf("infra.Stop: terminate nodejs: %v", err)
+ }
+ }
+ if s.redis != nil {
+ if err := s.redis.container.Terminate(ctx); err != nil {
+ log.Printf("infra.Stop: terminate redis: %v", err)
+ }
+ }
+ if s.postgres != nil {
+ if err := s.postgres.container.Terminate(ctx); err != nil {
+ log.Printf("infra.Stop: terminate postgres: %v", err)
+ }
+ }
+ if s.network != nil {
+ if err := s.network.Remove(ctx); err != nil {
+ log.Printf("infra.Stop: remove network: %v", err)
+ }
+ }
+}
+
+// setEnv sets environment variables so config.LoadConfig() picks up
+// the dynamically assigned ports from the running containers.
+func (s *Stack) setEnv() {
+ if s.postgres != nil {
+ os.Setenv("DB_CONNECTION_URI", s.postgres.URI())
+ }
+ if s.redis != nil {
+ os.Setenv("REDIS_URL", s.redis.URL())
+ }
+ os.Setenv("AUTH_SECRET", AuthSecret)
+ os.Setenv("ENCRYPTION_KEY", EncryptionKey)
+ os.Setenv("NODE_ENV", NodeEnv)
+}
diff --git a/backend-go/internal/testutil/seed.go b/backend-go/internal/testutil/seed.go
deleted file mode 100644
index f79c3dc8a0..0000000000
--- a/backend-go/internal/testutil/seed.go
+++ /dev/null
@@ -1,173 +0,0 @@
-package testutil
-
-import (
- "crypto/rand"
- "fmt"
- "log"
- "testing"
-
- "github.com/go-resty/resty/v2"
-)
-
-// ProjectSeed contains IDs for a project created via the Node.js API.
-type ProjectSeed struct {
- ID string
- Slug string
- EnvSlug string // default environment created with the project
-}
-
-// bootstrap calls the admin bootstrap API to create the initial user, org,
-// and machine identity, then logs in to obtain a user JWT.
-// Called once during SetupInfra. Uses log.Fatalf since it runs in TestMain.
-func (infra *TestInfra) bootstrap() {
- client := resty.New().SetBaseURL(infra.NodeJSURL)
-
- // Step 1: Bootstrap — creates admin user, org, and machine identity.
- var bootstrapResp map[string]any
- resp, err := client.R().
- SetBody(map[string]any{
- "email": "[email protected]",
- "password": "testpassword123",
- "organization": "test-org",
- }).
- SetResult(&bootstrapResp).
- Post("/api/v1/admin/bootstrap")
- if err != nil {
- log.Fatalf("testutil.bootstrap: request failed: %v", err)
- }
- if resp.IsError() {
- log.Fatalf("testutil.bootstrap: returned %d: %s", resp.StatusCode(), resp.String())
- }
-
- infra.OrgID = jsonStr(bootstrapResp, "organization.id")
- infra.IdentityToken = jsonStr(bootstrapResp, "identity.credentials.token")
- infra.UserEmail = jsonStr(bootstrapResp, "user.email")
- infra.UserID = jsonStr(bootstrapResp, "user.id")
-
- // Step 2: Login as the user to get a user JWT.
- var loginResp map[string]any
- resp, err = client.R().
- SetBody(map[string]any{
- "email": infra.UserEmail,
- "password": "testpassword123",
- }).
- SetResult(&loginResp).
- Post("/api/v3/auth/login")
- if err != nil {
- log.Fatalf("testutil.bootstrap: login request failed: %v", err)
- }
- if resp.IsError() {
- log.Fatalf("testutil.bootstrap: login returned %d: %s", resp.StatusCode(), resp.String())
- }
- infra.UserToken = jsonStr(loginResp, "accessToken")
-
- infra.client = client
-}
-
-// MustCreateProject creates a new project via the Node.js API.
-// Safe to call from TestMain — uses log.Fatalf on error.
-func (infra *TestInfra) MustCreateProject(name string) *ProjectSeed {
- var projectResp map[string]any
- resp, err := infra.client.R().
- SetAuthToken(infra.IdentityToken).
- SetBody(map[string]any{
- "projectName": name,
- "slug": fmt.Sprintf("test-%s", name),
- "type": "secret-manager",
- }).
- SetResult(&projectResp).
- Post("/api/v1/projects")
- if err != nil {
- log.Fatalf("testutil.MustCreateProject: request failed: %v", err)
- }
- if resp.IsError() {
- log.Fatalf("testutil.MustCreateProject: returned %d: %s", resp.StatusCode(), resp.String())
- }
-
- return &ProjectSeed{
- ID: jsonStr(projectResp, "project.id"),
- Slug: jsonStr(projectResp, "project.slug"),
- EnvSlug: "dev",
- }
-}
-
-// CreateProject creates a new project via the Node.js API and returns its metadata.
-func (infra *TestInfra) CreateProject(t *testing.T, name string) *ProjectSeed {
- t.Helper()
-
- b := make([]byte, 4)
- rand.Read(b)
- slug := fmt.Sprintf("t-%s-%x", name, b)
- if len(slug) > 36 {
- slug = slug[:36]
- }
-
- var projectResp map[string]any
- resp, err := infra.client.R().
- SetAuthToken(infra.IdentityToken).
- SetBody(map[string]any{
- "projectName": name,
- "slug": slug,
- "type": "secret-manager",
- }).
- SetResult(&projectResp).
- Post("/api/v1/projects")
- if err != nil {
- t.Fatalf("testutil.CreateProject: request failed: %v", err)
- }
- if resp.IsError() {
- t.Fatalf("testutil.CreateProject: returned %d: %s", resp.StatusCode(), resp.String())
- }
-
- return &ProjectSeed{
- ID: jsonStr(projectResp, "project.id"),
- Slug: jsonStr(projectResp, "project.slug"),
- EnvSlug: "dev",
- }
-}
-
-// DeleteProject deletes a project via the Node.js API.
-func (infra *TestInfra) DeleteProject(t *testing.T, projectID string) {
- t.Helper()
-
- resp, err := infra.client.R().
- SetAuthToken(infra.IdentityToken).
- Delete("/api/v1/projects/" + projectID)
- if err != nil {
- t.Fatalf("testutil.DeleteProject: request failed: %v", err)
- }
- if resp.IsError() {
- t.Fatalf("testutil.DeleteProject: returned %d: %s", resp.StatusCode(), resp.String())
- }
-}
-
-// jsonStr extracts a string value from a nested JSON map using dot-separated path.
-func jsonStr(m map[string]any, path string) string {
- keys := splitDotPath(path)
- current := any(m)
-
- for _, key := range keys {
- obj, ok := current.(map[string]any)
- if !ok {
- return ""
- }
- current = obj[key]
- }
-
- s, _ := current.(string)
- return s
-}
-
-// splitDotPath splits a dot-separated path into keys.
-func splitDotPath(path string) []string {
- var keys []string
- start := 0
- for i := 0; i < len(path); i++ {
- if path[i] == '.' {
- keys = append(keys, path[start:i])
- start = i + 1
- }
- }
- keys = append(keys, path[start:])
- return keys
-}