Skip to content

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

feat: added main harness shared setup

=095de5ae523f
diff --git a/tests/Makefile b/tests/Makefile
index c32b54730b..65e054d43c 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -3,7 +3,7 @@
# the toolchain's own.
GOFMT := $(shell go env GOROOT)/bin/gofmt
-.PHONY: fmt lint test test-unit test-docker down status generate-client
+.PHONY: fmt lint test test-unit test-docker test-suites up down status generate-client
fmt:
$(GOFMT) -w .
@@ -24,9 +24,16 @@ test: lint test-unit
test-docker:
INFRA_DOCKER_TESTS=1 go test ./infra/... -count=1
+# Every suite run starts from a clean stack.
+test-suites: down up
+ go test ./suites/... -count=1
+
down:
go run ./cmd/inf down
+up:
+ go run ./cmd/inf up
+
status:
go run ./cmd/inf status
diff --git a/tests/cmd/inf/main.go b/tests/cmd/inf/main.go
index 8e325cb5de..50c9694bc0 100644
--- a/tests/cmd/inf/main.go
+++ b/tests/cmd/inf/main.go
@@ -5,11 +5,13 @@
package main
import (
+ "context"
"fmt"
"os"
"os/exec"
"strings"
+ "github.com/Infisical/infisical/tests/harness"
"github.com/Infisical/infisical/tests/infra"
)
@@ -20,12 +22,15 @@ func main() {
}
switch cmd {
+ case "up":
+ os.Exit(up())
case "status":
os.Exit(status())
case "down":
os.Exit(down())
default:
fmt.Fprintln(os.Stderr, strings.TrimSpace(`
+inf up start the shared stack, so a test run adopts it instead of creating it
inf status list harness containers, with the checkout that created each
inf down stop every harness container and remove the network
`))
@@ -33,6 +38,20 @@ inf down stop every harness container and remove the network
}
}
+// up pre-warms the shared stack.
+//
+// Not required: a test binary creates what it needs if nothing is there. Running it
+// first means the binaries in one `go test ./...` adopt a single instance rather than
+// racing to create it, and it keeps the image build and the 540-migration boot out of
+// the first package's timing.
+func up() int {
+ if err := harness.Up(context.Background()); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return 1
+ }
+ return status()
+}
+
func status() int {
out, err := docker("ps", "-a",
"--filter", "label="+infra.LabelScope,
diff --git a/tests/harness/harness.go b/tests/harness/harness.go
new file mode 100644
index 0000000000..c216af60b3
--- /dev/null
+++ b/tests/harness/harness.go
@@ -0,0 +1,219 @@
+// Package harness runs Infisical for a test suite.
+//
+// A test package declares a profile and nothing else:
+//
+// func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }
+//
+// Everything below that line -- container lifetimes, adopt-or-create, the network,
+// bootstrap, entitlements -- is implementation a test never names.
+package harness
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/harness/infisical"
+ "github.com/Infisical/infisical/tests/harness/license"
+ "github.com/Infisical/infisical/tests/infra"
+ "github.com/Infisical/infisical/tests/infra/wiremock"
+)
+
+// current is the stack Main built, read by From. One per test binary, which is what
+// a package-level variable is for.
+var current *Stack
+
+// Stack is a running Infisical and everything around it.
+type Stack struct {
+ profile Profile
+ modules map[infra.Key]infra.Handle
+ log infra.Logger
+ pkg string
+ mainFile string
+
+ app *infisical.Handle
+ root infisical.Root
+ license *license.Server
+}
+
+// Option adjusts what Main brings up.
+type Option func(*config)
+
+type config struct {
+ extra []infra.Module
+ plan license.Plan
+}
+
+// WithInfra adds a container the harness does not know about, for a suite that needs
+// one: Pebble for ACME, a target database for rotation.
+func WithInfra(mods ...infra.Module) Option {
+ return func(c *config) { c.extra = append(c.extra, mods...) }
+}
+
+// WithDefaultPlan sets the entitlements a tenant gets unless it asks for others.
+func WithDefaultPlan(p license.Plan) Option {
+ return func(c *config) { c.plan = p }
+}
+
+// Main brings the stack up, runs the package's tests, and tears down what it owns.
+//
+// It calls os.Exit, so it never returns.
+func Main(m *testing.M, profile Profile, opts ...Option) {
+ cfg := &config{plan: license.Enterprise()}
+ for _, o := range opts {
+ o(cfg)
+ }
+
+ _, file, _, _ := runtime.Caller(1)
+ code, err := run(m, profile, cfg, file)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "harness: %v\n", err)
+ os.Exit(1)
+ }
+ os.Exit(code)
+}
+
+func run(m *testing.M, profile Profile, cfg *config, mainFile string) (int, error) {
+ ctx := context.Background()
+
+ stack, owned, err := bringUp(ctx, profile, cfg, packageNameFor(mainFile))
+ if err != nil {
+ return 0, err
+ }
+ defer stopAll(ctx, owned)
+
+ stack.mainFile = mainFile
+ current = stack
+ return m.Run(), nil
+}
+
+// Up brings up the shared stack without running anything.
+//
+// `inf up` uses it to pre-warm, so the test binaries in a run adopt one instance
+// instead of racing to create it. Everything it starts is shared, so nothing here
+// owns a container: only `inf down` stops them.
+func Up(ctx context.Context) error {
+ _, owned, err := bringUp(ctx, Shared, &config{plan: license.Enterprise()}, "")
+ if err != nil {
+ return err
+ }
+ if len(owned) > 0 {
+ return fmt.Errorf("harness: Up started %d package-scoped containers, which it cannot own", len(owned))
+ }
+ return nil
+}
+
+// bringUp starts the modules a profile asks for and prepares the instance.
+//
+// Returns the handles this caller owns, which is only ever the package-scoped ones.
+// Shared containers deliberately outlive the run so a second `go test` adopts them.
+func bringUp(ctx context.Context, profile Profile, cfg *config, pkg string) (*Stack, []infra.Handle, error) {
+ log := infra.NewLogger()
+
+ root, err := infra.RepoRoot()
+ if err != nil {
+ return nil, nil, err
+ }
+ img, err := infisical.ResolveImage(ctx, root, log)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ mods, scopes := profile.modules(img, cfg.extra...)
+ plan, err := infra.Resolve(mods, scopes)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ runner := infra.NewRunner(infra.Workspace(), log)
+ if err := runner.Network(ctx, infra.NetworkName); err != nil {
+ return nil, nil, err
+ }
+
+ handles := map[infra.Key]infra.Handle{}
+ var owned []infra.Handle
+
+ for _, mod := range plan.Modules() {
+ scope := plan.Scope(mod.Key())
+ name := mod.Name()
+ name.Scope = scope
+ if scope == infra.Package {
+ name.ScopeID = pkg
+ }
+
+ h, err := mod.Start(ctx, infra.NewDeps(handles, infra.NetworkName, infra.Workspace(), name, runner, log))
+ if err != nil {
+ stopAll(ctx, owned)
+ return nil, nil, err
+ }
+ handles[mod.Key()] = h
+ if scope != infra.Shared {
+ owned = append(owned, h)
+ }
+ }
+
+ app := handles[infisical.Key].(*infisical.Handle)
+ stack := &Stack{profile: profile, modules: handles, log: log, pkg: pkg, app: app}
+
+ if wm, ok := handles[wiremock.Key].(*wiremock.Handle); ok {
+ stack.license = license.New(wm)
+ if err := stack.license.InstallFallback(ctx, cfg.plan); err != nil {
+ stopAll(ctx, owned)
+ return nil, nil, err
+ }
+ }
+
+ if stack.root, err = infisical.Bootstrap(ctx, app.BaseURL(infra.External)); err != nil {
+ stopAll(ctx, owned)
+ return nil, nil, err
+ }
+ return stack, owned, nil
+}
+
+func stopAll(ctx context.Context, handles []infra.Handle) {
+ for i := len(handles) - 1; i >= 0; i-- {
+ _ = handles[i].Stop(context.WithoutCancel(ctx))
+ }
+}
+
+// From returns the stack this package's TestMain built.
+func From(t *testing.T) *Stack {
+ t.Helper()
+ if current == nil {
+ t.Fatal("harness: no stack. Add a TestMain to this package:\n\n" +
+ "\tfunc TestMain(m *testing.M) { harness.Main(m, harness.Shared) }")
+ }
+ return current
+}
+
+// App is the running Infisical.
+func (s *Stack) App() *infisical.Handle { return s.app }
+
+// Require returns a module handle, or fails the test naming the option to add.
+func (s *Stack) Require(t *testing.T, key infra.Key, option string) infra.Handle {
+ t.Helper()
+ h, ok := s.modules[key]
+ if !ok {
+ t.Fatalf("%s: this test needs the %q module.\nAdd %s to harness.Main in %s.",
+ s.pkg, key, option, filepath.Base(s.mainFile))
+ }
+ return h
+}
+
+// packageNameFor derives a container-name fragment from the TestMain file, so an
+// Isolated package's containers cannot be adopted by a different one.
+func packageNameFor(mainFile string) string {
+ root, err := infra.RepoRoot()
+ if err != nil {
+ return infra.Sanitize(filepath.Base(filepath.Dir(mainFile)))
+ }
+ dir := filepath.Dir(mainFile)
+ if rel, err := filepath.Rel(filepath.Join(root, "tests"), dir); err == nil {
+ return infra.Sanitize(rel)
+ }
+ return infra.Sanitize(strings.TrimPrefix(dir, root))
+}
diff --git a/tests/harness/infisical/client.go b/tests/harness/infisical/client.go
index ded17cac58..fd19ed5ffa 100644
--- a/tests/harness/infisical/client.go
+++ b/tests/harness/infisical/client.go
@@ -38,6 +38,28 @@ func NewClient(baseURL string, editors ...api.RequestEditorFn) (*api.ClientWithR
return c, nil
}
+// ForwardedFor gives a caller its own rate-limit bucket.
+//
+// Only three rate limits are entitlements (read, write, secrets); auth, invite, MFA,
+// identity-creation and project-creation are hardcoded and keyed on req.realIp. A
+// suite running in parallel shares one source address and burns through
+// authRateLimit's 60 per minute in seconds.
+//
+// Absent TRUSTED_PROXY_CIDRS, fastifyIp runs in legacy mode where the first matching
+// forwarded header wins verbatim, so a per-tenant address gives each tenant its own
+// bucket and the headroom scales with parallelism instead of being a fixed ceiling.
+//
+// This is the one place the harness leans on a behaviour a reimplementation might not
+// share. If it stops being honoured the limits collapse back to per-process, which is
+// slow and flaky rather than wrong, and the fallback is raising them through the
+// super-admin API.
+func ForwardedFor(ip string) api.RequestEditorFn {
+ return func(_ context.Context, req *http.Request) error {
+ req.Header.Set("X-Forwarded-For", ip)
+ return nil
+ }
+}
+
// BearerAuth attaches a token to every request.
func BearerAuth(token string) api.RequestEditorFn {
return func(_ context.Context, req *http.Request) error {
diff --git a/tests/harness/infisical/infisical.go b/tests/harness/infisical/infisical.go
index 7bea55e7a1..44243f054f 100644
--- a/tests/harness/infisical/infisical.go
+++ b/tests/harness/infisical/infisical.go
@@ -9,6 +9,7 @@ import (
"context"
"fmt"
+ "github.com/Infisical/infisical/tests/harness/license"
"github.com/Infisical/infisical/tests/infra"
"github.com/Infisical/infisical/tests/infra/mailpit"
"github.com/Infisical/infisical/tests/infra/postgres"
@@ -119,6 +120,14 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)
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
+
+ // Point the license client at the same WireMock, which is what makes
+ // entitlements resolve per organization. Without this the instance is not
+ // Cloud, and getPlan short-circuits to one instance-wide feature set for
+ // every tenant.
+ for k, v := range license.Env(wm) {
+ env[k] = v
+ }
}
for k, v := range m.env {
diff --git a/tests/harness/profile.go b/tests/harness/profile.go
new file mode 100644
index 0000000000..00ef001c92
--- /dev/null
+++ b/tests/harness/profile.go
@@ -0,0 +1,71 @@
+package harness
+
+import (
+ "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/infra/wiremock"
+)
+
+// Profile is how a package declares what it needs. It is the only thing a TestMain
+// says, and it determines the isolation a suite gets.
+type Profile int
+
+const (
+ // Shared runs against one instance for the whole `go test ./...`, with a fresh
+ // organization per test. Every test calls t.Parallel(). This is the default and
+ // covers almost everything.
+ Shared Profile = iota
+
+ // Isolated gives the package its own instance, so it can write state that is not
+ // organization-scoped: super-admin config, login methods, the encryption
+ // strategy, run modes. Tests do NOT call t.Parallel(); across packages they still
+ // run concurrently, because each test binary gets its own containers.
+ Isolated
+)
+
+func (p Profile) String() string {
+ if p == Isolated {
+ return "isolated"
+ }
+ return "shared"
+}
+
+// modules expands a profile into the module set and its lifetimes.
+//
+// A profile fixes the set completely, and that is load-bearing rather than tidy. A
+// shared container is adopted by name and takes its environment at creation, so if
+// one package declared WireMock and another did not, whichever started the instance
+// first would silently decide whether it runs in cloud mode for everyone.
+//
+// Mailpit stays shared even under Isolated: it holds no instance state, isolation
+// between tenants is by address, and a second one buys nothing.
+func (p Profile) modules(img infisical.Image, extra ...infra.Module) ([]infra.Module, map[infra.Key]infra.Scope) {
+ own := infra.Shared
+ if p == Isolated {
+ own = infra.Package
+ }
+
+ mods := []infra.Module{
+ postgres.Module(),
+ redis.Module(),
+ mailpit.Module(),
+ wiremock.Module(),
+ infisical.Module(infisical.WithImage(img)),
+ }
+ scopes := map[infra.Key]infra.Scope{
+ postgres.Key: own,
+ redis.Key: own,
+ mailpit.Key: infra.Shared,
+ wiremock.Key: own,
+ infisical.Key: own,
+ }
+
+ for _, m := range extra {
+ mods = append(mods, m)
+ scopes[m.Key()] = own
+ }
+ return mods, scopes
+}
diff --git a/tests/harness/tenant.go b/tests/harness/tenant.go
new file mode 100644
index 0000000000..f98c87db2b
--- /dev/null
+++ b/tests/harness/tenant.go
@@ -0,0 +1,283 @@
+package harness
+
+import (
+ "context"
+ "crypto/rand"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/harness/infisical"
+ "github.com/Infisical/infisical/tests/harness/license"
+ "github.com/Infisical/infisical/tests/infra"
+ "github.com/google/uuid"
+)
+
+// Tenant is one organization and everything under it. It is the unit of isolation:
+// every test gets its own, which is what makes t.Parallel() the default rather than
+// the exception.
+type Tenant struct {
+ OrgID uuid.UUID
+ OrgSlug string
+
+ // Admin is a plain organization administrator, not the instance root. It carries
+ // no super-admin flag, so a test cannot reach instance-wide state through it by
+ // accident: the server answers 403.
+ Admin *Principal
+
+ // ip is this tenant's rate-limit bucket. See infisical.ForwardedFor.
+ ip string
+
+ stack *Stack
+ plan *license.Plan
+}
+
+// Principal is anything that can authenticate: a user, a machine identity, a SCIM
+// token. The shape is the same, so a test asserting what an actor may do reads the
+// same whichever it holds.
+type Principal struct {
+ Email string
+ Token string
+ API *api.ClientWithResponses
+}
+
+// Address returns a mailbox inside this tenant's own domain, so two parallel tests
+// inviting "alice" never collide.
+func (t *Tenant) Address(local string) string {
+ return local + "@" + t.OrgSlug + ".test"
+}
+
+// TenantOption adjusts a new tenant.
+type TenantOption func(*tenantConfig)
+
+type tenantConfig struct {
+ name string
+ plan *license.Plan
+}
+
+// WithName names the organization. Rarely needed: the slug carries a nanoid, so names
+// do not have to be unique.
+func WithName(name string) TenantOption { return func(c *tenantConfig) { c.name = name } }
+
+// WithPlan gives the tenant entitlements other than the default.
+func WithPlan(p license.Plan) TenantOption { return func(c *tenantConfig) { c.plan = &p } }
+
+// NewTenant creates an organization with its own administrator.
+//
+// The instance root has to do the creating: POST /api/v2/organizations refuses any
+// actor that is not a USER, so the bootstrap identity token cannot mint tenants and
+// the root password is the only thing that can. That password stays inside the
+// harness; what a test gets back is an ordinary org admin.
+//
+// One login, not two. Every round trip here comes out of authRateLimit's 60 per
+// minute, which is not an entitlement and cannot be raised through the plan.
+func (s *Stack) NewTenant(t *testing.T, opts ...TenantOption) *Tenant {
+ t.Helper()
+ ctx := t.Context()
+
+ cfg := tenantConfig{name: "t-" + strings.ToLower(uuid.NewString()[:8])}
+ for _, o := range opts {
+ o(&cfg)
+ }
+
+ ip := tenantIP()
+ unscoped := s.rootToken(t, ip)
+
+ created, err := s.client(t, unscoped, ip).CreateOrganizationWithResponse(ctx,
+ api.CreateOrganizationJSONRequestBody{Name: cfg.name})
+ if err != nil {
+ t.Fatalf("harness: creating an organization: %v", err)
+ }
+ if created.JSON200 == nil {
+ t.Fatalf("harness: creating an organization returned %d: %s", created.StatusCode(), body(created.Body))
+ }
+
+ org := created.JSON200.Organization
+ tenant := &Tenant{OrgID: org.Id, OrgSlug: org.Slug, ip: ip, stack: s, plan: cfg.plan}
+ tenant.Admin = s.scopeToOrg(t, unscoped, org.Id, ip)
+
+ if cfg.plan != nil {
+ tenant.SetPlan(t, *cfg.plan)
+ }
+
+ t.Cleanup(tenant.remove)
+ return tenant
+}
+
+// SetPlan changes this tenant's entitlements, and proves the change took effect.
+//
+// A stub on its own does nothing: getPlan caches per organization in Redis for 900
+// seconds. Verify reads the plan back with refreshCache=true, which busts that cache
+// through the API and asserts the stub produced what was asked for in one call.
+func (t *Tenant) SetPlan(tt *testing.T, p license.Plan) {
+ tt.Helper()
+ if t.stack.license == nil {
+ tt.Fatalf("%s: SetPlan needs the license stub, which needs WireMock", t.stack.pkg)
+ }
+ if err := t.stack.license.SetOrgPlan(tt.Context(), t.OrgID.String(), p); err != nil {
+ tt.Fatalf("harness: %v", err)
+ }
+ t.plan = &p
+ t.Verify(tt, p)
+}
+
+// Verify reads the resolved plan back and fails if it is not what was asked for.
+//
+// The stub speaks License Server keys while the plan speaks TFeatureSet fields, and
+// feature-mapping.ts warns that a wrong key means the feature is never projected.
+// That failure is silent: it surfaces later as a 403 in a test that looks unrelated
+// to licensing. This turns it into a failure at tenant creation, naming the field.
+func (t *Tenant) Verify(tt *testing.T, want license.Plan) {
+ tt.Helper()
+
+ res, err := t.Admin.API.GetOrganizationPlanWithResponse(tt.Context(), t.OrgID.String(),
+ &api.GetOrganizationPlanParams{RefreshCache: refreshCache()})
+ if err != nil {
+ tt.Fatalf("harness: reading the plan back: %v", err)
+ }
+ if res.JSON200 == nil {
+ tt.Fatalf("harness: reading the plan back returned %d: %s", res.StatusCode(), body(res.Body))
+ }
+
+ got, ok := res.JSON200.Plan.(map[string]any)
+ if !ok {
+ tt.Fatalf("harness: plan came back as %T, not an object", res.JSON200.Plan)
+ }
+ for field, expected := range want.Expect() {
+ if !planMatches(lookup(got, field), expected) {
+ tt.Fatalf("tenant %s: asked for %s=%v, the instance resolved %v.\n"+
+ "Likely a wrong License Server feature key; see "+
+ "backend/src/services/license-client/feature-mapping.ts",
+ t.OrgSlug, field, expected, lookup(got, field))
+ }
+ }
+}
+
+// lookup resolves a TFeatureSet field, which may be nested.
+//
+// feature-mapping.ts records the target as a dotted path for nested fields, and the
+// rate limits are what use it: "rateLimits.readLimit" is an object member, not a key
+// containing a dot.
+func lookup(plan map[string]any, field string) any {
+ var current any = plan
+ for _, part := range strings.Split(field, ".") {
+ obj, ok := current.(map[string]any)
+ if !ok {
+ return nil
+ }
+ current = obj[part]
+ }
+ return current
+}
+
+// planMatches compares loosely on purpose: JSON numbers arrive as float64, so a cap
+// entitled as 1000000 comes back as 1e+06.
+func planMatches(got, want any) bool {
+ if g, ok := got.(float64); ok {
+ if w, ok := toFloat(want); ok {
+ return g == w
+ }
+ }
+ return got == want
+}
+
+func toFloat(v any) (float64, bool) {
+ switch n := v.(type) {
+ case int:
+ return float64(n), true
+ case float64:
+ return n, true
+ }
+ return 0, false
+}
+
+// rootToken logs in as the instance root and returns an unscoped token.
+//
+// Unexported: the root is shared by every tenant, so a test holding it could change a
+// password or revoke a session and break every parallel test on the instance.
+func (s *Stack) rootToken(t *testing.T, ip string) string {
+ t.Helper()
+ anon, err := infisical.NewClient(s.app.BaseURL(infra.External), infisical.ForwardedFor(ip))
+ if err != nil {
+ t.Fatalf("harness: %v", err)
+ }
+ res, err := anon.LoginV3WithResponse(t.Context(), api.LoginV3JSONRequestBody{
+ Email: s.root.Email,
+ Password: s.root.Password,
+ })
+ if err != nil {
+ t.Fatalf("harness: logging in as the instance root: %v", err)
+ }
+ if res.JSON200 == nil {
+ t.Fatalf("harness: logging in as the instance root returned %d: %s", res.StatusCode(), body(res.Body))
+ }
+ return res.JSON200.AccessToken
+}
+
+// scopeToOrg binds an unscoped session to one organization.
+//
+// A login token carries no organization; selectOrganization is what binds it, and
+// every org-scoped route needs that binding.
+func (s *Stack) scopeToOrg(t *testing.T, unscoped string, orgID uuid.UUID, ip string) *Principal {
+ t.Helper()
+
+ res, err := s.client(t, unscoped, ip).SelectOrganizationV3WithResponse(t.Context(),
+ api.SelectOrganizationV3JSONRequestBody{OrganizationId: orgID.String()})
+ if err != nil {
+ t.Fatalf("harness: selecting the organization: %v", err)
+ }
+ if res.JSON200 == nil {
+ t.Fatalf("harness: selecting the organization returned %d: %s", res.StatusCode(), body(res.Body))
+ }
+
+ return &Principal{
+ Email: s.root.Email,
+ Token: res.JSON200.Token,
+ API: s.client(t, res.JSON200.Token, ip),
+ }
+}
+
+// client builds an API client carrying a token and a rate-limit bucket.
+func (s *Stack) client(t *testing.T, token, ip string) *api.ClientWithResponses {
+ t.Helper()
+ c, err := infisical.NewClient(s.app.BaseURL(infra.External),
+ infisical.BearerAuth(token), infisical.ForwardedFor(ip))
+ if err != nil {
+ t.Fatalf("harness: %v", err)
+ }
+ return c
+}
+
+// tenantIP is a per-tenant source address, so one tenant's logins cannot exhaust
+// another's rate-limit budget.
+func tenantIP() string {
+ b := make([]byte, 3)
+ _, _ = rand.Read(b)
+ return fmt.Sprintf("10.%d.%d.%d", b[0], b[1], b[2])
+}
+
+// remove deletes the organization. Best effort and never fails a test: the org is
+// disposable, and a leaked one cannot affect another test because nothing outside it
+// can see it.
+func (t *Tenant) remove() {
+ ctx := context.WithoutCancel(context.Background())
+ res, err := t.Admin.API.DeleteOrganizationWithResponse(ctx, t.OrgID.String())
+ if err != nil || res.StatusCode() != http.StatusOK {
+ t.stack.log.Infof("tenant %s could not be deleted, leaving it", t.OrgSlug)
+ }
+}
+
+func refreshCache() *api.GetOrganizationPlanParamsRefreshCache {
+ v := api.GetOrganizationPlanParamsRefreshCache("true")
+ return &v
+}
+
+func body(b []byte) string {
+ const max = 400
+ if len(b) > max {
+ return string(b[:max]) + "..."
+ }
+ return string(b)
+}
diff --git a/tests/infra/runner.go b/tests/infra/runner.go
index 01f598aa81..241230de24 100644
--- a/tests/infra/runner.go
+++ b/tests/infra/runner.go
@@ -32,8 +32,27 @@ type dockerRunner struct {
seen map[string]bool // names this process has already started
}
+// disableRyuk turns off testcontainers' reaper.
+//
+// Ryuk reaps everything created in a session when that session ends, and a session is
+// one test binary. Two things break under it. Shared containers are meant to outlive
+// the run so a second `go test` adopts them; Ryuk deletes them at the first binary's
+// exit. Worse, a container carries the label of the session that CREATED it, so with
+// `go test ./...` running packages concurrently, the first binary to finish reaps
+// containers the others are still using.
+//
+// Reaping is explicit instead: every container carries an inf.scope label and
+// `inf down` removes them. The cost is that a killed run leaves containers behind,
+// which for shared ones is the intended behaviour anyway.
+func disableRyuk() {
+ if _, set := os.LookupEnv("TESTCONTAINERS_RYUK_DISABLED"); !set {
+ _ = os.Setenv("TESTCONTAINERS_RYUK_DISABLED", "true")
+ }
+}
+
// NewRunner returns the default Docker-backed Runner.
func NewRunner(workspace string, log Logger) Runner {
+ disableRyuk()
return &dockerRunner{workspace: workspace, log: log, runID: time.Now().UTC().Format("20060102-150405")}
}
@@ -126,8 +145,7 @@ func (r *dockerRunner) Run(ctx context.Context, spec ContainerSpec) (Container,
sink := newLogSink(r.runID, spec.Name)
opts = append(opts, testcontainers.WithLogConsumers(sink))
- r.log.Infof("start %s (%s)", spec.Name, spec.Image)
-
+ began := time.Now()
dc, err := testcontainers.Run(ctx, spec.Image, opts...)
if err != nil {
sink.Close()
@@ -191,6 +209,15 @@ func (r *dockerRunner) Run(ctx context.Context, spec ContainerSpec) (Container,
return c, fmt.Errorf("infra: %s came up but is not usable: %w", spec.Name, err)
}
}
+
+ // adopt versus create is the most useful single line the harness prints: an
+ // unexpected create means a name is varying when it should not, and everything
+ // downstream is slower than it should be.
+ action := "create"
+ if c.Adopted {
+ action = "adopt"
+ }
+ r.log.Decision(action, spec.Name, c.Endpoint(External, firstPort(spec)), time.Since(began), "")
return c, nil
}
@@ -247,3 +274,10 @@ func Workspace() string {
}
return strings.TrimSuffix(wd, "/tests")
}
+
+func firstPort(spec ContainerSpec) int {
+ if len(spec.Ports) == 0 {
+ return 0
+ }
+ return spec.Ports[0]
+}
diff --git a/tests/suites/platform/main_test.go b/tests/suites/platform/main_test.go
new file mode 100644
index 0000000000..7b3423bee5
--- /dev/null
+++ b/tests/suites/platform/main_test.go
@@ -0,0 +1,9 @@
+package platform_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/harness"
+)
+
+func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }
diff --git a/tests/suites/platform/organization_test.go b/tests/suites/platform/organization_test.go
new file mode 100644
index 0000000000..0ee254e1af
--- /dev/null
+++ b/tests/suites/platform/organization_test.go
@@ -0,0 +1,128 @@
+package platform_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/harness/license"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/google/uuid"
+)
+
+func TestOrganization_Create(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("ok/a tenant gets its own organization", func(t *testing.T) {
+ t.Parallel()
+ a, b := h.NewTenant(t), h.NewTenant(t)
+
+ if a.OrgID == b.OrgID {
+ t.Fatal("two tenants share an organization, so nothing is isolated")
+ }
+ if a.OrgSlug == b.OrgSlug {
+ t.Errorf("two tenants share a slug (%s), so their mail domains collide", a.OrgSlug)
+ }
+ })
+
+ t.Run("ok/the admin is scoped to its own organization", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `A login token carries no organization; selectOrganization binds it. An
+ unbound token reaches no org-scoped route, so this is what every other test
+ depends on without saying so.`)
+
+ tn := h.NewTenant(t)
+ res, err := tn.Admin.API.GetOrganizationPlanWithResponse(t.Context(), tn.OrgID.String(), nil)
+ if err != nil {
+ t.Fatalf("reading the plan: %v", err)
+ }
+ if res.StatusCode() != http.StatusOK {
+ t.Fatalf("admin cannot read its own organization: %d", res.StatusCode())
+ }
+ })
+
+ t.Run("cross-tenant/another tenant's organization is not readable", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `The claim the whole Shared profile rests on. If one tenant can reach
+ another's organization, running tests in parallel against one instance is unsound
+ and every result is suspect.`)
+
+ mine, theirs := h.NewTenant(t), h.NewTenant(t)
+
+ res, err := mine.Admin.API.GetOrganizationPlanWithResponse(t.Context(), theirs.OrgID.String(), nil)
+ if err != nil {
+ t.Fatalf("reading another organization: %v", err)
+ }
+ if res.StatusCode() == http.StatusOK {
+ t.Fatalf("tenant %s read tenant %s's plan", mine.OrgSlug, theirs.OrgSlug)
+ }
+ })
+
+ t.Run("notfound/an organization that never existed", func(t *testing.T) {
+ t.Parallel()
+ tn := h.NewTenant(t)
+
+ res, err := tn.Admin.API.GetOrganizationPlanWithResponse(t.Context(), uuid.NewString(), nil)
+ if err != nil {
+ t.Fatalf("reading an absent organization: %v", err)
+ }
+ if res.StatusCode() == http.StatusOK {
+ t.Fatal("an organization that does not exist returned a plan")
+ }
+ })
+}
+
+func TestOrganization_Entitlements(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("ok/a tenant is entitled by default", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Entitlements resolve per organization, which needs Cloud instance type:
+ every other type short-circuits to one instance-wide feature set. If this fails,
+ the license stub is not reaching the application at all.`)
+
+ h.NewTenant(t).Verify(t, license.Enterprise())
+ })
+
+ t.Run("ok/a tenant can be given a narrower plan", func(t *testing.T) {
+ t.Parallel()
+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.RBAC)))
+ tn.Verify(t, license.Enterprise().Without(license.RBAC))
+ })
+
+ t.Run("ok/entitlements are per tenant, not per instance", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `This is what lets a downgrade be asserted under a live organization
+ without a dedicated stack. If plans leaked across tenants, every licensing test
+ would need its own instance.`)
+
+ narrowed := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.RBAC)))
+ untouched := h.NewTenant(t)
+
+ untouched.Verify(t, license.Enterprise())
+ narrowed.Verify(t, license.Enterprise().Without(license.RBAC))
+ })
+}
+
+func TestProject_Create(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("ok/creates a project in the tenant's organization", func(t *testing.T) {
+ t.Parallel()
+ tn := h.NewTenant(t)
+
+ res, err := tn.Admin.API.CreateProjectWithResponse(t.Context(), api.CreateProjectJSONRequestBody{
+ ProjectName: "app",
+ })
+ if err != nil {
+ t.Fatalf("creating a project: %v", err)
+ }
+ if res.JSON200 == nil {
+ t.Fatalf("creating a project returned %d: %s", res.StatusCode(), res.Body)
+ }
+ })
+}