Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: addede new testing guideline prompt, new container linux test setup for hsm
=c643f9ce9c41
diff --git a/backend-go/Makefile b/backend-go/Makefileindex 4684fc181b..59ff6ce0dd 100644--- a/backend-go/Makefile+++ b/backend-go/Makefile@@ -1,4 +1,4 @@-.PHONY: lint lint-fix test test-integration test-all dev build generate+.PHONY: lint lint-fix test test-integration test-all dev build generate test-hsm-image test-hsm# Run linterslint:@@ -25,3 +25,11 @@ build:# Regenerate oapi-codegen-dd code from openapi.yml specsgenerate:go generate ./...++# Build the HSM test container image (requires Docker)+test-hsm-image:+ docker build -t infisical/go-test-backend -f docker-test/Dockerfile docker-test/++# Run HSM integration tests (requires test-hsm-image to be built first)+test-hsm: test-hsm-image+ INFISICAL_RUN_HSM_CONTAINER_TEST=1 go test -v -tags integration ./internal/ee/services/hsm/... -count=1 -timeout 300sdiff --git a/backend-go/cmd/infisical/main.go b/backend-go/cmd/infisical/main.goindex 24d1226b9d..18015de585 100644--- a/backend-go/cmd/infisical/main.go+++ b/backend-go/cmd/infisical/main.go@@ -13,6 +13,8 @@ import ("github.com/infisical/api/internal/config""github.com/infisical/api/internal/database/pg"redisdb "github.com/infisical/api/internal/database/redis"+ "github.com/infisical/api/internal/ee/services/hsm"+ "github.com/infisical/api/internal/ee/services/license""github.com/infisical/api/internal/keystore""github.com/infisical/api/internal/libs/bootstrap""github.com/infisical/api/internal/libs/errutil"@@ -76,11 +78,44 @@ func run(cfg *config.Config, logger *slog.Logger) error {queueSvc := queue.NewService(ctx, logger, redisClient)defer errutil.DeferErr(ctx, queueSvc.Close, "closing queue")+ // Initialize License service early (needed for HSM license check).+ licenseSvc := license.NewService(ctx, logger, &license.Deps{+ Config: cfg,+ DB: db,+ KeyStore: ks,+ })+ defer licenseSvc.Close()++ // Initialize HSM if configured.+ var hsmSvc *hsm.Service+ if cfg.IsHsmConfigured {+ hsmService, hsmErr := hsm.NewService(hsm.Config{+ LibPath: cfg.HSMLibPath,+ Slot: cfg.HSMSlot,+ Pin: cfg.HSMPin,+ KeyLabel: cfg.HSMKeyLabel,+ })+ if hsmErr != nil {+ logger.ErrorContext(ctx, "failed to initialize HSM", slog.Any("error", hsmErr))+ return hsmErr+ }+ defer errutil.DeferErr(ctx, hsmService.Close, "closing HSM")++ features := licenseSvc.GetOnPremFeatures()+ if err := hsmService.StartService(features.HSM); err != nil {+ logger.ErrorContext(ctx, "failed to start HSM service", slog.Any("error", err))+ return err+ }+ logger.InfoContext(ctx, "HSM service started")+ hsmSvc = hsmService+ }+services, cleanup, err := api.NewServices(ctx, &api.Infra{Logger: logger,Config: cfg,DB: db,- HSM: nil,+ HSM: hsmSvc,+ License: licenseSvc,KeyStore: ks,Queue: queueSvc,})diff --git a/backend-go/docker-test/Dockerfile b/backend-go/docker-test/Dockerfilenew file mode 100644index 0000000000..f1311a9095--- /dev/null+++ b/backend-go/docker-test/Dockerfile@@ -0,0 +1,20 @@+# Base image for running Go integration tests that require SoftHSM2.+# Used by testcontainers to run HSM tests inside a container.++FROM golang:1.26-alpine++RUN apk add --no-cache \+ softhsm \+ opensc \+ git \+ gcc \+ musl-dev \+ && mkdir -p /var/lib/softhsm/tokens++# Set default SoftHSM2 library path for tests+ENV SOFTHSM2_LIB=/usr/lib/softhsm/libsofthsm2.so++WORKDIR /app++# Keep container running for exec commands+CMD ["tail", "-f", "/dev/null"]diff --git a/backend-go/internal/hsm/hsm.go b/backend-go/internal/ee/services/hsm/hsm.gosimilarity index 89%rename from backend-go/internal/hsm/hsm.gorename to backend-go/internal/ee/services/hsm/hsm.goindex 564fd9dec3..eeed4c1022 100644--- a/backend-go/internal/hsm/hsm.go+++ b/backend-go/internal/ee/services/hsm/hsm.go@@ -28,10 +28,11 @@ const (// Config holds the HSM connection parameters.type Config struct {- LibPath string- Slot int- Pin string- KeyLabel string+ LibPath string+ Slot int // Slot number (used if TokenLabel is empty)+ TokenLabel string // Token label (preferred over Slot if set)+ Pin string+ KeyLabel string}// Service provides HSM-backed encryption, decryption, and random byte generation.@@ -45,12 +46,19 @@ type Service struct {// NewService loads the PKCS#11 library and opens a session pool to the token.func NewService(cfg Config) (*Service, error) {- slot := cfg.Slot- ctx, err := crypto11.Configure(&crypto11.Config{- Path: cfg.LibPath,- SlotNumber: &slot,- Pin: cfg.Pin,- })+ cryptoCfg := &crypto11.Config{+ Path: cfg.LibPath,+ Pin: cfg.Pin,+ }++ if cfg.TokenLabel != "" {+ cryptoCfg.TokenLabel = cfg.TokenLabel+ } else {+ slot := cfg.Slot+ cryptoCfg.SlotNumber = &slot+ }++ ctx, err := crypto11.Configure(cryptoCfg)if err != nil {return nil, fmt.Errorf("HSM: configuring PKCS#11: %w", err)}@@ -71,7 +79,12 @@ func (s *Service) Close() error {// StartService ensures the required AES and HMAC keys exist on the token,// then runs a self-test to validate the HSM is working correctly.-func (s *Service) StartService() error {+// The licenseAllowsHSM parameter must be true, otherwise returns an error.+func (s *Service) StartService(licenseAllowsHSM bool) error {+ if !licenseAllowsHSM {+ return fmt.Errorf("HSM: your license does not include HSM integration, please upgrade to the Enterprise plan")+ }+if err := s.ensureKeys(); err != nil {return fmt.Errorf("HSM: ensuring keys: %w", err)}@@ -210,12 +223,12 @@ func (s *Service) RandomBytes(n int) ([]byte, error) {// ensureKeys creates the AES and HMAC keys on the token if they don't already exist.func (s *Service) ensureKeys() error {- // AES key.- aesKey, err := s.ctx.FindKey(nil, []byte(s.config.KeyLabel))+ // AES key - use FindKeys (returns empty slice if not found, unlike FindKey which errors).+ aesKeys, err := s.ctx.FindKeys(nil, []byte(s.config.KeyLabel))if err != nil {return fmt.Errorf("finding AES key: %w", err)}- if aesKey == nil {+ if len(aesKeys) == 0 {_, err = s.ctx.GenerateSecretKeyWithLabel([]byte(s.config.KeyLabel),[]byte(s.config.KeyLabel),@@ -229,11 +242,11 @@ func (s *Service) ensureKeys() error {// HMAC key.hmacLabel := s.config.KeyLabel + "_HMAC"- hmacKey, err := s.ctx.FindKey(nil, []byte(hmacLabel))+ hmacKeys, err := s.ctx.FindKeys(nil, []byte(hmacLabel))if err != nil {return fmt.Errorf("finding HMAC key: %w", err)}- if hmacKey == nil {+ if len(hmacKeys) == 0 {_, err = s.ctx.GenerateSecretKeyWithLabel([]byte(hmacLabel),[]byte(hmacLabel),diff --git a/backend-go/internal/hsm/hsm_test.go b/backend-go/internal/ee/services/hsm/hsm_integration_test.gosimilarity index 76%rename from backend-go/internal/hsm/hsm_test.gorename to backend-go/internal/ee/services/hsm/hsm_integration_test.goindex bd71856dde..0f7ed3e4ba 100644--- a/backend-go/internal/hsm/hsm_test.go+++ b/backend-go/internal/ee/services/hsm/hsm_integration_test.go@@ -1,3 +1,5 @@+//go:build integration+package hsm_testimport (@@ -9,22 +11,40 @@ import ("github.com/stretchr/testify/assert""github.com/stretchr/testify/require"- "github.com/infisical/api/internal/hsm"+ "github.com/infisical/api/internal/ee/services/hsm"+ "github.com/infisical/api/internal/testutil/infra")-// setupHSM initializes a SoftHSM2 token and returns a ready HSM service.-// Skips the test if SOFTHSM2_LIB is not set.+var runner = infra.NewContainerTest(+ "infisical/go-test-backend",+ "INFISICAL_HSM_TEST_INSIDE",+ "INFISICAL_RUN_HSM_CONTAINER_TEST",+).+ WithTestPath("./internal/ee/services/hsm/...").+ WithBuildTags("integration").+ WithEnv("SOFTHSM2_LIB", "/usr/lib/softhsm/libsofthsm2.so")++func TestMain(m *testing.M) {+ if runner.IsInsideContainer() {+ os.Exit(m.Run())+ }++ os.Exit(runner.MustRun())+}++// ============================================================================+// HSM tests (run inside the container)+// ============================================================================+func setupHSM(t *testing.T) *hsm.Service {t.Helper()- libPath := os.Getenv("SOFTHSM2_LIB")- if libPath == "" {- t.Skip("Skipping HSM tests: SOFTHSM2_LIB environment variable not set. Set it to the path of libsofthsm2.so to enable HSM tests.")+ if !runner.IsInsideContainer() {+ t.Skip("skipping: not inside test container")}- if _, err := exec.LookPath("softhsm2-util"); err != nil {- t.Skip("Skipping HSM tests: softhsm2-util not found in PATH")- }+ libPath := os.Getenv("SOFTHSM2_LIB")+ require.NotEmpty(t, libPath, "SOFTHSM2_LIB not set")tokenDir := t.TempDir()confPath := filepath.Join(tokenDir, "softhsm2.conf")@@ -43,15 +63,15 @@ func setupHSM(t *testing.T) *hsm.Service {require.NoError(t, err, "softhsm2-util: "+string(out))svc, err := hsm.NewService(hsm.Config{- LibPath: libPath,- Slot: 0,- Pin: "1234",- KeyLabel: "test-infisical",+ LibPath: libPath,+ TokenLabel: "test-token",+ Pin: "1234",+ KeyLabel: "test-infisical",})require.NoError(t, err)t.Cleanup(func() { svc.Close() })- require.NoError(t, svc.StartService())+ require.NoError(t, svc.StartService(true))return svc}@@ -68,8 +88,6 @@ func TestEncrypt_RoundTrip(t *testing.T) {blob, err := svc.Encrypt(plaintext)require.NoError(t, err)-- // Verify blob structure: IV(16) + at least one padded block(16) + HMAC(32).assert.GreaterOrEqual(t, len(blob), 16+16+32)got, err := svc.Decrypt(blob)@@ -110,7 +128,6 @@ func TestDecrypt_TamperedHMAC(t *testing.T) {blob, err := svc.Encrypt([]byte("tamper test"))require.NoError(t, err)- // Flip a byte in the HMAC region (last 32 bytes).blob[len(blob)-1] ^= 0xFF_, err = svc.Decrypt(blob)@@ -123,7 +140,6 @@ func TestDecrypt_TamperedCiphertext(t *testing.T) {blob, err := svc.Encrypt([]byte("tamper ciphertext"))require.NoError(t, err)- // Flip a byte in the ciphertext region (after IV, before HMAC).blob[20] ^= 0xFF_, err = svc.Decrypt(blob)@@ -136,7 +152,6 @@ func TestDecrypt_TamperedIV(t *testing.T) {blob, err := svc.Encrypt([]byte("tamper iv"))require.NoError(t, err)- // Flip a byte in the IV region.blob[0] ^= 0xFF_, err = svc.Decrypt(blob)diff --git a/backend-go/internal/services/license/api.go b/backend-go/internal/ee/services/license/api.gosimilarity index 100%rename from backend-go/internal/services/license/api.gorename to backend-go/internal/ee/services/license/api.godiff --git a/backend-go/internal/services/license/keys/license_public_key.pem b/backend-go/internal/ee/services/license/keys/license_public_key.pemsimilarity index 100%rename from backend-go/internal/services/license/keys/license_public_key.pemrename to backend-go/internal/ee/services/license/keys/license_public_key.pemdiff --git a/backend-go/internal/services/license/license.go b/backend-go/internal/ee/services/license/license.gosimilarity index 98%rename from backend-go/internal/services/license/license.gorename to backend-go/internal/ee/services/license/license.goindex 329bfdb011..fb49d6ae2b 100644--- a/backend-go/internal/services/license/license.go+++ b/backend-go/internal/ee/services/license/license.go@@ -460,3 +460,11 @@ func (s *Service) Close() {func (s *Service) GetInstanceType() InstanceType { return s.instanceType }func (s *Service) IsValidLicense() bool { return s.isValid }++// GetOnPremFeatures returns a copy of the on-prem feature set.+// For cloud instances, this returns the default features (use GetPlan for org-specific features).+func (s *Service) GetOnPremFeatures() FeatureSet {+ s.mu.RLock()+ defer s.mu.RUnlock()+ return s.onPremFeatures+}diff --git a/backend-go/internal/services/license/license_test.go b/backend-go/internal/ee/services/license/license_test.gosimilarity index 100%rename from backend-go/internal/services/license/license_test.gorename to backend-go/internal/ee/services/license/license_test.godiff --git a/backend-go/internal/services/license/types.go b/backend-go/internal/ee/services/license/types.gosimilarity index 100%rename from backend-go/internal/services/license/types.gorename to backend-go/internal/ee/services/license/types.godiff --git a/backend-go/internal/server/api/api.go b/backend-go/internal/server/api/api.goindex 9e6840797e..d12d9482e7 100644--- a/backend-go/internal/server/api/api.go+++ b/backend-go/internal/server/api/api.go@@ -7,6 +7,7 @@ import ("github.com/infisical/api/internal/config""github.com/infisical/api/internal/database/pg"+ "github.com/infisical/api/internal/ee/services/license""github.com/infisical/api/internal/keystore""github.com/infisical/api/internal/queue""github.com/infisical/api/internal/services/kms"@@ -18,6 +19,7 @@ type Infra struct {Config *config.ConfigDB pg.DBHSM kms.HsmService+ License *license.ServiceKeyStore keystore.KeyStoreQueue *queue.Service}diff --git a/backend-go/internal/server/api/platform_services.go b/backend-go/internal/server/api/platform_services.goindex b59f9df475..7d9c1a57f1 100644--- a/backend-go/internal/server/api/platform_services.go+++ b/backend-go/internal/server/api/platform_services.go@@ -5,11 +5,11 @@ import ("fmt""github.com/infisical/api/internal/ee/services/externalkms"+ "github.com/infisical/api/internal/ee/services/license""github.com/infisical/api/internal/services/assumeprivilege""github.com/infisical/api/internal/services/auditlog""github.com/infisical/api/internal/services/auth/apiauth""github.com/infisical/api/internal/services/kms"- "github.com/infisical/api/internal/services/license""github.com/infisical/api/internal/services/permission""github.com/infisical/api/internal/services/project")@@ -46,12 +46,6 @@ func newPlatformServices(ctx context.Context, infra *Infra) (*PlatformServices,return nil, fmt.Errorf("kms start: %w", err)}- licenseSvc := license.NewService(ctx, infra.Logger, &license.Deps{- Config: infra.Config,- DB: infra.DB,- KeyStore: infra.KeyStore,- })-permissionSvc := permission.NewService(ctx, infra.Logger, &permission.Deps{DB: infra.DB})projectSvc := project.NewService(ctx, infra.Logger, &project.Deps{DB: infra.DB})@@ -71,7 +65,7 @@ func newPlatformServices(ctx context.Context, infra *Infra) (*PlatformServices,auditLogQueueHandler := auditlog.NewQueueHandler(ctx, infra.Logger, &auditlog.QueueHandlerDeps{DB: infra.DB,Project: projectSvc,- License: licenseSvc,+ License: infra.License,Config: infra.Config,KeyStore: infra.KeyStore,})@@ -81,7 +75,7 @@ func newPlatformServices(ctx context.Context, infra *Infra) (*PlatformServices,Authenticator: authenticator,Permission: permissionSvc,KMS: kmsSvc,- License: licenseSvc,+ License: infra.License,Project: projectSvc,AuditLog: auditLogSvc,AssumePrivilege: assumePrivilegeSvc,diff --git a/backend-go/internal/services/auditlog/queue_handler.go b/backend-go/internal/services/auditlog/queue_handler.goindex 60f5fa3913..f46ada28ad 100644--- a/backend-go/internal/services/auditlog/queue_handler.go+++ b/backend-go/internal/services/auditlog/queue_handler.go@@ -13,9 +13,9 @@ import ("github.com/infisical/api/internal/config""github.com/infisical/api/internal/database/pg"+ "github.com/infisical/api/internal/ee/services/license""github.com/infisical/api/internal/keystore""github.com/infisical/api/internal/queue"- "github.com/infisical/api/internal/services/license""github.com/infisical/api/internal/services/project")diff --git a/backend-go/internal/testutil/infra/container.go b/backend-go/internal/testutil/infra/container.gonew file mode 100644index 0000000000..0a870ccbd3--- /dev/null+++ b/backend-go/internal/testutil/infra/container.go@@ -0,0 +1,162 @@+//go:build integration++package infra++import (+ "context"+ "fmt"+ "log"+ "os"+ "path/filepath"++ "github.com/docker/docker/api/types/container"+ "github.com/testcontainers/testcontainers-go"+ "github.com/testcontainers/testcontainers-go/wait"+)++// ContainerTestRunner configures and runs Go tests inside a Docker container.+// Use this for tests that require specific system dependencies (e.g., SoftHSM).+type ContainerTestRunner struct {+ image string+ insideEnvVar string+ optInEnvVar string+ testPath string+ buildTags string+ env map[string]string+}++// NewContainerTest creates a new container test runner.+// - image: full Docker image name (e.g., "infisical/go-test-backend")+// - insideEnvVar: env var set inside container to prevent infinite loop (e.g., "INFISICAL_HSM_TEST_INSIDE")+// - optInEnvVar: env var that must be "1" to run tests (e.g., "INFISICAL_RUN_HSM_CONTAINER_TEST")+func NewContainerTest(image, insideEnvVar, optInEnvVar string) *ContainerTestRunner {+ return &ContainerTestRunner{+ image: image,+ insideEnvVar: insideEnvVar,+ optInEnvVar: optInEnvVar,+ env: make(map[string]string),+ }+}++// WithTestPath sets the Go test path (e.g., "./internal/ee/services/hsm/...").+func (r *ContainerTestRunner) WithTestPath(path string) *ContainerTestRunner {+ r.testPath = path+ return r+}++// WithBuildTags sets the build tags for go test (e.g., "integration").+func (r *ContainerTestRunner) WithBuildTags(tags string) *ContainerTestRunner {+ r.buildTags = tags+ return r+}++// WithEnv adds an environment variable to pass to the container.+func (r *ContainerTestRunner) WithEnv(key, value string) *ContainerTestRunner {+ r.env[key] = value+ return r+}++// IsInsideContainer returns true if running inside the test container.+func (r *ContainerTestRunner) IsInsideContainer() bool {+ return os.Getenv(r.insideEnvVar) == "1"+}++// isOptedIn returns true if the user has opted in to run container tests.+func (r *ContainerTestRunner) isOptedIn() bool {+ return os.Getenv(r.optInEnvVar) == "1"+}++// MustRun pulls the image and runs go test inside the container.+// Returns 0 if opt-in env var is not set (skip).+// Uses log.Fatalf on setup errors.+func (r *ContainerTestRunner) MustRun() int {+ if !r.isOptedIn() {+ log.Printf("infra: skipping container test (%s not set)", r.optInEnvVar)+ return 0+ }++ code, err := r.run(context.Background())+ if err != nil {+ log.Fatalf("infra: container test failed: %v", err)+ }+ return code+}++func (r *ContainerTestRunner) run(ctx context.Context) (int, error) {+ projectRoot, err := findProjectRoot()+ if err != nil {+ return 1, fmt.Errorf("finding project root: %w", err)+ }++ env := map[string]string{+ r.insideEnvVar: "1",+ "CGO_ENABLED": "1",+ }+ for k, v := range r.env {+ env[k] = v+ }++ req := testcontainers.GenericContainerRequest{+ ContainerRequest: testcontainers.ContainerRequest{+ Image: r.image,+ HostConfigModifier: func(hc *container.HostConfig) {+ hc.Binds = []string{projectRoot + ":/app"}+ },+ Env: env,+ WaitingFor: wait.ForLog(""),+ },+ Started: true,+ }++ ctr, err := testcontainers.GenericContainer(ctx, req)+ if err != nil {+ return 1, fmt.Errorf("creating container: %w", err)+ }+ defer func() {+ if termErr := ctr.Terminate(ctx); termErr != nil {+ log.Printf("infra: failed to terminate container: %v", termErr)+ }+ }()++ cmd := []string{"go", "test", "-v"}+ if r.buildTags != "" {+ cmd = append(cmd, "-tags="+r.buildTags)+ }+ cmd = append(cmd, r.testPath)++ exitCode, outputReader, err := ctr.Exec(ctx, cmd)+ if err != nil {+ return 1, fmt.Errorf("executing tests: %w", err)+ }++ buf := make([]byte, 4096)+ for {+ n, readErr := outputReader.Read(buf)+ if n > 0 {+ _, _ = os.Stdout.Write(buf[:n])+ }+ if readErr != nil {+ break+ }+ }++ return exitCode, nil+}++func findProjectRoot() (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("go.mod not found")+ }+ dir = parent+ }+}diff --git a/backend-go/llm/TESTING_GUIDELINE.md b/backend-go/llm/TESTING_GUIDELINE.mdnew file mode 100644index 0000000000..16523c8ce4--- /dev/null+++ b/backend-go/llm/TESTING_GUIDELINE.md@@ -0,0 +1,390 @@+# Go Testing Guide++You write tests to constrain behavior, not to hit coverage targets. Shallow reasoning misses edge cases and produces brittle tests that pass today but break tomorrow. Every test you write should answer: "what contract does this code promise, and what breaks if someone violates it?"++## Core Rules++- Table-driven tests MUST use named subtests — every test case needs a `name` field passed to `t.Run`.+- Integration tests MUST use build tags (`//go:build integration`) to separate from unit tests.+- Tests MUST NOT depend on execution order — each test MUST be independently runnable.+- Packages with goroutines SHOULD use `goleak.VerifyTestMain` in `TestMain` to detect goroutine leaks.+- Use testify as helpers, not a replacement for the standard library.+- Mock interfaces, not concrete types.+- Run tests with `-race` in CI.++## Test Naming++Follow the convention `Test<FunctionName>_<Scenario>`:++```go+func TestGetSecretByName_ReturnsErrWhenNotFound(t *testing.T) { ... }+func TestListSecrets_FiltersByEnvironment(t *testing.T) { ... }+func TestExpandSecrets_HandlesCircularReferences(t *testing.T) { ... }+```++The function name anchors what's under test. The scenario describes the specific behavior being verified. Together they read as a sentence: "Test GetSecretByName returns err when not found."++## Table-Driven Tests++Table-driven tests are the default style. They consolidate related scenarios that share the same setup/assertion shape into a single function. If multiple test setups can be organized together, prefer one table-driven test over many standalone functions.++Every entry MUST have a `name` field, and every entry MUST be run inside `t.Run`:++```go+func TestResolveSecretPath_Normalization(t *testing.T) {+ tests := []struct {+ name string+ input string+ expected string+ }{+ {+ name: "root path stays unchanged",+ input: "/",+ expected: "/",+ },+ {+ name: "trailing slash is stripped",+ input: "/secrets/prod/",+ expected: "/secrets/prod",+ },+ {+ name: "empty string defaults to root",+ input: "",+ expected: "/",+ },+ {+ name: "double slashes are collapsed",+ input: "/secrets//prod",+ expected: "/secrets/prod",+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ result := ResolveSecretPath(tc.input)+ assert.Equal(t, tc.expected, result)+ })+ }+}+```++### When to reach for table-driven tests++Use them when multiple cases share the same arrange/act/assert structure but differ in inputs and expected outputs. Do NOT force unrelated scenarios into one table — if the setup or assertion logic diverges significantly between cases, write separate test functions.++### Embedding behavior in table entries++For cases where each scenario needs slightly different setup or assertions, use function fields:++```go+func TestPermissionChecker_SecretAccess(t *testing.T) {+ tests := []struct {+ name string+ setup func(t *testing.T) *project.SecretAccessChecker+ check func(checker *project.SecretAccessChecker) bool+ allowed bool+ }{+ {+ name: "read allowed when ability grants read on environment",+ setup: func(t *testing.T) *project.SecretAccessChecker {+ ability := buildAbility(t, project.SecretActionReadValue, "production", "/")+ return project.NewSecretAccessChecker(ability)+ },+ check: func(c *project.SecretAccessChecker) bool {+ return c.CanReadSecretValue("production", "/", "DB_HOST", nil)+ },+ allowed: true,+ },+ {+ name: "read denied when ability lacks environment",+ setup: func(t *testing.T) *project.SecretAccessChecker {+ ability := buildAbility(t, project.SecretActionReadValue, "staging", "/")+ return project.NewSecretAccessChecker(ability)+ },+ check: func(c *project.SecretAccessChecker) bool {+ return c.CanReadSecretValue("production", "/", "DB_HOST", nil)+ },+ allowed: false,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ checker := tc.setup(t)+ got := tc.check(checker)+ assert.Equal(t, tc.allowed, got)+ })+ }+}+```++## Mocking++Mock interfaces, never concrete types. This aligns with the codebase rule that interfaces are consumer-defined.++Define mock structs in the test file, next to the test that uses them. Only stub the methods the test actually calls:++```go+type mockSecretsService struct {+ listFn func(ctx context.Context, opts secrets.ListOpts) ([]secrets.Secret, error)+}++func (m *mockSecretsService) ListSecrets(ctx context.Context, opts secrets.ListOpts) ([]secrets.Secret, error) {+ return m.listFn(ctx, opts)+}+```++Usage in a test:++```go+func TestListSecretsV4_CallsServiceWithResolvedPath(t *testing.T) {+ var capturedOpts secrets.ListOpts++ svc := &mockSecretsService{+ listFn: func(_ context.Context, opts secrets.ListOpts) ([]secrets.Secret, error) {+ capturedOpts = opts+ return nil, nil+ },+ }++ handler := secret.NewHandler(&secret.Deps{Secrets: svc})+ _, err := handler.ListSecretsV4(ctx, &secret.ListSecretsV4ServiceRequestOptions{+ Query: &secret.ListSecretsV4Query{+ ProjectID: "proj-123",+ Environment: "production",+ SecretPath: nil, // should default to "/"+ },+ })++ require.NoError(t, err)+ assert.Equal(t, "/", capturedOpts.SecretPath)+}+```++Do NOT use a mocking framework that generates mocks for every interface in the codebase. Hand-rolled mocks are small, obvious, and live next to the test that needs them.++## Integration Tests++Integration tests run against real dependencies (Postgres via testcontainers, Redis, etc.) and are separated from unit tests with a build tag.++### Build tag++Every integration test file starts with:++```go+//go:build integration++package mypackage_test+```++This keeps `go test ./...` fast by default. Integration tests run explicitly:++```bash+make test # runs: go test -race -tags=integration ./...+```++### Test database setup++Use the `testutil` package to spin up a Postgres container. The container is shared across tests in the same package via `TestMain`:++```go+//go:build integration++package secrets_test++import (+ "os"+ "testing"++ "go.uber.org/goleak"++ "your/module/internal/testutil"+)++func TestMain(m *testing.M) {+ goleak.VerifyTestMain(m,+ goleak.IgnoreTopFunction("..."), // known benign leaks from drivers, if any+ )++ // testutil.Setup starts containers and applies migrations.+ // It returns a teardown func.+ teardown := testutil.Setup()+ code := m.Run()+ teardown()+ os.Exit(code)+}+```++### Writing an integration test++Each test gets a clean transaction that rolls back at the end, so tests never pollute each other:++```go+func TestCreateSecret_PersistsToDatabase(t *testing.T) {+ db := testutil.AcquireDB(t) // returns a pg.DB scoped to a rolled-back tx++ svc := secrets.NewService(context.Background(), testutil.Logger(t), &secrets.Deps{+ DB: db,+ })++ created, err := svc.CreateSecret(context.Background(), secrets.CreateOpts{+ FolderID: testutil.SeedFolder(t, db, "production", "/"),+ Key: "DB_PASSWORD",+ Value: []byte("hunter2"),+ })++ require.NoError(t, err)+ assert.Equal(t, "DB_PASSWORD", created.Key)++ // Verify it's readable+ fetched, err := svc.GetSecretByName(context.Background(), secrets.GetByNameOpts{+ FolderID: created.FolderID,+ Key: "DB_PASSWORD",+ })+ require.NoError(t, err)+ assert.Equal(t, created.ID, fetched.ID)+}+```++### Seed helpers++Create small helper functions for common test data setup. These belong in `testutil/` or as unexported helpers in the test file:++```go+// testutil/seeds.go+func SeedFolder(t *testing.T, db pg.DB, env, path string) uuid.UUID {+ t.Helper()+ id := uuid.New()+ _, err := db.Primary().Exec(context.Background(),+ `INSERT INTO secret_folders (id, environment, path) VALUES (@id, @env, @path)`,+ pgx.NamedArgs{"id": id, "env": env, "path": path},+ )+ require.NoError(t, err)+ return id+}+```++Always call `t.Helper()` so failure messages point to the calling test, not the seed function.++## Goroutine Leak Detection++Any package that spawns goroutines (background workers, watchers, connection pools) SHOULD use `goleak.VerifyTestMain` in its `TestMain` to catch leaks:++```go+func TestMain(m *testing.M) {+ goleak.VerifyTestMain(m)+}+```++If a known third-party goroutine is benign and cannot be stopped (e.g., a database driver's internal watcher), ignore it explicitly and leave a comment:++```go+goleak.VerifyTestMain(m,+ // pgxpool starts a background health-check goroutine+ goleak.IgnoreTopFunction("github.com/jackc/pgx/v5/pgxpool.(*Pool).backgroundHealthCheck"),+)+```++## Race Detection++All tests — unit and integration — run with `-race` in CI. This catches data races that only manifest under concurrency. Design your tests accordingly:++- Do not share mutable state across parallel subtests without synchronization.+- If a test does `t.Parallel()`, ensure each subtest captures its loop variable (or use Go 1.22+ loop semantics).++```go+for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ // tc is safe here in Go 1.22+; for older versions, shadow it:+ // tc := tc+ result := doSomething(tc.input)+ assert.Equal(t, tc.expected, result)+ })+}+```++## Testify Usage++Use `require` for preconditions that must hold for the rest of the test to make sense. Use `assert` for the actual verification:++```go+func TestDecryptSecret_RoundTrip(t *testing.T) {+ key, err := kms.GenerateDataKey(ctx)+ require.NoError(t, err) // if this fails, nothing below is meaningful++ ciphertext, err := kms.Encrypt(ctx, key, []byte("plaintext"))+ require.NoError(t, err)++ plaintext, err := kms.Decrypt(ctx, key, ciphertext)+ assert.NoError(t, err) // the behavior we're actually testing+ assert.Equal(t, []byte("plaintext"), plaintext)+}+```++Do NOT use testify's suite package. Standard `Test` functions with table-driven subtests are simpler and compose better with Go's tooling (`go test -run`, `-count`, `-parallel`).++## Error Path Testing++Test the sad paths. Services in this codebase return structured errors via `errutil`. Verify both the error type and the message context:++```go+func TestGetSecret_ReturnsNotFoundForMissingKey(t *testing.T) {+ svc := setupService(t)++ _, err := svc.GetSecretByName(ctx, secrets.GetByNameOpts{+ FolderID: folderID,+ Key: "NONEXISTENT",+ })++ require.Error(t, err)+ var appErr *errutil.Error+ require.ErrorAs(t, err, &appErr)+ assert.Equal(t, errutil.StatusNotFound, appErr.Status)+}+```++## Context and Logger in Tests++Follow the codebase constructor convention `(ctx, logger, deps)` in tests too. Use `context.Background()` for ctx and a test-scoped logger:++```go+func TestSomething(t *testing.T) {+ ctx := context.Background()+ logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelDebug}))++ svc := myservice.NewService(ctx, logger, &myservice.Deps{+ DB: testDB,+ })+ // ...+}+```++Or use a `testutil.Logger(t)` helper that ties log output to `t.Log` so it only appears on failure:++```go+// testutil/logger.go+func Logger(t *testing.T) *slog.Logger {+ t.Helper()+ return slog.New(slog.NewTextHandler(testWriter{t}, &slog.HandlerOptions{Level: slog.LevelDebug}))+}++type testWriter struct{ t *testing.T }++func (w testWriter) Write(p []byte) (int, error) {+ w.t.Helper()+ w.t.Log(string(p))+ return len(p), nil+}+```++## Checklist Before Submitting++1. `make test` passes (integration tests with `-race`).+2. `make lint` passes — no `//nolint` without a justification comment.+3. Every table-driven test case has a descriptive `name` and runs under `t.Run`.+4. Mocks are hand-rolled against consumer-defined interfaces, not generated against implementations.+5. Integration tests have the `//go:build integration` tag.+6. Seed helpers call `t.Helper()`.+7. `require` is used for preconditions, `assert` for verifications.+8. No test depends on another test running first.