Skip to content

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

feat: configured license and mocking

=581a48dee704
diff --git a/tests/.gitignore b/tests/.gitignore
index 308ae80196..934cd0b320 100644
--- a/tests/.gitignore
+++ b/tests/.gitignore
@@ -1,4 +1,2 @@
# Container logs, written unconditionally so you can tail one while a test hangs.
.logs/
-# Materialized Docker build context for the test image.
-.build-context/
diff --git a/tests/harness/infisical/bootstrap.go b/tests/harness/infisical/bootstrap.go
new file mode 100644
index 0000000000..9c974aa76d
--- /dev/null
+++ b/tests/harness/infisical/bootstrap.go
@@ -0,0 +1,189 @@
+package infisical
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+)
+
+// Credentials the harness bootstraps an instance with.
+//
+// Fixed rather than generated, for the same reason as AUTH_SECRET: a container is
+// adopted by name, so a second test binary inherits an instance it did not create
+// and has to be able to log in as the same administrator.
+const (
+ RootEmail = "[email protected]"
+ RootPassword = "HarnessRootPassword7!"
+ RootOrgName = "harness-root"
+)
+
+// Root is what bootstrapping an instance yields.
+//
+// Three principals come out of one call, and they are deliberately used for
+// different things:
+//
+// - The USER is the only one that can create an organization, because
+// POST /api/v2/organizations checks req.auth.actor !== ActorType.USER. The
+// harness keeps its password privately to mint tenants and never exposes it.
+// - The IDENTITY passes verifySuperAdmin, because isSuperAdmin accepts
+// ActorType.IDENTITY when auth.isInstanceAdmin, which bootstrapInstance arranges.
+// It carries no user-level state a test could corrupt, so it is what instance
+// level suites get.
+// - The organization it creates is incidental. Tenants make their own.
+type Root struct {
+ UserID string
+ Email string
+ Password string
+ OrgID string
+ IdentityID string
+ IdentityToken string
+}
+
+type bootstrapResponse struct {
+ User struct {
+ ID string `json:"id"`
+ Username string `json:"username"`
+ } `json:"user"`
+ Organization struct {
+ ID string `json:"id"`
+ Slug string `json:"slug"`
+ } `json:"organization"`
+ Identity struct {
+ ID string `json:"id"`
+ Credentials struct {
+ Token string `json:"token"`
+ } `json:"credentials"`
+ } `json:"identity"`
+}
+
+// Bootstrap prepares a freshly migrated instance.
+//
+// POST /api/v1/admin/bootstrap is one shot per database: it refuses once
+// serverCfg.initialized is set. An adopted container is therefore already
+// bootstrapped, and the second caller logs in instead.
+func Bootstrap(ctx context.Context, baseURL string) (Root, error) {
+ c := &http.Client{Timeout: 30 * time.Second}
+
+ var out bootstrapResponse
+ code, body, err := post(ctx, c, baseURL+"/api/v1/admin/bootstrap", "", map[string]string{
+ "email": RootEmail,
+ "password": RootPassword,
+ "organization": RootOrgName,
+ }, &out)
+ if err != nil {
+ return Root{}, err
+ }
+
+ switch {
+ case code == http.StatusOK:
+ case alreadyBootstrapped(code, body):
+ return adopt(ctx, c, baseURL)
+ default:
+ return Root{}, fmt.Errorf("infisical: bootstrap returned %d: %s", code, trunc(body))
+ }
+
+ root := Root{
+ UserID: out.User.ID,
+ Email: RootEmail,
+ Password: RootPassword,
+ OrgID: out.Organization.ID,
+ IdentityID: out.Identity.ID,
+ IdentityToken: out.Identity.Credentials.Token,
+ }
+
+ // bootstrapInstance sets allowSignUp:false whenever the instance is not cloud.
+ // Without turning it back on, creating a second real user is impossible, and
+ // that is the only path to a non-administrator principal.
+ if err := allowSignUp(ctx, c, baseURL, root.IdentityToken); err != nil {
+ return Root{}, err
+ }
+ return root, nil
+}
+
+func adopt(ctx context.Context, c *http.Client, baseURL string) (Root, error) {
+ var login struct {
+ AccessToken string `json:"accessToken"`
+ }
+ code, body, err := post(ctx, c, baseURL+"/api/v3/auth/login", "", map[string]string{
+ "email": RootEmail,
+ "password": RootPassword,
+ }, &login)
+ if err != nil {
+ return Root{}, err
+ }
+ if code != http.StatusOK {
+ return Root{}, fmt.Errorf(
+ "infisical: this instance is already bootstrapped but the harness root cannot log in (%d: %s).\n"+
+ "It was probably bootstrapped by something other than the harness. Run `inf down` and retry.",
+ code, trunc(body))
+ }
+ return Root{Email: RootEmail, Password: RootPassword}, nil
+}
+
+func allowSignUp(ctx context.Context, c *http.Client, baseURL, token string) error {
+ code, body, err := patch(ctx, c, baseURL+"/api/v1/admin/config", token, map[string]any{
+ "allowSignUp": true,
+ })
+ if err != nil {
+ return err
+ }
+ if code != http.StatusOK {
+ return fmt.Errorf("infisical: re-enabling signup returned %d: %s", code, trunc(body))
+ }
+ return nil
+}
+
+// alreadyBootstrapped recognises the one failure that is expected and recoverable.
+func alreadyBootstrapped(code int, body string) bool {
+ return code == http.StatusBadRequest && bytes.Contains([]byte(body), []byte("already"))
+}
+
+func post(ctx context.Context, c *http.Client, url, token string, in, out any) (int, string, error) {
+ return do(ctx, c, http.MethodPost, url, token, in, out)
+}
+
+func patch(ctx context.Context, c *http.Client, url, token string, in any) (int, string, error) {
+ return do(ctx, c, http.MethodPatch, url, token, in, nil)
+}
+
+func do(ctx context.Context, c *http.Client, method, url, token string, in, out any) (int, string, error) {
+ buf, err := json.Marshal(in)
+ if err != nil {
+ return 0, "", err
+ }
+ req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(buf))
+ if err != nil {
+ return 0, "", err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ // completeAccount rejects a request without one, so send it everywhere.
+ req.Header.Set("User-Agent", "infisical-harness")
+ if token != "" {
+ req.Header.Set("Authorization", "Bearer "+token)
+ }
+
+ resp, err := c.Do(req)
+ if err != nil {
+ return 0, "", fmt.Errorf("infisical: %s %s: %w", method, url, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ body, _ := io.ReadAll(resp.Body)
+ if out != nil && resp.StatusCode == http.StatusOK {
+ if err := json.Unmarshal(body, out); err != nil {
+ return resp.StatusCode, string(body), fmt.Errorf("infisical: decoding %s: %w", url, err)
+ }
+ }
+ return resp.StatusCode, string(body), nil
+}
+
+func trunc(s string) string {
+ if len(s) > 400 {
+ return s[:400] + "..."
+ }
+ return s
+}
diff --git a/tests/harness/infisical/image.go b/tests/harness/infisical/image.go
new file mode 100644
index 0000000000..1f629e6161
--- /dev/null
+++ b/tests/harness/infisical/image.go
@@ -0,0 +1,144 @@
+package infisical
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra"
+)
+
+// ImageEnv names a prebuilt image to use instead of building one. CI sets it from a
+// tag built in a prior job, so the parallel test binaries do not each rediscover the
+// same build.
+const ImageEnv = "INFISICAL_TEST_IMAGE"
+
+// localTag is mutable on purpose. It is a convenience handle; the image ID returned
+// by the build is the thing that carries identity.
+const localTag = "infisical-test:local"
+
+// Image is a built application image. ID is the Docker content address, which is
+// what goes into the container name so that changed code means a fresh container.
+type Image struct {
+ Ref string // what to run: a tag, or the ID
+ ID string // sha256:...
+}
+
+// ShortID is the container-name fragment.
+func (i Image) ShortID() string {
+ id := strings.TrimPrefix(i.ID, "sha256:")
+ if len(id) > 12 {
+ return id[:12]
+ }
+ return id
+}
+
+// ResolveImage returns the application image to test against.
+//
+// Docker's build cache already answers "has anything changed", exactly, so the
+// harness does not compute a content hash of its own. It builds, and takes the image
+// ID Docker hands back. A no-op rebuild is context transfer plus layer digest checks;
+// backend/.dockerignore already keeps node_modules and dist out of the context.
+//
+// The build context is backend/ verbatim. Nothing is substituted: entitlements come
+// from the stubbed license server at runtime, not from a patched source tree.
+func ResolveImage(ctx context.Context, repoRoot string, log infra.Logger) (Image, error) {
+ if ref := os.Getenv(ImageEnv); ref != "" {
+ id, err := inspectID(ctx, ref)
+ if err != nil {
+ return Image{}, fmt.Errorf("infisical: %s=%q could not be inspected: %w", ImageEnv, ref, err)
+ }
+ log.Infof("image %s (from %s) -> %s", ref, ImageEnv, short(id))
+ return Image{Ref: ref, ID: id}, nil
+ }
+
+ // Four binaries starting at once would otherwise all build the same context.
+ release, err := infra.Lock("image-build")
+ if err != nil {
+ return Image{}, err
+ }
+ defer release()
+
+ began := time.Now()
+ id, err := build(ctx, repoRoot)
+ if err != nil {
+ return Image{}, err
+ }
+ log.Infof("image %s -> %s (%.1fs)", localTag, short(id), time.Since(began).Seconds())
+ return Image{Ref: localTag, ID: id}, nil
+}
+
+func build(ctx context.Context, repoRoot string) (string, error) {
+ backend := filepath.Join(repoRoot, "backend")
+ if _, err := os.Stat(filepath.Join(backend, "Dockerfile")); err != nil {
+ return "", fmt.Errorf("infisical: no backend/Dockerfile under %s: %w", repoRoot, err)
+ }
+
+ iid, err := os.CreateTemp("", "inf-iid-*")
+ if err != nil {
+ return "", err
+ }
+ iidPath := iid.Name()
+ _ = iid.Close()
+ defer func() { _ = os.Remove(iidPath) }()
+
+ args := []string{"build", "-f", filepath.Join(backend, "Dockerfile"), "-t", localTag, "--iidfile", iidPath}
+ if pin := cliVersion(repoRoot); pin != "" {
+ // Keep the pinned CLI version honest. The Dockerfile carries a matching ARG
+ // default, and check-dockerfile-pins.yml fails a PR when they drift.
+ args = append(args, "--build-arg", "INFISICAL_CLI_VERSION="+pin)
+ }
+ args = append(args, backend)
+
+ cmd := exec.CommandContext(ctx, "docker", args...)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return "", fmt.Errorf("infisical: docker build failed: %w\n%s", err, tail(string(out), 40))
+ }
+
+ b, err := os.ReadFile(iidPath)
+ if err != nil {
+ return "", fmt.Errorf("infisical: reading image id: %w", err)
+ }
+ return strings.TrimSpace(string(b)), nil
+}
+
+func inspectID(ctx context.Context, ref string) (string, error) {
+ out, err := exec.CommandContext(ctx, "docker", "image", "inspect", "-f", "{{.Id}}", ref).CombinedOutput()
+ if err != nil {
+ return "", fmt.Errorf("%w: %s", err, strings.TrimSpace(string(out)))
+ }
+ return strings.TrimSpace(string(out)), nil
+}
+
+func cliVersion(repoRoot string) string {
+ b, err := os.ReadFile(filepath.Join(repoRoot, "build-versions.env"))
+ if err != nil {
+ return ""
+ }
+ for _, line := range strings.Split(string(b), "\n") {
+ if v, ok := strings.CutPrefix(strings.TrimSpace(line), "INFISICAL_CLI_VERSION="); ok {
+ return v
+ }
+ }
+ return ""
+}
+
+func short(id string) string {
+ id = strings.TrimPrefix(id, "sha256:")
+ if len(id) > 12 {
+ return id[:12]
+ }
+ return id
+}
+
+func tail(s string, n int) string {
+ lines := strings.Split(strings.TrimRight(s, "\n"), "\n")
+ if len(lines) > n {
+ lines = lines[len(lines)-n:]
+ }
+ return strings.Join(lines, "\n")
+}
diff --git a/tests/harness/infisical/infisical.go b/tests/harness/infisical/infisical.go
new file mode 100644
index 0000000000..ef736e722f
--- /dev/null
+++ b/tests/harness/infisical/infisical.go
@@ -0,0 +1,158 @@
+// Package infisical runs the application under test.
+//
+// This is the one module that knows what Infisical is. Everything it needs from the
+// product is a Docker image, a set of environment variables, and the OpenAPI spec,
+// which is the whole contract that lets the suite survive a reimplementation.
+package infisical
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/Infisical/infisical/tests/infra"
+ "github.com/Infisical/infisical/tests/infra/mailpit"
+ "github.com/Infisical/infisical/tests/infra/postgres"
+ "github.com/Infisical/infisical/tests/infra/redis"
+ "github.com/Infisical/infisical/tests/infra/wiremock"
+)
+
+const (
+ Key = infra.Key("infisical")
+
+ // backend/Dockerfile: ENV HOST=0.0.0.0, EXPOSE 4000. The standalone image uses
+ // 8080; this is not that image.
+ port = 4000
+
+ // Fixed, never generated per process.
+ //
+ // A container is adopted by name, so a second test binary inherits whatever the
+ // first one started. If these varied, that binary would mint tokens under a
+ // different AUTH_SECRET than the running server validates with, and every
+ // request would fail authentication for no visible reason.
+ //
+ // 32 hex characters, which is the non-FIPS form. The base64 value in
+ // docker-compose.test.yml is the FIPS root-key variant and is not interchangeable.
+ authSecret = "4bnfe4e407b8921c104518903515b218"
+ encryptionKey = "6c1fe4e407b8911c104518103505b218"
+)
+
+type module struct {
+ image Image
+ env map[string]string
+ runModes string
+}
+
+type Option func(*module)
+
+// WithImage pins the image instead of resolving one.
+func WithImage(img Image) Option { return func(m *module) { m.image = img } }
+
+// WithEnv overrides or adds an environment variable.
+func WithEnv(k, v string) Option { return func(m *module) { m.env[k] = v } }
+
+// WithRunModes sets INFISICAL_RUN_MODES. A pod that does not include "api" serves
+// /api/status and no product routes, which is a thing worth asserting.
+func WithRunModes(modes string) Option { return func(m *module) { m.runModes = modes } }
+
+func Module(opts ...Option) infra.Module {
+ m := &module{env: map[string]string{}}
+ for _, o := range opts {
+ o(m)
+ }
+ return m
+}
+
+func (m *module) Key() infra.Key { return Key }
+
+// Requires is the hard floor. env.ts enforces Redis with a zod refine, and the
+// database URI has a default that resolves to a literal "undefined" host, so both
+// fail at connect time rather than parse time if absent.
+func (m *module) Requires() []infra.Key { return []infra.Key{postgres.Key, redis.Key} }
+
+// Optional is consumed if declared. SMTP is what makes user creation possible at
+// all; WireMock is what makes outbound calls and entitlements controllable.
+func (m *module) Optional() []infra.Key { return []infra.Key{mailpit.Key, wiremock.Key} }
+
+func (m *module) Name() infra.NameParts {
+ return infra.NameParts{Module: "infisical", Fingerprint: m.image.ShortID()}
+}
+
+func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error) {
+ if m.image.Ref == "" {
+ return nil, fmt.Errorf("infisical: no image; pass WithImage(ResolveImage(...))")
+ }
+
+ self := d.ContainerName()
+ env := map[string]string{
+ "DB_CONNECTION_URI": postgres.MustFrom(d).DSN(infra.Internal),
+ "REDIS_URL": redis.MustFrom(d).URL(infra.Internal),
+ "AUTH_SECRET": authSecret,
+ "ENCRYPTION_KEY": encryptionKey,
+ "NODE_ENV": "production",
+ "TELEMETRY_ENABLED": "false",
+ "SITE_URL": fmt.Sprintf("http://%s:%d", self, port),
+ }
+ if m.runModes != "" {
+ env["INFISICAL_RUN_MODES"] = m.runModes
+ }
+
+ _, wantSMTP := mailpit.From(d)
+ if mp, ok := mailpit.From(d); ok {
+ e := mp.Endpoint(infra.Internal)
+ env["SMTP_HOST"] = e.Host
+ env["SMTP_PORT"] = fmt.Sprint(e.Port)
+ env["SMTP_FROM_ADDRESS"] = "[email protected]"
+ env["SMTP_FROM_NAME"] = "Infisical Harness"
+ // SMTP_REQUIRE_TLS defaults to true in env.ts. Against Mailpit that is the
+ // usual reason a first attempt silently sends nothing.
+ env["SMTP_REQUIRE_TLS"] = "false"
+ }
+
+ if wm, ok := wiremock.From(d); ok {
+ proxy := wm.ProxyURL(infra.Internal)
+ env["HTTP_PROXY"] = proxy
+ env["HTTPS_PROXY"] = proxy
+ env["NO_PROXY"] = wiremock.NoProxy(postgres.MustFrom(d).Endpoint(infra.Internal).Host,
+ redis.MustFrom(d).Endpoint(infra.Internal).Host)
+ env["NODE_EXTRA_CA_CERTS"] = wiremock.CAPath
+ }
+
+ for k, v := range m.env {
+ env[k] = v
+ }
+
+ c, err := d.Run(ctx, infra.ContainerSpec{
+ Image: m.image.Ref,
+ Env: env,
+ Ports: []int{port},
+ // /api/status is registered before the run-mode guard, so it answers even on
+ // a pod that serves no product routes. It also reports emailConfigured and
+ // redisConfigured, which the harness asserts so a misconfigured SMTP is a
+ // boot failure rather than a mysterious timeout twenty tests later.
+ Ready: readyStrategy(),
+ Check: checkStatus(wantSMTP),
+ })
+ if err != nil {
+ return nil, err
+ }
+ return &Handle{c: c, image: m.image}, nil
+}
+
+// Handle is a running Infisical.
+type Handle struct {
+ c infra.Container
+ image Image
+}
+
+func (h *Handle) Endpoint(m infra.Mode) infra.Endpoint { return h.c.Endpoint(m, port) }
+func (h *Handle) Stop(ctx context.Context) error { return h.c.Stop(ctx) }
+func (h *Handle) Image() Image { return h.image }
+
+// BaseURL is the API root. Almost always External: the Go test process calls it.
+func (h *Handle) BaseURL(m infra.Mode) string { return h.Endpoint(m).URL("http") }
+
+// Logs is what a failure dumps. Under a Shared profile one instance serves every
+// parallel tenant, so a caller filters by org id rather than printing all of it.
+func (h *Handle) Logs(ctx context.Context) (string, error) { return h.c.Logs(ctx) }
+
+func From(d infra.Deps) (*Handle, bool) { return d.Get[*Handle](Key) }
diff --git a/tests/harness/infisical/infisical_test.go b/tests/harness/infisical/infisical_test.go
new file mode 100644
index 0000000000..e19baa60bc
--- /dev/null
+++ b/tests/harness/infisical/infisical_test.go
@@ -0,0 +1,92 @@
+package infisical_test
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/Infisical/infisical/tests/harness/infisical"
+ "github.com/Infisical/infisical/tests/infra"
+ "github.com/Infisical/infisical/tests/infra/mailpit"
+ "github.com/Infisical/infisical/tests/infra/postgres"
+ "github.com/Infisical/infisical/tests/infra/redis"
+ "github.com/Infisical/infisical/tests/internal/spec"
+)
+
+func requireDocker(t *testing.T) {
+ t.Helper()
+ if os.Getenv("INFRA_DOCKER_TESTS") == "" {
+ t.Skip("set INFRA_DOCKER_TESTS=1 to run container tests")
+ }
+}
+
+// bootStack brings up the minimum an Infisical container needs.
+func bootStack(t *testing.T, opts ...infisical.Option) *infisical.Handle {
+ t.Helper()
+ ctx := t.Context()
+ log := infra.NewLogger()
+
+ root, err := infra.RepoRoot()
+ if err != nil {
+ t.Fatalf("repo root: %v", err)
+ }
+ img, err := infisical.ResolveImage(ctx, root, log)
+ if err != nil {
+ t.Fatalf("image: %v", err)
+ }
+
+ mods := []infra.Module{postgres.Module(), redis.Module(), mailpit.Module(),
+ infisical.Module(append([]infisical.Option{infisical.WithImage(img)}, opts...)...)}
+ scopes := map[infra.Key]infra.Scope{}
+ for _, m := range mods {
+ scopes[m.Key()] = infra.Shared
+ }
+ plan, err := infra.Resolve(mods, scopes)
+ if err != nil {
+ t.Fatalf("resolve: %v", err)
+ }
+
+ runner := infra.NewRunner(infra.Workspace(), log)
+ if err := runner.Network(ctx, infra.NetworkName); err != nil {
+ t.Fatalf("network: %v", err)
+ }
+
+ handles := map[infra.Key]infra.Handle{}
+ for _, m := range plan.Modules() {
+ name := m.Name()
+ name.Scope = infra.Test
+ name.ScopeID = "m2boot"
+
+ began := time.Now()
+ h, err := m.Start(ctx, infra.NewDeps(handles, infra.NetworkName, infra.Workspace(), name, runner, log))
+ if err != nil {
+ t.Fatalf("start %s: %v", m.Key(), err)
+ }
+ handles[m.Key()] = h
+ t.Cleanup(func() { _ = h.Stop(context.WithoutCancel(ctx)) })
+ log.Decision("ready", infra.ContainerName(name), h.Endpoint(infra.External), time.Since(began), "")
+ }
+ return handles[infisical.Key].(*infisical.Handle)
+}
+
+func TestInfisical_Boot(t *testing.T) {
+ requireDocker(t)
+ spec.Why(t, `This is the first point where the env contract in the module meets the real
+ application. Everything downstream assumes it holds, and a mistake in it surfaces as
+ a container that exits during migrations with no obvious cause.`)
+
+ app := bootStack(t)
+
+ t.Run("ok/serves the API once Start returns", func(t *testing.T) {
+ if app.BaseURL(infra.External) == "" {
+ t.Fatal("no base URL")
+ }
+ })
+
+ t.Run("ok/the container name carries the image id", func(t *testing.T) {
+ if app.Image().ShortID() == "" {
+ t.Fatal("image has no id, so a code change would adopt a stale container")
+ }
+ })
+}
diff --git a/tests/harness/infisical/ready.go b/tests/harness/infisical/ready.go
new file mode 100644
index 0000000000..6d92cb9756
--- /dev/null
+++ b/tests/harness/infisical/ready.go
@@ -0,0 +1,69 @@
+package infisical
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra"
+)
+
+// status is the subset of GET /api/status the harness reads.
+//
+// The route is registered before the run-mode guard, so it answers even on a pod
+// serving no product routes. That makes it the right readiness probe in every mode.
+type status struct {
+ EmailConfigured bool `json:"emailConfigured"`
+ RedisConfigured bool `json:"redisConfigured"`
+}
+
+// readyStrategy waits for the application to serve /api/status.
+//
+// Deliberately not a log-line wait. Waiting on log output would couple the harness
+// to this implementation's logging format, which is exactly what the suite exists
+// not to depend on: a Go reimplementation emits entirely different lines while
+// /api/status stays identical. A status route is a contract; a log line is not.
+func readyStrategy() infra.Ready {
+ return infra.ForHTTP("/api/status").
+ WithPort(fmt.Sprintf("%d/tcp", port)).
+ WithStatusCodeMatcher(func(code int) bool { return code == http.StatusOK })
+}
+
+// checkStatus runs once the application is up and asserts that the optional modules
+// actually took effect.
+//
+// Separate from the wait strategy because a response matcher returns a bool, and the
+// whole value here is the message. A silently unconfigured SMTP would otherwise
+// surface twenty tests later as an email that never arrives, with nothing pointing
+// at the cause.
+func checkStatus(wantSMTP bool) func(context.Context, infra.Container) error {
+ return func(ctx context.Context, c infra.Container) error {
+ url := c.Endpoint(infra.External, port).URL("http") + "/api/status"
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return err
+ }
+ resp, err := (&http.Client{Timeout: 10 * time.Second}).Do(req)
+ if err != nil {
+ return fmt.Errorf("reading /api/status: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var s status
+ if err := json.NewDecoder(resp.Body).Decode(&s); err != nil {
+ return fmt.Errorf("decoding /api/status: %w", err)
+ }
+
+ if !s.RedisConfigured {
+ return fmt.Errorf("reports redisConfigured=false; REDIS_URL did not take effect")
+ }
+ if wantSMTP && !s.EmailConfigured {
+ return fmt.Errorf("reports emailConfigured=false; SMTP_HOST did not take effect, " +
+ "which would otherwise surface later as an email that never arrives")
+ }
+ return nil
+ }
+}
diff --git a/tests/harness/license/features.go b/tests/harness/license/features.go
new file mode 100644
index 0000000000..6177c250c7
--- /dev/null
+++ b/tests/harness/license/features.go
@@ -0,0 +1,164 @@
+package license
+
+var (
+ ActiveCerts = Feature{V2: "active_certs", V1: ""}
+ AuditLogStreamLimit = Feature{V2: "audit_log_stream_limit", V1: "auditLogStreamLimit"}
+ AuditLogStreams = Feature{V2: "audit_log_streams", V1: "auditLogStreams"}
+ AuditLogs = Feature{V2: "audit_logs", V1: "auditLogs"}
+ AuditRetentionDays = Feature{V2: "audit_retention_days", V1: "auditLogsRetentionDays"}
+ CACRL = Feature{V2: "ca_crl", V1: "caCrl"}
+ CertManager = Feature{V2: "cert_manager", V1: "certManager"}
+ CrossProjectSecretSharing = Feature{V2: "cross_project_secret_sharing", V1: "crossProjectSecretSharing"}
+ CustomAlerts = Feature{V2: "custom_alerts", V1: "customAlerts"}
+ CustomRateLimits = Feature{V2: "custom_rate_limits", V1: "customRateLimits"}
+ DynamicSecret = Feature{V2: "dynamic_secret", V1: "dynamicSecret"}
+ EnforceGoogleSSO = Feature{V2: "enforce_google_sso", V1: "enforceGoogleSSO"}
+ EnforceMFA = Feature{V2: "enforce_mfa", V1: "enforceMfa"}
+ EnterpriseAppConnections = Feature{V2: "enterprise_app_connections", V1: "enterpriseAppConnections"}
+ EnterprisePAMAccount = Feature{V2: "enterprise_pam_account", V1: "enterprisePamAccount"}
+ EnterpriseSecretSyncs = Feature{V2: "enterprise_secret_syncs", V1: "enterpriseSecretSyncs"}
+ EnvironmentLimit = Feature{V2: "environment_limit", V1: "environmentLimit"}
+ EventSubscriptions = Feature{V2: "event_subscriptions", V1: "eventSubscriptions"}
+ ExternalKMS = Feature{V2: "external_kms", V1: "externalKms"}
+ FIPS = Feature{V2: "fips", V1: "fips"}
+ Gateway = Feature{V2: "gateway", V1: "gateway"}
+ GatewayPool = Feature{V2: "gateway_pool", V1: "gatewayPool"}
+ GithubOrgSync = Feature{V2: "github_org_sync", V1: "githubOrgSync"}
+ Groups = Feature{V2: "groups", V1: "groups"}
+ HSM = Feature{V2: "hsm", V1: "hsm"}
+ HoneyTokenLimit = Feature{V2: "honey_token_limit", V1: "honeyTokenLimit"}
+ HoneyTokens = Feature{V2: "honey_tokens", V1: "honeyTokens"}
+ IPAllowlisting = Feature{V2: "ip_allowlisting", V1: "ipAllowlisting"}
+ Identities = Feature{V2: "identities", V1: ""}
+ InstanceUserManagement = Feature{V2: "instance_user_management", V1: "instanceUserManagement"}
+ InternalCAs = Feature{V2: "internal_cas", V1: ""}
+ KMIP = Feature{V2: "kmip", V1: "kmip"}
+ KMSPQC = Feature{V2: "kms_pqc", V1: "kmsPqc"}
+ LDAP = Feature{V2: "ldap", V1: "ldap"}
+ MachineIdentityAuthTemplates = Feature{V2: "machine_identity_auth_templates", V1: "machineIdentityAuthTemplates"}
+ MaxCAs = Feature{V2: "max_cas", V1: "maxCas"}
+ MaxCertificates = Feature{V2: "max_certificates", V1: "maxCertificates"}
+ MaxIdentityLimit = Feature{V2: "max_identity_limit", V1: "identityLimit"}
+ MaxInternalCAs = Feature{V2: "max_internal_cas", V1: "maxInternalCas"}
+ MaxPAMAccounts = Feature{V2: "max_pam_accounts", V1: "maxPamAccounts"}
+ MaxSansPerCertificate = Feature{V2: "max_sans_per_certificate", V1: "maxSansPerCertificate"}
+ MaxWildcardCertificates = Feature{V2: "max_wildcard_certificates", V1: "maxWildcardCertificates"}
+ OIDCSSO = Feature{V2: "oidc_sso", V1: "oidcSSO"}
+ PAM = Feature{V2: "pam", V1: "pam"}
+ PAMSlackNotifications = Feature{V2: "pam_slack_notifications", V1: "pamSlackNotifications"}
+ PITRecovery = Feature{V2: "pit_recovery", V1: "pitRecovery"}
+ PKIACME = Feature{V2: "pki_acme", V1: "pkiAcme"}
+ PKIApprovals = Feature{V2: "pki_approvals", V1: "pkiApprovals"}
+ PKICodeSigning = Feature{V2: "pki_code_signing", V1: "pkiCodeSigning"}
+ PKIDiscovery = Feature{V2: "pki_discovery", V1: "pkiDiscovery"}
+ PKIEST = Feature{V2: "pki_est", V1: "pkiEst"}
+ PKIEnterpriseAlerting = Feature{V2: "pki_enterprise_alerting", V1: "pkiEnterpriseAlerting"}
+ PKIEnterpriseCAIntegrations = Feature{V2: "pki_enterprise_ca_integrations", V1: "pkiEnterpriseCaIntegrations"}
+ PKIExternalIntermediateCA = Feature{V2: "pki_external_intermediate_ca", V1: "pkiExternalIntermediateCa"}
+ PKIPQC = Feature{V2: "pki_pqc", V1: "pkiPqc"}
+ PKISCEP = Feature{V2: "pki_scep", V1: "pkiScep"}
+ PKISyncs = Feature{V2: "pki_syncs", V1: "pkiSyncs"}
+ ProjectTemplates = Feature{V2: "project_templates", V1: "projectTemplates"}
+ RBAC = Feature{V2: "rbac", V1: "rbac"}
+ ReadRateLimit = Feature{V2: "read_rate_limit", V1: "rateLimits.readLimit"}
+ SAMLSSO = Feature{V2: "saml_sso", V1: "samlSSO"}
+ SCIM = Feature{V2: "scim", V1: "scim"}
+ SSOEnforcement = Feature{V2: "sso_enforcement", V1: ""}
+ SecretAccessInsights = Feature{V2: "secret_access_insights", V1: "secretAccessInsights"}
+ SecretApproval = Feature{V2: "secret_approval", V1: "secretApproval"}
+ SecretRotation = Feature{V2: "secret_rotation", V1: "secretRotation"}
+ SecretScanning = Feature{V2: "secret_scanning", V1: "secretScanning"}
+ SecretShareExternalBranding = Feature{V2: "secret_share_external_branding", V1: "secretShareExternalBranding"}
+ SecretSyncLimit = Feature{V2: "secret_sync_limit", V1: "secretSyncLimit"}
+ SecretVersioning = Feature{V2: "secret_versioning", V1: "secretVersioning"}
+ SecretsBrokering = Feature{V2: "secrets_brokering", V1: "secretsBrokering"}
+ SecretsFolderRBAC = Feature{V2: "secrets_folder_rbac", V1: "secretsFolderRbac"}
+ SecretsRateLimit = Feature{V2: "secrets_rate_limit", V1: "rateLimits.secretsLimit"}
+ SecretsTemporaryAccess = Feature{V2: "secrets_temporary_access", V1: "secretsTemporaryAccess"}
+ SubOrganization = Feature{V2: "sub_organization", V1: "subOrganization"}
+ WildcardCerts = Feature{V2: "wildcard_certs", V1: ""}
+ WriteRateLimit = Feature{V2: "write_rate_limit", V1: "rateLimits.writeLimit"}
+)
+
+// All is every mapped feature. Enterprise turns all of them on, which it has to do
+// explicitly: projectV2ToFeatureSet layers entitlements over the OSS defaults, so a
+// feature the stub omits stays off.
+var All = []Feature{
+ ActiveCerts,
+ AuditLogStreamLimit,
+ AuditLogStreams,
+ AuditLogs,
+ AuditRetentionDays,
+ CACRL,
+ CertManager,
+ CrossProjectSecretSharing,
+ CustomAlerts,
+ CustomRateLimits,
+ DynamicSecret,
+ EnforceGoogleSSO,
+ EnforceMFA,
+ EnterpriseAppConnections,
+ EnterprisePAMAccount,
+ EnterpriseSecretSyncs,
+ EnvironmentLimit,
+ EventSubscriptions,
+ ExternalKMS,
+ FIPS,
+ Gateway,
+ GatewayPool,
+ GithubOrgSync,
+ Groups,
+ HSM,
+ HoneyTokenLimit,
+ HoneyTokens,
+ IPAllowlisting,
+ Identities,
+ InstanceUserManagement,
+ InternalCAs,
+ KMIP,
+ KMSPQC,
+ LDAP,
+ MachineIdentityAuthTemplates,
+ MaxCAs,
+ MaxCertificates,
+ MaxIdentityLimit,
+ MaxInternalCAs,
+ MaxPAMAccounts,
+ MaxSansPerCertificate,
+ MaxWildcardCertificates,
+ OIDCSSO,
+ PAM,
+ PAMSlackNotifications,
+ PITRecovery,
+ PKIACME,
+ PKIApprovals,
+ PKICodeSigning,
+ PKIDiscovery,
+ PKIEST,
+ PKIEnterpriseAlerting,
+ PKIEnterpriseCAIntegrations,
+ PKIExternalIntermediateCA,
+ PKIPQC,
+ PKISCEP,
+ PKISyncs,
+ ProjectTemplates,
+ RBAC,
+ ReadRateLimit,
+ SAMLSSO,
+ SCIM,
+ SSOEnforcement,
+ SecretAccessInsights,
+ SecretApproval,
+ SecretRotation,
+ SecretScanning,
+ SecretShareExternalBranding,
+ SecretSyncLimit,
+ SecretVersioning,
+ SecretsBrokering,
+ SecretsFolderRBAC,
+ SecretsRateLimit,
+ SecretsTemporaryAccess,
+ SubOrganization,
+ WildcardCerts,
+ WriteRateLimit,
+}
diff --git a/tests/harness/license/key.go b/tests/harness/license/key.go
new file mode 100644
index 0000000000..04e4c3ca6b
--- /dev/null
+++ b/tests/harness/license/key.go
@@ -0,0 +1,33 @@
+package license
+
+import (
+ "crypto/rand"
+ "crypto/rsa"
+ "crypto/x509"
+ "encoding/pem"
+ "fmt"
+ "sync"
+)
+
+// serviceKey is the RSA private key the license client signs its service JWT with.
+//
+// Generated at first use rather than committed. A real private key in this repo
+// would be flagged by Infisical's own secret scanning and by GitHub's, for a value
+// that grants nothing.
+//
+// It deliberately does NOT need to be stable across processes, unlike AUTH_SECRET.
+// WireMock never verifies the signature, so a second test binary adopting a running
+// instance can hold a different key and every call still succeeds. The only real
+// constraint is that the client can parse it: it fails before sending anything if it
+// cannot.
+var serviceKey = sync.OnceValue(func() string {
+ key, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ panic(fmt.Sprintf("license: generating service key: %v", err))
+ }
+ der, err := x509.MarshalPKCS8PrivateKey(key)
+ if err != nil {
+ panic(fmt.Sprintf("license: encoding service key: %v", err))
+ }
+ return string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der}))
+})
diff --git a/tests/harness/license/license.go b/tests/harness/license/license.go
new file mode 100644
index 0000000000..f57f1cf485
--- /dev/null
+++ b/tests/harness/license/license.go
@@ -0,0 +1,19 @@
+// Package license controls a tenant's entitlements.
+//
+// Entitlements are a property of the tenant, not the instance, which is what lets a
+// downgrade be asserted under a live org without a dedicated stack. That requires
+// Cloud instance type: getPlan short-circuits to the instance-wide feature set for
+// every other type.
+package license
+
+// Feature carries both names for one entitlement, because two vocabularies are in
+// play and getting them confused fails silently.
+//
+// V2 is the License Server registry key the stub emits. V1 is the TFeatureSet field
+// the read-back checks. feature-mapping.ts warns that a wrong key means the feature
+// is never projected onto the plan, so a raw string would surface as a 403 in a test
+// that looks unrelated to licensing.
+type Feature struct {
+ V2 string
+ V1 string
+}
diff --git a/tests/harness/license/license_test.go b/tests/harness/license/license_test.go
new file mode 100644
index 0000000000..b87d82e276
--- /dev/null
+++ b/tests/harness/license/license_test.go
@@ -0,0 +1,70 @@
+package license
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestPlan_Payload(t *testing.T) {
+ t.Parallel()
+
+ t.Run("ok/enterprise turns on every feature the list knows", func(t *testing.T) {
+ t.Parallel()
+ p := Enterprise()
+ for _, f := range All {
+ if _, ok := p.Features[f.V2]; !ok {
+ t.Fatalf("enterprise omits %s; projectV2ToFeatureSet layers over the OSS "+
+ "defaults, so anything omitted stays off", f.V2)
+ }
+ }
+ })
+
+ t.Run("ok/free omits every feature rather than disabling them", func(t *testing.T) {
+ t.Parallel()
+ if len(Free.Features) != 0 {
+ t.Fatalf("free carries %d features; a downgraded customer gets the OSS "+
+ "defaults, not an explicit set of falses", len(Free.Features))
+ }
+ })
+
+ t.Run("ok/a cap is a number, not a boolean", func(t *testing.T) {
+ t.Parallel()
+ p := Enterprise()
+ for _, f := range []Feature{MaxInternalCAs, AuditRetentionDays} {
+ if _, isBool := p.Features[f.V2].(bool); isBool {
+ t.Errorf("%s is entitled as a boolean; it projects onto a numeric "+
+ "TFeatureSet field", f.V2)
+ }
+ }
+ })
+
+ t.Run("ok/Without leaves the original untouched", func(t *testing.T) {
+ t.Parallel()
+ base := Enterprise()
+ _ = base.Without(RBAC)
+ if base.Features[RBAC.V2] != true {
+ t.Fatal("Without mutated the plan it was called on, so one test would " +
+ "change another's entitlements")
+ }
+ })
+
+ t.Run("ok/Expect covers only features with somewhere to check them", func(t *testing.T) {
+ t.Parallel()
+ expect := Enterprise().Expect()
+ if _, ok := expect[""]; ok {
+ t.Fatal("Expect includes a feature with no TFeatureSet field")
+ }
+ if _, ok := expect[RBAC.V1]; !ok {
+ t.Fatalf("Expect omits %s, which does map to a plan field", RBAC.V1)
+ }
+ })
+}
+
+func TestServiceKey_IsParseablePEM(t *testing.T) {
+ t.Parallel()
+ key := serviceKey()
+ if !strings.HasPrefix(key, "-----BEGIN PRIVATE KEY-----") {
+ t.Fatalf("service key is not PKCS#8 PEM; the license client parses it before "+
+ "signing and fails before sending anything.\ngot: %.40s", key)
+ }
+}
diff --git a/tests/harness/license/plan.go b/tests/harness/license/plan.go
new file mode 100644
index 0000000000..71ea1d1904
--- /dev/null
+++ b/tests/harness/license/plan.go
@@ -0,0 +1,129 @@
+package license
+
+import "maps"
+
+// Plan is what the stubbed License Server returns for one organization.
+type Plan struct {
+ Slug string
+ Features map[string]any // keyed by License Server v2 key
+ Products []Product
+}
+
+// Product is an entitlement row. An entitlement can exist without a Stripe
+// subscription mirror, so a product's state is read from here rather than inferred
+// from the feature map.
+type Product struct {
+ Key string `json:"product_key"`
+ Plan string `json:"plan_key,omitempty"`
+ Status string `json:"status,omitempty"`
+}
+
+// Free is the absence of entitlements. An empty feature map leaves every flag at the
+// OSS default, which is what a downgraded customer actually gets.
+var Free = Plan{Slug: "", Features: map[string]any{}}
+
+// Enterprise turns on everything in the generated mapping.
+//
+// It has to enumerate rather than send a wildcard: projectV2ToFeatureSet layers
+// entitlements over getDefaultOnPremFeatures(), so a feature the stub omits stays
+// off. Limit features get a large number rather than true, since their value is a cap.
+func Enterprise() Plan {
+ features := make(map[string]any, len(All))
+ for _, f := range All {
+ features[f.V2] = valueFor(f)
+ }
+ return Plan{
+ Slug: "enterprise",
+ Features: features,
+ Products: []Product{
+ {Key: "secret-manager", Plan: "enterprise", Status: "active"},
+ {Key: "cert-manager", Plan: "enterprise", Status: "active"},
+ {Key: "pam", Plan: "enterprise", Status: "active"},
+ },
+ }
+}
+
+// valueFor picks a sensible entitlement value from the feature's name.
+//
+// The License Server distinguishes capabilities from metered limits, and the mapping
+// does not record which is which. A cap sent as `true` would project onto a numeric
+// TFeatureSet field as a boolean, so limits are inferred by name and given a value
+// high enough that no test hits them accidentally.
+func valueFor(f Feature) any {
+ switch {
+ case hasPrefix(f.V2, "max_"), hasSuffix(f.V2, "_limit"), hasSuffix(f.V2, "_days"):
+ return 1_000_000
+ case hasSuffix(f.V2, "_cas"), hasSuffix(f.V2, "_certs"), hasSuffix(f.V2, "_identities"):
+ return 1_000_000
+ case f.V2 == "identities":
+ return 1_000_000
+ default:
+ return true
+ }
+}
+
+// Without turns features off, for asserting that a gate actually gates.
+func (p Plan) Without(features ...Feature) Plan {
+ out := p.clone()
+ for _, f := range features {
+ out.Features[f.V2] = false
+ }
+ return out
+}
+
+// With overrides one feature, for limits: Enterprise().With(license.MaxInternalCAs, 2).
+func (p Plan) With(f Feature, value any) Plan {
+ out := p.clone()
+ out.Features[f.V2] = value
+ return out
+}
+
+func (p Plan) clone() Plan {
+ out := Plan{Slug: p.Slug, Features: make(map[string]any, len(p.Features))}
+ maps.Copy(out.Features, p.Features)
+ out.Products = append([]Product(nil), p.Products...)
+ return out
+}
+
+// entitlementsPayload is the response body shape. `features` and `products` are
+// load-bearing; the schema is passthrough, so extra fields are tolerated.
+type entitlementsPayload struct {
+ Slug string `json:"slug,omitempty"`
+ Features map[string]featureValue `json:"features"`
+ Products []Product `json:"products"`
+}
+
+type featureValue struct {
+ Value any `json:"value"`
+}
+
+// Payload renders the plan as the License Server would.
+func (p Plan) Payload() any {
+ features := make(map[string]featureValue, len(p.Features))
+ for k, v := range p.Features {
+ features[k] = featureValue{Value: v}
+ }
+ products := p.Products
+ if products == nil {
+ products = []Product{}
+ }
+ return entitlementsPayload{Slug: p.Slug, Features: features, Products: products}
+}
+
+// Expect is the set a plan read-back can verify: the features that map to a
+// TFeatureSet field. The rest are real entitlements with nowhere to check them.
+func (p Plan) Expect() map[string]any {
+ out := map[string]any{}
+ for _, f := range All {
+ if f.V1 == "" {
+ continue
+ }
+ if v, ok := p.Features[f.V2]; ok {
+ out[f.V1] = v
+ }
+ }
+ return out
+}
+
+func hasPrefix(s, p string) bool { return len(s) >= len(p) && s[:len(p)] == p }
+func hasSuffix(s, p string) bool { return len(s) >= len(p) && s[len(s)-len(p):] == p }
diff --git a/tests/harness/license/server.go b/tests/harness/license/server.go
new file mode 100644
index 0000000000..a21f7306e2
--- /dev/null
+++ b/tests/harness/license/server.go
@@ -0,0 +1,96 @@
+package license
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/Infisical/infisical/tests/infra"
+ "github.com/Infisical/infisical/tests/infra/wiremock"
+)
+
+// Stub priorities. WireMock treats a lower number as higher precedence.
+const (
+ priorityOrg = 1 // one organization
+ priorityFallback = 10 // any organization
+)
+
+// Server stubs the License Server on the shared WireMock.
+type Server struct {
+ wm *wiremock.Client
+}
+
+func New(wm *wiremock.Handle) *Server {
+ return &Server{wm: wm.NewAdminClient()}
+}
+
+// Env is what the application container needs to talk to the stub instead of the
+// real License Server.
+func Env(wm *wiremock.Handle) map[string]string {
+ return map[string]string{
+ // Setting this at all is what makes isCloud true, and Cloud is the only
+ // instance type whose getPlan resolves per organization. Every other type
+ // short-circuits to one instance-wide feature set, which would make
+ // per-tenant entitlements impossible.
+ "LICENSE_SERVER_V2_SERVICE_KEY": serviceKey(),
+ "LICENSE_SERVER_URL": wm.ProxyURL(infra.Internal),
+ }
+}
+
+// InstallFallback answers for any organization.
+//
+// Registered before the application container starts, and not optional. On any
+// failure getPlan writes the OSS defaults into the plan cache for the full TTL
+// rather than leaving it empty, so a single unanswered call poisons that org for
+// about fifteen minutes.
+func (s *Server) InstallFallback(ctx context.Context, p Plan) error {
+ if _, err := s.wm.Register(ctx, wiremock.Stub{
+ Method: "GET",
+ URLRe: `/v1/organizations/[^/]+/entitlements`,
+ Status: 200,
+ JSONBody: p.Payload(),
+ Priority: priorityFallback,
+ Metadata: map[string]string{"harness": "license-fallback"},
+ }); err != nil {
+ return fmt.Errorf("license: installing fallback entitlements: %w", err)
+ }
+
+ // The usage reporter authenticates against the same server. Nothing asserts on
+ // it, but an unanswered call is noise in the logs and a failed request path.
+ for _, path := range []string{"/v1/products", "/v1/subscription"} {
+ if _, err := s.wm.Register(ctx, wiremock.Stub{
+ Method: "GET",
+ URLPath: path,
+ Status: 200,
+ JSONBody: map[string]any{},
+ Priority: priorityFallback,
+ Metadata: map[string]string{"harness": "license-fallback"},
+ }); err != nil {
+ return fmt.Errorf("license: installing %s: %w", path, err)
+ }
+ }
+ return nil
+}
+
+// SetOrgPlan answers for one organization, overriding the fallback.
+//
+// Stub on the ROOT org id. fetchAndCacheCloudPlan resolves findRootOrgDetails and
+// sends the root organization to the license server, so a sub-org resolves its
+// parent's plan.
+//
+// Registering a stub does not by itself change anything: the plan is cached per org
+// in Redis for 900 seconds. The caller busts that through the API by reading the
+// plan back with refreshCache=true, which is the same call that verifies the stub
+// produced what was asked for.
+func (s *Server) SetOrgPlan(ctx context.Context, rootOrgID string, p Plan) error {
+ if _, err := s.wm.Register(ctx, wiremock.Stub{
+ Method: "GET",
+ URLPath: fmt.Sprintf("/v1/organizations/%s/entitlements", rootOrgID),
+ Status: 200,
+ JSONBody: p.Payload(),
+ Priority: priorityOrg,
+ Metadata: map[string]string{"harness": "license-org", "org": rootOrgID},
+ }); err != nil {
+ return fmt.Errorf("license: stubbing entitlements for org %s: %w", rootOrgID, err)
+ }
+ return nil
+}
diff --git a/tests/infra/container.go b/tests/infra/container.go
index 734e3102a6..5de17fc899 100644
--- a/tests/infra/container.go
+++ b/tests/infra/container.go
@@ -9,9 +9,6 @@ type File struct {
Mode int64 // 0 means 0644
}
-// ReadyFunc decides when a container is usable. Implementations live in ready.go.
-type ReadyFunc func(ctx context.Context, c Container) error
-
// ContainerSpec is what a module asks for. Everything a module needs to say about a
// container, and nothing about how it gets created.
type ContainerSpec struct {
@@ -27,7 +24,8 @@ type ContainerSpec struct {
Aliases []string
Files []File
Labels map[string]string
- Ready ReadyFunc
+ Ready Ready
+ Check func(context.Context, Container) error
}
// Container is a started container, as seen by a module.
@@ -39,12 +37,20 @@ type Container struct {
stop func(context.Context) error
exec func(context.Context, []string) (int, string, error)
logs func(context.Context) (string, error)
+ running func(context.Context) (bool, int, error)
}
func (c Container) Endpoint(m Mode, port int) Endpoint { return c.endpoint(m, port) }
func (c Container) Stop(ctx context.Context) error { return c.stop(ctx) }
func (c Container) Logs(ctx context.Context) (string, error) { return c.logs(ctx) }
+// Running reports whether the container is still up, and its exit code if not.
+//
+// Readiness uses it to fail the moment the application exits during boot rather than
+// waiting out the full timeout. On a 540-migration boot that is the difference
+// between a clear error and a five minute stare.
+func (c Container) Running(ctx context.Context) (bool, int, error) { return c.running(ctx) }
+
// Exec runs a command inside the container and returns its exit code and combined
// output. Used by readiness checks such as pg_isready.
func (c Container) Exec(ctx context.Context, cmd []string) (int, string, error) {
diff --git a/tests/infra/mailpit/mailpit.go b/tests/infra/mailpit/mailpit.go
index fb9be0ebcd..85f2929c38 100644
--- a/tests/infra/mailpit/mailpit.go
+++ b/tests/infra/mailpit/mailpit.go
@@ -41,7 +41,7 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)
c, err := d.Run(ctx, infra.ContainerSpec{
Image: m.image,
Ports: []int{smtpPort, apiPort},
- Ready: infra.HTTPReady(apiPort, "/api/v1/info"),
+ Ready: infra.ForHTTP("/api/v1/info").WithPort("8025/tcp"),
})
if err != nil {
return nil, err
diff --git a/tests/infra/module.go b/tests/infra/module.go
index d4d04c7464..47572ffd39 100644
--- a/tests/infra/module.go
+++ b/tests/infra/module.go
@@ -47,10 +47,15 @@ type Deps struct {
workspace string
name NameParts
runner Runner
+ log Logger
}
func (d Deps) Network() string { return d.network }
+// ContainerName is the name this module's container will get. A module needs it to
+// build a URL pointing at itself, which Infisical does for SITE_URL.
+func (d Deps) ContainerName() string { return ContainerName(d.name) }
+
// Run starts this module's container. Name, alias and labels are filled in from the
// resolved scope, so a module never computes its own identity and cannot get the
// naming convention subtly wrong.
@@ -68,10 +73,15 @@ func (d Deps) Run(ctx context.Context, spec ContainerSpec) (Container, error) {
}
// NewDeps builds the Deps handed to one module's Start.
-func NewDeps(handles map[Key]Handle, network, workspace string, name NameParts, r Runner) Deps {
- return Deps{handles: handles, network: network, workspace: workspace, name: name, runner: r}
+func NewDeps(handles map[Key]Handle, network, workspace string, name NameParts, r Runner, log Logger) Deps {
+ if log == nil {
+ log = NewLogger()
+ }
+ return Deps{handles: handles, network: network, workspace: workspace, name: name, runner: r, log: log}
}
+func (d Deps) Log() Logger { return d.log }
+
// Get returns a typed handle, or false when the module was not declared.
//
// A generic method rather than a package function, which Go 1.27 allows. Modules
diff --git a/tests/infra/postgres/postgres.go b/tests/infra/postgres/postgres.go
index 0f1885003e..4a58244a8c 100644
--- a/tests/infra/postgres/postgres.go
+++ b/tests/infra/postgres/postgres.go
@@ -73,9 +73,9 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)
"POSTGRES_DB": m.database,
},
Ports: []int{port},
- // `up --wait` treats a container with no healthcheck as ready once it is
- // running, which for Postgres is before it accepts connections.
- Ready: infra.ExecReady("pg_isready", "-U", user, "-d", m.database),
+ // A running Postgres container is not an accepting one, which is why this is
+ // pg_isready rather than a port check.
+ Ready: infra.ForExec([]string{"pg_isready", "-U", user, "-d", m.database}),
})
if err != nil {
return nil, err
diff --git a/tests/infra/postgres/postgres_test.go b/tests/infra/postgres/postgres_test.go
index 0d9c9b5865..06f41c3bf4 100644
--- a/tests/infra/postgres/postgres_test.go
+++ b/tests/infra/postgres/postgres_test.go
@@ -34,7 +34,7 @@ func start(t *testing.T, opts ...postgres.Option) *postgres.Handle {
name.ScopeID = infra.Sanitize(t.Name())
began := time.Now()
- h, err := m.Start(ctx, infra.NewDeps(nil, infra.NetworkName, infra.Workspace(), name, runner))
+ h, err := m.Start(ctx, infra.NewDeps(nil, infra.NetworkName, infra.Workspace(), name, runner, log))
if err != nil {
t.Fatalf("start: %v", err)
}
diff --git a/tests/infra/ready.go b/tests/infra/ready.go
deleted file mode 100644
index e2857addf1..0000000000
--- a/tests/infra/ready.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package infra
-
-import (
- "context"
- "fmt"
- "net"
- "net/http"
- "strings"
- "time"
-)
-
-const (
- readyPoll = 250 * time.Millisecond
- readyTimeout = 90 * time.Second
-)
-
-// ExecReady polls a command inside the container until it exits zero.
-func ExecReady(cmd ...string) ReadyFunc {
- return func(ctx context.Context, c Container) error {
- return poll(ctx, fmt.Sprintf("exec %s", strings.Join(cmd, " ")), func() error {
- code, out, err := c.Exec(ctx, cmd)
- if err != nil {
- return err
- }
- if code != 0 {
- return fmt.Errorf("exit %d: %s", code, strings.TrimSpace(out))
- }
- return nil
- })
- }
-}
-
-// TCPReady polls until the mapped port accepts a connection. The weakest useful
-// check: it proves something is listening, not that it works.
-func TCPReady(port int) ReadyFunc {
- return func(ctx context.Context, c Container) error {
- return poll(ctx, fmt.Sprintf("tcp %d", port), func() error {
- conn, err := net.DialTimeout("tcp", c.Endpoint(External, port).HostPort(), 2*time.Second)
- if err != nil {
- return err
- }
- return conn.Close()
- })
- }
-}
-
-// HTTPReady polls until path returns a 2xx.
-func HTTPReady(port int, path string) ReadyFunc {
- return func(ctx context.Context, c Container) error {
- client := &http.Client{Timeout: 3 * time.Second}
- url := c.Endpoint(External, port).URL("http") + path
- return poll(ctx, "http "+path, func() error {
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
- if err != nil {
- return err
- }
- resp, err := client.Do(req)
- if err != nil {
- return err
- }
- defer func() { _ = resp.Body.Close() }()
- if resp.StatusCode < 200 || resp.StatusCode > 299 {
- return fmt.Errorf("status %d", resp.StatusCode)
- }
- return nil
- })
- }
-}
-
-func poll(ctx context.Context, what string, check func() error) error {
- deadline := time.Now().Add(readyTimeout)
- var last error
- for {
- if err := check(); err == nil {
- return nil
- } else {
- last = err
- }
- if time.Now().After(deadline) {
- return fmt.Errorf("%s did not pass within %s, last error: %w", what, readyTimeout, last)
- }
- select {
- case <-ctx.Done():
- return ctx.Err()
- case <-time.After(readyPoll):
- }
- }
-}
diff --git a/tests/infra/redis/redis.go b/tests/infra/redis/redis.go
index 791f05c00c..0c2a6795d7 100644
--- a/tests/infra/redis/redis.go
+++ b/tests/infra/redis/redis.go
@@ -48,7 +48,7 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)
c, err := d.Run(ctx, infra.ContainerSpec{
Image: m.image,
Ports: []int{port},
- Ready: infra.ExecReady("redis-cli", "ping"),
+ Ready: infra.ForExec([]string{"redis-cli", "ping"}),
})
if err != nil {
return nil, err
diff --git a/tests/infra/root.go b/tests/infra/root.go
new file mode 100644
index 0000000000..9119960e82
--- /dev/null
+++ b/tests/infra/root.go
@@ -0,0 +1,24 @@
+package infra
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+)
+
+func RepoRoot() (string, error) {
+ dir, err := os.Getwd()
+ if err != nil {
+ return "", err
+ }
+ for {
+ if _, err := os.Stat(filepath.Join(dir, "backend", "Dockerfile")); err == nil {
+ return dir, nil
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ return "", fmt.Errorf("infra: no backend/Dockerfile found above the working directory")
+ }
+ dir = parent
+ }
+}
diff --git a/tests/infra/runner.go b/tests/infra/runner.go
index 03b40fcd95..447f22b5d0 100644
--- a/tests/infra/runner.go
+++ b/tests/infra/runner.go
@@ -82,6 +82,9 @@ func (r *dockerRunner) Run(ctx context.Context, spec ContainerSpec) (Container,
}
opts = append(opts, testcontainers.WithExposedPorts(ports...))
}
+ if spec.Ready != nil {
+ opts = append(opts, testcontainers.WithWaitStrategyAndDeadline(DefaultStartupTimeout, spec.Ready))
+ }
if len(spec.Command) > 0 {
opts = append(opts, testcontainers.WithCmd(spec.Command...))
}
@@ -113,6 +116,8 @@ func (r *dockerRunner) Run(ctx context.Context, spec ContainerSpec) (Container,
}
defer release()
+ r.log.Infof("start %s (%s)", spec.Name, spec.Image)
+
dc, err := testcontainers.Run(ctx, spec.Image, opts...)
if err != nil {
return Container{}, fmt.Errorf("infra: starting %s (%s): %w", spec.Name, spec.Image, err)
@@ -149,6 +154,13 @@ func (r *dockerRunner) Run(ctx context.Context, spec ContainerSpec) (Container,
out, _ := io.ReadAll(reader)
return code, string(out), nil
},
+ running: func(ctx context.Context) (bool, int, error) {
+ st, err := dc.State(ctx)
+ if err != nil {
+ return false, 0, err
+ }
+ return st.Running, st.ExitCode, nil
+ },
logs: func(ctx context.Context) (string, error) {
rc, err := dc.Logs(ctx)
if err != nil {
@@ -160,9 +172,9 @@ func (r *dockerRunner) Run(ctx context.Context, spec ContainerSpec) (Container,
},
}
- if spec.Ready != nil {
- if err := spec.Ready(ctx, c); err != nil {
- return c, fmt.Errorf("infra: %s never became ready: %w", spec.Name, err)
+ if spec.Check != nil {
+ if err := spec.Check(ctx, c); err != nil {
+ return c, fmt.Errorf("infra: %s came up but is not usable: %w", spec.Name, err)
}
}
return c, nil
diff --git a/tests/infra/runner_test.go b/tests/infra/runner_test.go
index 3d13a5330b..66ab131ce5 100644
--- a/tests/infra/runner_test.go
+++ b/tests/infra/runner_test.go
@@ -41,7 +41,7 @@ func TestRunner_AdoptOrCreate(t *testing.T) {
Name: name,
Image: "redis:7-alpine",
Ports: []int{6379},
- Ready: infra.ExecReady("redis-cli", "ping"),
+ Ready: infra.ForExec([]string{"redis-cli", "ping"}),
}
first, err := runner.Run(ctx, spec)
@@ -92,7 +92,7 @@ func TestRunner_NameChangeCreatesNewContainer(t *testing.T) {
Name: infra.ContainerName(p),
Image: "redis:7-alpine",
Ports: []int{6379},
- Ready: infra.ExecReady("redis-cli", "ping"),
+ Ready: infra.ForExec([]string{"redis-cli", "ping"}),
})
if err != nil {
t.Fatalf("run %s: %v", fingerprint, err)
diff --git a/tests/infra/stack_test.go b/tests/infra/stack_test.go
index 1f8ad28453..66c7f7544e 100644
--- a/tests/infra/stack_test.go
+++ b/tests/infra/stack_test.go
@@ -40,7 +40,7 @@ func startAll(t *testing.T, mods []infra.Module, scope infra.Scope) map[infra.Ke
name.Scope = infra.Test
name.ScopeID = "m1smoke"
- h, err := m.Start(ctx, infra.NewDeps(handles, infra.NetworkName, infra.Workspace(), name, runner))
+ h, err := m.Start(ctx, infra.NewDeps(handles, infra.NetworkName, infra.Workspace(), name, runner, log))
if err != nil {
t.Fatalf("start %s: %v", m.Key(), err)
}
diff --git a/tests/infra/wait.go b/tests/infra/wait.go
new file mode 100644
index 0000000000..641a7817af
--- /dev/null
+++ b/tests/infra/wait.go
@@ -0,0 +1,39 @@
+package infra
+
+import (
+ "time"
+
+ "github.com/testcontainers/testcontainers-go/wait"
+)
+
+// Ready is a testcontainers wait strategy, applied while the container starts.
+//
+// Aliased rather than reimplemented. An earlier version of this package hand-rolled
+// exec, TCP and HTTP pollers; testcontainers already ships them, handles the
+// container-exited case during startup, and is better tested than anything written
+// here would be. The alias is what keeps modules from importing testcontainers
+// directly, so the container engine stays behind one seam.
+type Ready = wait.Strategy
+
+// Re-exported so a module imports only this package.
+var (
+ ForExec = wait.ForExec
+ ForHTTP = wait.ForHTTP
+ ForListeningPort = wait.ForListeningPort
+ ForHealthCheck = wait.ForHealthCheck
+ ForAll = wait.ForAll
+ ForAny = wait.ForAny
+
+ // ForLog is deliberately NOT re-exported for the application container.
+ //
+ // Waiting on a log line couples the harness to the implementation's logging
+ // format, which is the one thing this suite exists not to depend on: a Go
+ // reimplementation would emit entirely different lines while /api/status stays
+ // identical. Use it for third-party images whose output is a stable contract,
+ // never for Infisical.
+ ForLog = wait.ForLog
+)
+
+// DefaultStartupTimeout bounds a container that never becomes ready. Generous
+// because the application runs 540 migrations on a cold database.
+const DefaultStartupTimeout = 5 * time.Minute
diff --git a/tests/infra/wiremock/client.go b/tests/infra/wiremock/client.go
new file mode 100644
index 0000000000..b6e9ba5d33
--- /dev/null
+++ b/tests/infra/wiremock/client.go
@@ -0,0 +1,155 @@
+package wiremock
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra"
+)
+
+// Client talks to WireMock's admin API.
+//
+// Stubs are registered with a discriminating request matcher so that parallel
+// tenants sharing one WireMock cannot match each other's requests. Metadata is
+// admin-side only: WireMock does not match requests on it, so it serves cleanup and
+// nothing else.
+type Client struct {
+ base string
+ http *http.Client
+}
+
+func NewClient(adminURL string) *Client {
+ return &Client{base: adminURL, http: &http.Client{Timeout: 10 * time.Second}}
+}
+
+// Matcher is a WireMock request-matching predicate, for example
+// {"contains": "a1b2c3d4"} or {"equalTo": "x"}.
+type Matcher map[string]any
+
+func Contains(v string) Matcher { return Matcher{"contains": v} }
+func EqualTo(v string) Matcher { return Matcher{"equalTo": v} }
+func MatchesRe(v string) Matcher {
+ return Matcher{"matches": v}
+}
+
+// Stub is one mapping.
+type Stub struct {
+ Method string
+ URLPath string
+ URLRe string
+ Headers map[string]Matcher
+ Query map[string]Matcher
+ Status int
+ JSONBody any
+ Priority int
+ Metadata map[string]string
+}
+
+type mapping struct {
+ Request map[string]any `json:"request"`
+ Response map[string]any `json:"response"`
+ Priority int `json:"priority,omitempty"`
+ Metadata map[string]string `json:"metadata,omitempty"`
+}
+
+// Register creates a mapping and returns its id.
+func (c *Client) Register(ctx context.Context, s Stub) (string, error) {
+ req := map[string]any{"method": s.Method}
+ switch {
+ case s.URLRe != "":
+ req["urlPathPattern"] = s.URLRe
+ default:
+ req["urlPath"] = s.URLPath
+ }
+ if len(s.Headers) > 0 {
+ req["headers"] = s.Headers
+ }
+ if len(s.Query) > 0 {
+ req["queryParameters"] = s.Query
+ }
+
+ status := s.Status
+ if status == 0 {
+ status = http.StatusOK
+ }
+ resp := map[string]any{"status": status}
+ if s.JSONBody != nil {
+ resp["jsonBody"] = s.JSONBody
+ resp["headers"] = map[string]string{"Content-Type": "application/json"}
+ }
+
+ var out struct {
+ ID string `json:"id"`
+ }
+ if err := c.do(ctx, http.MethodPost, "/mappings", mapping{
+ Request: req, Response: resp, Priority: s.Priority, Metadata: s.Metadata,
+ }, &out); err != nil {
+ return "", err
+ }
+ return out.ID, nil
+}
+
+// RemoveByMetadata deletes every mapping carrying the given metadata.
+//
+// This is what metadata is for. It cannot isolate request matching, only cleanup.
+func (c *Client) RemoveByMetadata(ctx context.Context, key, value string) error {
+ return c.do(ctx, http.MethodPost, "/mappings/remove-by-metadata", map[string]any{
+ "matchesJsonPath": fmt.Sprintf("$.%s", key),
+ "equalToJson": fmt.Sprintf(`{"%s":"%s"}`, key, value),
+ }, nil)
+}
+
+// Requests returns journal entries matching a criteria document.
+//
+// Always filtered. The journal is global and shared by every tenant, and
+// resetRequests must never be called because it would destroy another tenant's
+// evidence mid-run.
+func (c *Client) Requests(ctx context.Context, criteria map[string]any) (int, error) {
+ var out struct {
+ Requests []json.RawMessage `json:"requests"`
+ }
+ if err := c.do(ctx, http.MethodPost, "/requests/find", criteria, &out); err != nil {
+ return 0, err
+ }
+ return len(out.Requests), nil
+}
+
+func (c *Client) do(ctx context.Context, method, path string, in, out any) error {
+ var body io.Reader
+ if in != nil {
+ buf, err := json.Marshal(in)
+ if err != nil {
+ return err
+ }
+ body = bytes.NewReader(buf)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.base+path, body)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return fmt.Errorf("wiremock: %s %s: %w", method, path, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ raw, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode >= 300 {
+ return fmt.Errorf("wiremock: %s %s returned %d: %s", method, path, resp.StatusCode, raw)
+ }
+ if out != nil {
+ return json.Unmarshal(raw, out)
+ }
+ return nil
+}
+
+// NewAdminClient returns a client for this WireMock. Always External: the Go test
+// process talks to the admin API, not a container.
+func (h *Handle) NewAdminClient() *Client { return NewClient(h.AdminURL(infra.External)) }
diff --git a/tests/infra/wiremock/wiremock.go b/tests/infra/wiremock/wiremock.go
index d60ade3d3d..ad953ae47e 100644
--- a/tests/infra/wiremock/wiremock.go
+++ b/tests/infra/wiremock/wiremock.go
@@ -73,7 +73,7 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)
Command: m.flags,
Ports: []int{port},
Aliases: m.aliases,
- Ready: infra.HTTPReady(port, "/__admin/mappings"),
+ Ready: infra.ForHTTP("/__admin/mappings").WithPort("8080/tcp"),
})
if err != nil {
return nil, err