Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: switched from wiremock to fakenet
=4c8ce1b9049a
diff --git a/tests/.gitignore b/tests/.gitignoreindex 934cd0b320..29e08f693c 100644--- a/tests/.gitignore+++ b/tests/.gitignore@@ -1,2 +1,6 @@# Container logs, written unconditionally so you can tail one while a test hangs..logs/++# The fakenet CA, generated on first run. Removed by `inf down`, so it can never+# outlive the Infisical container that was told to trust it.+.cache/diff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdindex a2a4b766db..d9f135dccc 100644--- a/tests/CLAUDE.md+++ b/tests/CLAUDE.md@@ -38,7 +38,7 @@ Each of the first three brings the stack up, runs its packages, and tears the stdown on the way out, including after a failure or a Ctrl-C. The exit status is thetest run's, so a red run stays red.-They are separate targets so a red line says *which thing* broke: `test-suites`+They are separate targets so a red line says _which thing_ broke: `test-suites`failing means Infisical is broken, `test-harness` failing means the harness is. Onetarget reporting both would erase that distinction, which is the whole reason the twodirectories exist.@@ -65,7 +65,7 @@ infra layer's own container tests, `make fmt` formats.inf-shared-postgres postgres:14-alpine, max_locks_per_transaction=512inf-shared-redis redis:7-alpineinf-shared-mailpit fake SMTP with a search API-inf-shared-wiremock fake internet, in forward-proxy mode+inf-shared-fakenet the fake internet: DNS, our fakes over TLS, a control APIinf-shared-infisical-<image id> built from backend/Dockerfile```@@ -75,11 +75,15 @@ Boot costs about 25 seconds, almost all of it 540 migrations.name, adopts it if it exists and creates it if it does not. That is why `go test`with nothing running works, and why a second run is fast. It also means **changing ashared container's configuration silently adopts a stale one**: if you change an-image tag, a command flag or a network alias, run `make down` first or the change-will not take effect.+image tag or a command flag, run `make down` first or the change will not take+effect.++fakenet is the exception, and deliberately so: its name carries its image ID, so+editing a fake produces a fresh container, and the previous generation is removed+first because only one container can hold the fixed address.**Nothing auto-cleans.** Testcontainers' reaper is disabled, because it deletes by-the *creating* session's label and would reap containers another binary had adopted.+the _creating_ session's label and would reap containers another binary had adopted.Cleanup belongs to `make down`. After an interrupted run, `make down` is also the fixfor a stale container.@@ -95,14 +99,15 @@ tests/│ ├── shared/│ └── isolated/├── harness/ Stack, Profile, Tenant, Principal, instance lifecycle-│ ├── infisical/ the application container module-│ └── license/ the entitlement stub+│ └── infisical/ the application container module├── fixture/ per-product resource builders: project, appconnection-├── provider/ what we know about third parties we stub-├── stub/ WireMock scopes that can only match one caller+├── fakes/ one package per faked service: github, license+├── provider/ what creating an app connection needs, per service├── infra/ product-agnostic container layer+│ └── fakenet/ the fake-internet engine and its container module├── internal/ mail, id, apierr, spec├── clients/api/ generated Infisical client — never hand-edit+├── cmd/fakenet/ the fake-internet server└── cmd/inf/ up, down, status```@@ -156,10 +161,10 @@ func TestSecret_Create(t *testing.T) {### Profiles-| profile | what it gives | when |-|---|---|---|-| `harness.Shared` | one instance for the whole run, a fresh organization per test | almost always |-| `harness.Isolated` | the package's own Postgres, Redis, WireMock, Infisical and Docker network | only when the test writes instance-wide state |+| profile | what it gives | when |+| ------------------ | ------------------------------------------------------------- | --------------------------------------------- |+| `harness.Shared` | one instance for the whole run, a fresh organization per test | almost always |+| `harness.Isolated` | the package's own Postgres, Redis and Infisical | only when the test writes instance-wide state |`Isolated` costs a full Infisical boot, roughly 40 to 50 seconds per package. Reachfor it only when the test writes something not scoped to an organization: super-admin@@ -198,16 +203,16 @@ func TestProject_Access(t *testing.T)Subtest: `<outcome>/<what happened, in words>`. The prefix is not decoration; it iswhat makes a run readable and what a lint can check.-| prefix | meaning |-|---|---|-| `ok/` | the happy path |-| `invalid/` | the request was malformed or referenced something that does not exist |-| `forbidden/` | authenticated but not allowed |-| `cross-tenant/` | another tenant's data was not reachable |-| `notfound/` | the target does not exist |-| `conflict/` | the request collided with existing state |-| `unlicensed/` | the plan does not include the feature |-| `idempotent/` | doing it twice is the same as doing it once |+| prefix | meaning |+| --------------- | --------------------------------------------------------------------- |+| `ok/` | the happy path |+| `invalid/` | the request was malformed or referenced something that does not exist |+| `forbidden/` | authenticated but not allowed |+| `cross-tenant/` | another tenant's data was not reachable |+| `notfound/` | the target does not exist |+| `conflict/` | the request collided with existing state |+| `unlicensed/` | the plan does not include the feature |+| `idempotent/` | doing it twice is the same as doing it once |One file per resource or flow, named after it: `create_test.go`, `access_test.go`.Variants of one flow are subtests, not new files.@@ -223,7 +228,7 @@ did exactly that; it now checks the project landed in the caller's organizationthat `dev`, `staging` and `prod` were provisioned, because those are what a callerrelies on.-**A rejection test must also check nothing changed.** A route can refuse *and* have+**A rejection test must also check nothing changed.** A route can refuse _and_ havealready written. The duplicate-secret test re-reads the secret and asserts theoriginal value survived.@@ -282,6 +287,16 @@ conn := appconnection.New(t, tn, provider.GitHub)appconnection.Try(t, tn, provider.GitHub, appconnection.RejectCredentials(401))```+A connection carries the credential its fake is keyed on, so the two travel together:++```go+gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())+gh.Seed(t, github.RepoSecret("acme/app", "UNMANAGED", "keep"))+gh.Repo(t, "acme/app").Secrets // what the destination holds now+gh.Fail(t, "PUT", "/repos/*", 500, 1) // failure injection+gh.Received(t, "GET", "/user") // the call log+```+**Never build your own API client.** Use `tn.Admin.API`, a principal's `.API`, or`tn.Client(t, token)`. A hand-built client loses the tenant's `X-Forwarded-For`address and starts drawing down a rate-limit bucket shared with every other test, so@@ -291,76 +306,108 @@ Organization roles and project roles are separate types on purpose:`harness.OrgRole("admin")` and `project.Role("viewer")`. Passing one where the otherbelongs does not compile. It used to be silently ignored.-## 9. Outbound calls and stubbing+## 9. Outbound calls and fakes-The instance has **no access to the real internet.** WireMock runs as a forward proxy-and a catch-all refuses anything unstubbed with a 501 naming the URL:+The instance has **no access to the real internet.** fakenet answers DNS for every+hostname, so nothing resolves to a real address, and a host nobody faked gets a 501+naming it:```-The harness has no stub for GET https://api.checklyhq.com/v1/accounts-Register one with conn.Stub(t), or add the host to the provider registry.+fakenet has no fake for GET https://api.checklyhq.com/v1/accounts: no fake is+registered for this host```-This is load bearing. Browser proxying forwards unmatched requests to the real host-by default, so without the catch-all a test that forgot a stub would quietly pass-against the live API.+This is load bearing, and it was measured rather than assumed: with plain Docker+network aliases and no DNS of our own, a container on the harness network reaches+`api.checklyhq.com` and gets a real 401 back from Checkly.-### Stubbing+### Fakes, not stubs++A fake is a working implementation of a service, holding real state. You assert on+what the destination ended up holding, not on which requests were sent:```goconn := appconnection.New(t, tn, provider.GitHub)-sc := conn.Stub(t)-sc.On(t, "PUT", "/repos/acme/app/actions/secrets/DB_URL").Return(t, 204, nil)-...-if n := sc.Received(t, "PUT", "/repos/acme/app/actions/secrets/DB_URL"); n != 1 { ... }+gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())++gh.Seed(t, github.RepoSecret("acme/app", "UNMANAGED", "keep"))+// ... trigger a sync, delete a secret, trigger again ...+got := gh.Repo(t, "acme/app").Secrets```-One WireMock serves every tenant, so **isolation is by discriminator, not by server**.-Each connection gets a unique credential, the provider's `Auth` function turns it into-request matchers, and every stub and journal query carries them. Two tenants stubbing-the same method and path cannot see each other, and that is enforced at registration-rather than detected afterwards. No org id is threaded anywhere: the application-already proves who it is by which credential it sends.--### Two interception paths, and why both exist--**Forward proxy.** `HTTP_PROXY` and `HTTPS_PROXY` point at WireMock; the client sends-`CONNECT api.example.com:443`, and WireMock forges a certificate for that host signed-by its own CA, which is injected into the container as `NODE_EXTRA_CA_CERTS`. Works-for anything using plain axios through `createRequestClient`.--**DNS alias**, for clients that resolve the hostname themselves. Infisical's-SSRF-safe client `safeRequest` resolves a hostname up front and **pins the socket to-that IP**. With a proxy configured, axios then uses the proxy's *port* with the real-host's *IP* and hangs for 100 seconds. The fix is `stubbedHosts` in-`harness/profile.go`: Docker DNS resolves the name to WireMock, so the pin lands on-the proxy and the `CONNECT` still tells WireMock which certificate to forge. This also-needs `ALLOW_INTERNAL_IP_CONNECTIONS=true`, because the SSRF guard would otherwise-reject a public hostname resolving to a private address.--If you add a host to `stubbedHosts`, **run `make down`**. The WireMock container name-does not change, so a running one is adopted with the old aliases and the new host-quietly reaches the internet.--A network alias belongs to the network, not the container, so two WireMocks claiming-one name make Docker DNS round-robin between them. That is why an `Isolated` package-gets its own network.+That difference is the point. A secret sync computes what to delete from what the+destination _returns_, so stubbing that list means asserting against a fixture you+invented. The same goes for the key-schema guard, `disableSecretDeletion`, and the+sealed box: the GitHub fake holds the private key, so `Secrets["DB_URL"].Value` is the+plaintext that actually arrived.++One fakenet serves every tenant, so **isolation is by credential, not by server**.+Each connection invents a unique one, the product sends it on every outbound call,+and fakenet keys state on it. No org id is threaded anywhere.++### How interception works++fakenet runs its own DNS server, and Infisical is started with `--dns <fakenet>`.+Docker's embedded resolver still answers container names first, so `postgres` and+`redis` are unaffected; everything else falls through to fakenet, which answers with+its own address. It then serves 443, minting a certificate per name asked for, signed+by a CA the instance was told to trust.++No `HTTP_PROXY`, no `CONNECT`, no host aliases. Three consequences worth knowing:++- **`safeRequest` stops being a problem.** It resolves a hostname up front and pins+ the socket to that IP. With a proxy that meant dialling the real host on the proxy's+ port and hanging for 100 seconds. Now the pin lands on fakenet because fakenet _is_+ the address.+- **Clients that ignore proxy env are covered**, which the AWS, GCP and Azure SDKs all+ do. DNS asks for no cooperation.+- **`ALLOW_INTERNAL_IP_CONNECTIONS=true` is required**, because fakenet answers for+ public hostnames from a private address and the SSRF guard would otherwise refuse.++fakenet holds a fixed address (`10.201.0.53`) on a fixed subnet, because Infisical is+told where to resolve when its container is created and is then adopted by later test+binaries. Its CA lives in `tests/.cache/` for the same reason: editing a fake rebuilds+fakenet, and a CA minted per boot would leave a running Infisical trusting an+authority that no longer exists. `make down` removes both together.++### Writing a fake++One package under `fakes/<service>/`, holding three things:++1. **The state struct**, shaped like the service rather than like our code.+2. **`ServeHTTP`**, routing with Go 1.22 patterns+ (`PUT /repos/{owner}/{repo}/actions/secrets/{name}`).+3. **`Host`, `Scope` and `New`** — the hostname, how to read the credential off a+ request, and an empty state.++Then one line in `cmd/fakenet/main.go`. The generic `fakenet.Scope[S]` gives the test+side `State`, `Seed`, `Fail`, `Calls` and cleanup, so a fake adds only naming.++The state struct is declared once and imported by both halves, so a field rename is a+compile error rather than a silent zero value.++**A fake is a plain `http.Handler`, so develop it in-process with no Docker at all**+(`fakes/github/fake_test.go` does this). The container is only how the suite consumes+it.++**One fake per service, never per feature.** GitHub is used by app connections, secret+sync, rotation and scanning; they all talk to the same GitHub. Splitting them would+mean two things claiming to be GitHub and free to disagree.### Adding a provider-Add an entry to `provider/`. It carries the app slug, the hostname the client-hardcodes, an `Auth` function producing the discriminator, a `Validate` function-listing the stubs a connection create requires, and a `Create` closure calling the-generated client. Look at `provider.GitHub`.+`provider/` carries only what _creating a connection_ needs: the app slug, the+hostname the client hardcodes, and a `Create` closure calling the generated client.+How the service behaves once reached lives in its fake.The hostname must be one the client hardcodes. If the provider lets you configure a-base URL and you point it straight at WireMock, the test proves the stub works and+base URL and you point it straight at fakenet, the test proves the fake works andnothing about interception.## 10. EntitlementsEvery tenant gets a full enterprise plan by default. The instance runs in Cloud mode-against a WireMock-stubbed license server, which is what makes plans resolve **per+against a faked license server, which is what makes plans resolve **perorganization** rather than instance-wide.```go@@ -369,7 +416,7 @@ tn.SetPlan(t, license.Enterprise()) // also verifies it took effect````SetPlan` and `Verify` read the plan back with `refreshCache=true`, which busts the-900-second Redis cache and asserts the stub produced what was asked for. A wrong+900-second Redis cache and asserts the fake produced what was asked for. A wrongfeature key otherwise surfaces much later as a 403 in an unrelated test.Use `unlicensed/` subtests to pin downgrade behaviour. `CODE_QUALITY.md` requires that@@ -381,11 +428,11 @@ to test that.The limiter is registered because the harness runs Cloud mode. Three tiers, and youcan only move one:-| where the limit comes from | examples | raisable |-|---|---|---|-| the organization's plan | `readLimit`, `writeLimit`, `secretsLimit` | yes, via the license stub |-| instance configuration | `authRateLimit`, `inviteUserRateLimit`, `identityCreationLimit` | no |-| a literal in the source | `smtpRateLimit`, 2 per **40s** | no |+| where the limit comes from | examples | raisable |+| -------------------------- | --------------------------------------------------------------- | ------------------------- |+| the organization's plan | `readLimit`, `writeLimit`, `secretsLimit` | yes, via the license fake |+| instance configuration | `authRateLimit`, `inviteUserRateLimit`, `identityCreationLimit` | no |+| a literal in the source | `smtpRateLimit`, 2 per **40s** | no |`PUT /api/v1/rate-limit` looks like the lever for the middle tier and is inert here:the sync that reads its row is gated on an entitlement Cloud mode never resolves.@@ -411,7 +458,7 @@ are user input. Issue a certificate valid for 7 days and set the alert threshold30, and the condition is true immediately.**Async work is polled, never slept.** Syncs, rotations, webhooks and audit logs land-after the response returns. `time.Sleep` is how you get a suite that is slow *and*+after the response returns. `time.Sleep` is how you get a suite that is slow _and_flaky. There is no shared polling helper yet; `internal/mail` has a private loop, andthe second caller should extract one.@@ -446,25 +493,26 @@ oapi-codegen derives a name from the path, which changes when the path does.### Two generator traps**Union request bodies do not marshal.** oapi-codegen declares the request-body type-as a *defined type* over the union struct, and a defined type does not inherit+as a _defined type_ over the union struct, and a defined type does not inheritmethods, so the generated `MarshalJSON` is lost and the union serialises as `{}`.Build the `JSONBody`, `json.Marshal` it yourself, and post through`...WithBodyWithResponse`.-**Union responses need unwrapping.** `createSecretV4` returns a secret *or* an+**Union responses need unwrapping.** `createSecretV4` returns a secret _or_ anapproval request. Call `AsCreateSecretV4200JSONResponseBody0()` and fail loudly if itis the other branch, rather than letting an approval request read as success.## 14. Debugging a failure1. **Container logs**: `.logs/<timestamp>/<container>.log`, written unconditionally.-2. **The WireMock journal**: `curl localhost:<port>/__admin/requests` shows every- outbound call, whether it matched, and what was returned. `/__admin/mappings` shows- registered stubs.+2. **The fakenet log**, which carries one line per outbound call:+ `GET api.github.com/user -> 200 scope=7116dd6caf34...`. It answers "did the call+ happen at all, and under which credential" before anything else.+ `GET /__fake/denied` lists calls that reached no fake.3. **Mailpit UI**: the mapped port on the Mailpit container, for anything email.4. **`make status`** lists harness containers and their state.-5. If a test hangs for ~100 seconds on an outbound call, suspect the `safeRequest`- pin: the host probably needs to be in `stubbedHosts`.+5. If an outbound call is refused, the host has no fake. Register its `Service` in+ `cmd/fakenet/main.go`, or add the missing route to the fake that owns it.## 15. Anti-patterns@@ -474,8 +522,8 @@ Each has bitten a suite like this before.- Asserting on log lines instead of responses, outside boot tests.- Package-level mutable state shared between tests.- Using `tn.Admin` in a test about what a member can do.-- Over-stubbing: stubbing more than the test needs hides a real outbound call the- code should not have made.+- Seeding more than the test needs, which hides an outbound call the code should not+ have made.- A `Shared` test that cannot be `t.Parallel()`. It is in the wrong package.- Asserting only status codes where the message is part of the contract.- Reaching for the database. There is no client, deliberately.@@ -504,8 +552,9 @@ Honest state, so you do not assume coverage that is not there.- Product coverage is thin: organization, project and secret creation only.- No `internal/wait` helper yet, so polling is hand-rolled per call site.- Secret sync and rotation are not covered; neither is PKI, PAM, KMS, scanning or SSO.-- The license fallback and catch-all stubs accumulate on the shared WireMock across- runs, because nothing removes them. Harmless today since they are identical.+ The GitHub fake already serves the sync endpoints, so the suite is the missing half.+- Only two fakes exist: `github` and `license`. AWS Parameter Store is the next one+ worth writing, since it is the only way to reach the SDK retry and batching paths.- Three operation IDs in the generated client have no caller(`listSecretsV4`, `beginEmailSignupV3`, `verifyEmailSignupV3`).- `-p` is not pinned in the Makefile, so local and CI exercise different amounts ofdiff --git a/tests/cmd/fakenet/Dockerfile b/tests/cmd/fakenet/Dockerfilenew file mode 100644index 0000000000..228599cf75--- /dev/null+++ b/tests/cmd/fakenet/Dockerfile@@ -0,0 +1,7 @@+# The binary is cross-compiled on the host and copied in, rather than built in a+# golang stage: the module cache is already warm from running tests, so this is a+# second where an in-Docker build would download the whole module graph.+FROM scratch+COPY fakenet /fakenet+EXPOSE 53/udp 443 8080+ENTRYPOINT ["/fakenet"]diff --git a/tests/cmd/fakenet/main.go b/tests/cmd/fakenet/main.gonew file mode 100644index 0000000000..0ff058d3c8--- /dev/null+++ b/tests/cmd/fakenet/main.go@@ -0,0 +1,48 @@+// Command fakenet serves the harness's fakes.+//+// Three listeners, and each exists for a different reason:+//+// 53 DNS, so every hostname resolves here and nothing reaches the real internet+// 443 the fakes, with a certificate minted per name asked for+// 8080 the control API, on its own port so the application can never reach it+package main++import (+ "log"+ "net/http"+ "os"++ "github.com/Infisical/infisical/tests/fakes/github"+ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/infra/fakenet"+)++func main() {+ selfIP := os.Getenv("FAKENET_IP")+ if selfIP == "" {+ log.Fatal("fakenet: FAKENET_IP is unset, so the DNS server has no address to answer with")+ }++ ca, err := fakenet.LoadOrCreateCA(fakenet.CAPath)+ if err != nil {+ log.Fatalf("fakenet: %v", err)+ }++ srv := fakenet.New(+ github.Service,+ license.Service,+ )++ go func() { log.Fatalf("fakenet: %v", fakenet.ServeDNS(":53", selfIP)) }()++ go func() {+ log.Fatalf("fakenet: admin listener: %v", http.ListenAndServe(":8080", srv.Admin(ca)))+ }()++ ln, err := tlsListen(":443", ca)+ if err != nil {+ log.Fatalf("fakenet: %v", err)+ }+ log.Printf("fakenet: %s serving %v", selfIP, srv.Hosts())+ log.Fatalf("fakenet: https listener: %v", http.Serve(ln, srv))+}diff --git a/tests/cmd/fakenet/tls.go b/tests/cmd/fakenet/tls.gonew file mode 100644index 0000000000..7b6881b99d--- /dev/null+++ b/tests/cmd/fakenet/tls.go@@ -0,0 +1,12 @@+package main++import (+ "crypto/tls"+ "net"++ "github.com/Infisical/infisical/tests/infra/fakenet"+)++func tlsListen(addr string, ca *fakenet.CA) (net.Listener, error) {+ return tls.Listen("tcp", addr, ca.TLSConfig())+}diff --git a/tests/cmd/inf/main.go b/tests/cmd/inf/main.goindex 91cd9ac01c..2188a1fbde 100644--- a/tests/cmd/inf/main.go+++ b/tests/cmd/inf/main.go@@ -9,10 +9,12 @@ import ("fmt""os""os/exec"+ "path/filepath""strings""github.com/Infisical/infisical/tests/harness""github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/infra/fakenet")func main() {@@ -108,6 +110,17 @@ func down() int {if _, err := docker("network", "rm", infra.NetworkName); err == nil {fmt.Println("removed network " + infra.NetworkName)}++ // The CA goes with the containers. Infisical is told to trust it when its+ // container is created, so a CA that outlived the stack would be a certificate+ // the next Infisical never sees, and the failure would be a TLS error with+ // nothing pointing at the cause.+ if root, err := infra.RepoRoot(); err == nil {+ ca := filepath.Join(root, "tests", fakenet.CAFile)+ if err := os.Remove(ca); err == nil {+ fmt.Println("removed the fakenet CA")+ }+ }return 0}diff --git a/tests/fakes/github/fake.go b/tests/fakes/github/fake.gonew file mode 100644index 0000000000..8cfae0d33d--- /dev/null+++ b/tests/fakes/github/fake.go@@ -0,0 +1,272 @@+package github++import (+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "net/http"+ "slices"+ "strconv"+ "strings"+ "time"++ "github.com/Infisical/infisical/tests/infra/fakenet"+ "golang.org/x/crypto/nacl/box"+)++// Service answers for github.com. Use At for a self-hosted instance, which is worth+// registering separately: a sync pointed at the wrong instance then shows up as an+// empty store rather than passing.+var Service = service{host: "api.github.com"}++type service struct{ host string }++func (s service) At(host string) service { return service{host: host} }+func (s service) Host() string { return s.host }++// Scope is the token. Two tenants syncing to the same repository at the same time are+// told apart by what they authenticate with.+func (service) Scope(r *http.Request) (string, bool) {+ return strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")+}++func (service) New() fakenet.Fake {+ a := &Account{Login: "harness", Stores: map[string]*Store{}}+ a.mux = a.routes()+ return a+}++func (a *Account) ServeHTTP(w http.ResponseWriter, r *http.Request) { a.mux.ServeHTTP(w, r) }++func (a *Account) routes() *http.ServeMux {+ mux := http.NewServeMux()++ // Creating a GitHub app connection with the token method calls this to check the+ // credential works, so the fake answers it by existing rather than because a+ // test registered anything.+ mux.HandleFunc("GET /user", a.user)++ // One group per GitHubSyncScope. They differ only in the path they address, which+ // is why storeKey can fold all three into one address.+ a.secretRoutes(mux, "/orgs/{org}/actions/secrets")+ a.secretRoutes(mux, "/repos/{owner}/{repo}/actions/secrets")+ a.secretRoutes(mux, "/repos/{owner}/{repo}/environments/{env}/secrets")++ return mux+}++func (a *Account) secretRoutes(mux *http.ServeMux, path string) {+ mux.HandleFunc("GET "+path, a.list)+ mux.HandleFunc("GET "+path+"/public-key", a.publicKey)+ mux.HandleFunc("PUT "+path+"/{name}", a.put)+ mux.HandleFunc("DELETE "+path+"/{name}", a.remove)+}++func (a *Account) user(w http.ResponseWriter, _ *http.Request) {+ a.mu.Lock()+ defer a.mu.Unlock()+ writeJSON(w, http.StatusOK, map[string]any{"login": a.Login, "id": 1, "type": "User"})+}++func (a *Account) publicKey(w http.ResponseWriter, r *http.Request) {+ a.mu.Lock()+ defer a.mu.Unlock()+ st := a.store(storeKey(r))+ writeJSON(w, http.StatusOK, map[string]any{+ "key_id": st.KeyID,+ "key": base64.StdEncoding.EncodeToString(st.pub[:]),+ })+}++// list answers with a Link header when the result spans pages.+//+// Real pagination, because the client sets per_page=100, reads the Link header, parses+// rel="last" for a page count and then fetches the remaining pages concurrently+// (github-connection-fns.ts:433-500). Returning everything on one page would leave+// that loop untested.+func (a *Account) list(w http.ResponseWriter, r *http.Request) {+ a.mu.Lock()+ defer a.mu.Unlock()+ st := a.store(storeKey(r))++ names := make([]string, 0, len(st.Secrets))+ for n := range st.Secrets {+ names = append(names, n)+ }+ slices.Sort(names)++ perPage := intParam(r, "per_page", 30)+ page := intParam(r, "page", 1)+ last := (len(names) + perPage - 1) / perPage+ if last == 0 {+ last = 1+ }++ start := min((page-1)*perPage, len(names))+ end := min(start+perPage, len(names))+ if page < last {+ w.Header().Set("Link", linkHeader(r, page, last))+ }++ out := make([]map[string]any, 0, end-start)+ for _, n := range names[start:end] {+ out = append(out, map[string]any{+ "name": n,+ "created_at": st.Secrets[n].UpdatedAt.Format(time.RFC3339),+ "updated_at": st.Secrets[n].UpdatedAt.Format(time.RFC3339),+ })+ }+ writeJSON(w, http.StatusOK, map[string]any{"total_count": len(names), "secrets": out})+}++func (a *Account) put(w http.ResponseWriter, r *http.Request) {+ a.mu.Lock()+ defer a.mu.Unlock()+ st, name := a.store(storeKey(r)), r.PathValue("name")++ var body struct {+ EncryptedValue string `json:"encrypted_value"`+ KeyID string `json:"key_id"`+ }+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ writeErr(w, http.StatusBadRequest, "Problems parsing JSON")+ return+ }+ if body.KeyID != st.KeyID {+ writeErr(w, http.StatusUnprocessableEntity,+ fmt.Sprintf("key_id %q is not the public key for this scope", body.KeyID))+ return+ }++ // The check a stub cannot make. A sync that sent plaintext, sealed against the+ // wrong key, or mangled the base64 fails here rather than reading as a 204.+ sealed, err := base64.StdEncoding.DecodeString(body.EncryptedValue)+ if err != nil {+ writeErr(w, http.StatusUnprocessableEntity, "encrypted_value is not valid base64")+ return+ }+ plain, ok := box.OpenAnonymous(nil, sealed, st.pub, st.priv)+ if !ok {+ writeErr(w, http.StatusUnprocessableEntity, "encrypted_value is not a sealed box for this public key")+ return+ }++ _, existed := st.Secrets[name]+ st.Secrets[name] = Secret{Value: string(plain), UpdatedAt: time.Now().UTC()}+ if existed {+ w.WriteHeader(http.StatusNoContent)+ return+ }+ w.WriteHeader(http.StatusCreated)+}++func (a *Account) remove(w http.ResponseWriter, r *http.Request) {+ a.mu.Lock()+ defer a.mu.Unlock()+ st, name := a.store(storeKey(r)), r.PathValue("name")++ if _, ok := st.Secrets[name]; !ok {+ writeErr(w, http.StatusNotFound, "Not Found")+ return+ }+ delete(st.Secrets, name)+ w.WriteHeader(http.StatusNoContent)+}++// Snapshot marshals under the lock, so a concurrent request cannot mutate a map+// mid-encode.+func (a *Account) Snapshot() ([]byte, error) {+ a.mu.Lock()+ defer a.mu.Unlock()+ return json.Marshal(struct {+ Login string `json:"login"`+ Stores map[string]*Store `json:"stores"`+ }{a.Login, a.Stores})+}++// Seed merges a partial account in, so a test names only what it cares about.+func (a *Account) Seed(raw []byte) error {+ var in Account+ if err := json.Unmarshal(raw, &in); err != nil {+ return err+ }++ a.mu.Lock()+ defer a.mu.Unlock()+ if in.Login != "" {+ a.Login = in.Login+ }+ for key, st := range in.Stores {+ dst := a.store(key)+ for name, s := range st.Secrets {+ at := s.UpdatedAt+ if at.IsZero() {+ at = time.Now().UTC()+ }+ dst.Secrets[name] = Secret{Value: s.Value, UpdatedAt: at}+ }+ }+ return nil+}++// store returns a scope's bag of secrets, creating it and its key pair on first+// touch. GitHub has no "create a repository's secret store" call; it is simply there.+func (a *Account) store(key string) *Store {+ if st, ok := a.Stores[key]; ok {+ return st+ }+ pub, priv, err := box.GenerateKey(rand.Reader)+ if err != nil {+ panic(fmt.Sprintf("github fake: generating a key pair: %v", err))+ }+ st := &Store{+ KeyID: "key-" + strings.ReplaceAll(key, "/", "-"),+ Secrets: map[string]Secret{},+ pub: pub,+ priv: priv,+ }+ a.Stores[key] = st+ return st+}++// storeKey folds whichever route matched into one address.+func storeKey(r *http.Request) string {+ if org := r.PathValue("org"); org != "" {+ return "orgs/" + org+ }+ key := "repos/" + r.PathValue("owner") + "/" + r.PathValue("repo")+ if env := r.PathValue("env"); env != "" {+ key += "/envs/" + env+ }+ return key+}++func linkHeader(r *http.Request, page, last int) string {+ u := *r.URL+ build := func(p int, rel string) string {+ q := u.Query()+ q.Set("page", strconv.Itoa(p))+ v := u+ v.RawQuery = q.Encode()+ return fmt.Sprintf(`<https://%s%s>; rel="%s"`, r.Host, v.RequestURI(), rel)+ }+ return build(page+1, "next") + ", " + build(last, "last")+}++func intParam(r *http.Request, name string, def int) int {+ if v, err := strconv.Atoi(r.URL.Query().Get(name)); err == nil && v > 0 {+ return v+ }+ return def+}++func writeJSON(w http.ResponseWriter, status int, body any) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _ = json.NewEncoder(w).Encode(body)+}++func writeErr(w http.ResponseWriter, status int, msg string) {+ writeJSON(w, status, map[string]string{"message": msg})+}diff --git a/tests/fakes/github/fake_test.go b/tests/fakes/github/fake_test.gonew file mode 100644index 0000000000..74529bf7e0--- /dev/null+++ b/tests/fakes/github/fake_test.go@@ -0,0 +1,232 @@+package github_test++import (+ "bytes"+ "crypto/rand"+ "encoding/base64"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/Infisical/infisical/tests/fakes/github"+ "github.com/Infisical/infisical/tests/infra/fakenet"+ "golang.org/x/crypto/nacl/box"+)++// A fake is a plain http.Handler, so it is provable without Docker. That is the+// intended development loop: write the fake here, then let the suite consume it+// through the container.+func newServer(t *testing.T) (*httptest.Server, *fakenet.Server) {+ t.Helper()+ srv := fakenet.New(github.Service)+ ts := httptest.NewServer(srv)+ t.Cleanup(ts.Close)+ return ts, srv+}++func do(t *testing.T, ts *httptest.Server, method, token, path string, body any) (int, []byte) {+ t.Helper()+ var r io.Reader+ if body != nil {+ raw, err := json.Marshal(body)+ if err != nil {+ t.Fatal(err)+ }+ r = bytes.NewReader(raw)+ }+ req, err := http.NewRequestWithContext(t.Context(), method, ts.URL+path, r)+ if err != nil {+ t.Fatal(err)+ }+ req.Host = "api.github.com"+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ res, err := ts.Client().Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = res.Body.Close() }()+ out, _ := io.ReadAll(res.Body)+ return res.StatusCode, out+}++// seal encrypts the way the product does, so the test drives the fake through the+// same wire format GitHub requires.+func seal(t *testing.T, ts *httptest.Server, token, scope, value string) (string, string) {+ t.Helper()+ code, body := do(t, ts, http.MethodGet, token, scope+"/public-key", nil)+ if code != http.StatusOK {+ t.Fatalf("public-key returned %d: %s", code, body)+ }+ var pk struct {+ KeyID string `json:"key_id"`+ Key string `json:"key"`+ }+ if err := json.Unmarshal(body, &pk); err != nil {+ t.Fatal(err)+ }+ raw, err := base64.StdEncoding.DecodeString(pk.Key)+ if err != nil {+ t.Fatal(err)+ }+ var pub [32]byte+ copy(pub[:], raw)+ sealed, err := box.SealAnonymous(nil, []byte(value), &pub, rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ return base64.StdEncoding.EncodeToString(sealed), pk.KeyID+}++func TestGitHubFake_Secrets(t *testing.T) {+ const repo = "/repos/acme/app/actions/secrets"++ t.Run("ok/a sealed value is stored as plaintext the test can read", func(t *testing.T) {+ ts, _ := newServer(t)+ enc, keyID := seal(t, ts, "ghp_a", repo, "postgres://db/app")++ code, body := do(t, ts, http.MethodPut, "ghp_a", repo+"/DB_URL",+ map[string]string{"encrypted_value": enc, "key_id": keyID})+ if code != http.StatusCreated {+ t.Fatalf("PUT returned %d: %s", code, body)+ }++ code, body = do(t, ts, http.MethodGet, "ghp_a", repo, nil)+ if code != http.StatusOK {+ t.Fatalf("list returned %d: %s", code, body)+ }+ if !bytes.Contains(body, []byte("DB_URL")) {+ t.Errorf("list does not mention the secret: %s", body)+ }+ })++ t.Run("invalid/a value that is not a sealed box is refused", func(t *testing.T) {+ ts, _ := newServer(t)+ _, keyID := seal(t, ts, "ghp_a", repo, "ignored")++ // Plaintext, base64'd, which is what a sync that forgot to encrypt would send.+ code, body := do(t, ts, http.MethodPut, "ghp_a", repo+"/DB_URL", map[string]string{+ "encrypted_value": base64.StdEncoding.EncodeToString([]byte("postgres://db/app")),+ "key_id": keyID,+ })+ if code != http.StatusUnprocessableEntity {+ t.Fatalf("PUT of plaintext returned %d, want 422: %s", code, body)+ }+ })++ t.Run("ok/a deleted secret stops being listed", func(t *testing.T) {+ ts, _ := newServer(t)+ enc, keyID := seal(t, ts, "ghp_a", repo, "v")+ do(t, ts, http.MethodPut, "ghp_a", repo+"/GONE", map[string]string{"encrypted_value": enc, "key_id": keyID})++ if code, body := do(t, ts, http.MethodDelete, "ghp_a", repo+"/GONE", nil); code != http.StatusNoContent {+ t.Fatalf("DELETE returned %d: %s", code, body)+ }+ if _, body := do(t, ts, http.MethodGet, "ghp_a", repo, nil); bytes.Contains(body, []byte("GONE")) {+ t.Errorf("a deleted secret is still listed: %s", body)+ }+ })++ t.Run("cross-tenant/two credentials hold separate accounts", func(t *testing.T) {+ ts, _ := newServer(t)+ encA, keyA := seal(t, ts, "ghp_a", repo, "a-value")+ do(t, ts, http.MethodPut, "ghp_a", repo+"/SHARED", map[string]string{"encrypted_value": encA, "key_id": keyA})++ // Same repository path, different credential. This is the whole isolation+ // story: one fakenet serves every parallel tenant.+ if _, body := do(t, ts, http.MethodGet, "ghp_b", repo, nil); bytes.Contains(body, []byte("SHARED")) {+ t.Errorf("credential b can see credential a's secret: %s", body)+ }+ })++ t.Run("ok/listing paginates and advertises the last page", func(t *testing.T) {+ ts, _ := newServer(t)+ enc, keyID := seal(t, ts, "ghp_a", repo, "v")+ for i := range 150 {+ do(t, ts, http.MethodPut, "ghp_a", fmt.Sprintf("%s/S%03d", repo, i),+ map[string]string{"encrypted_value": enc, "key_id": keyID})+ }++ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+repo+"?per_page=100", nil)+ if err != nil {+ t.Fatal(err)+ }+ req.Host = "api.github.com"+ req.Header.Set("Authorization", "Bearer ghp_a")+ res, err := ts.Client().Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = res.Body.Close() }()++ link := res.Header.Get("Link")+ if link == "" {+ t.Fatal("no Link header on a result that spans pages, so the client would never fetch page 2")+ }+ if !bytes.Contains([]byte(link), []byte(`rel="last"`)) {+ t.Fatalf("Link header carries no rel=last, which is what the client parses for a page count: %s", link)+ }++ // Walk the pages the way makePaginatedGitHubRequest does, and check every+ // secret is reachable. A fake that answered page 1 forever would pass a+ // header check and fail this.+ seen := map[string]bool{}+ for page := 1; page <= 2; page++ {+ _, body := do(t, ts, http.MethodGet, "ghp_a",+ fmt.Sprintf("%s?per_page=100&page=%d", repo, page), nil)+ var out struct {+ TotalCount int `json:"total_count"`+ Secrets []struct {+ Name string `json:"name"`+ } `json:"secrets"`+ }+ if err := json.Unmarshal(body, &out); err != nil {+ t.Fatal(err)+ }+ if out.TotalCount != 150 {+ t.Errorf("page %d reports total_count %d, want 150", page, out.TotalCount)+ }+ for _, s := range out.Secrets {+ seen[s.Name] = true+ }+ }+ if len(seen) != 150 {+ t.Errorf("walking two pages found %d secrets, want 150", len(seen))+ }+ })+}++func TestFakenet_Dispatch(t *testing.T) {+ t.Run("invalid/an unfaked host is refused by name", func(t *testing.T) {+ ts, _ := newServer(t)+ req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, ts.URL+"/v1/accounts", nil)+ if err != nil {+ t.Fatal(err)+ }+ req.Host = "api.checklyhq.com"+ res, err := ts.Client().Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer func() { _ = res.Body.Close() }()++ if res.StatusCode != http.StatusNotImplemented {+ t.Fatalf("an unfaked host returned %d, want 501", res.StatusCode)+ }+ body, _ := io.ReadAll(res.Body)+ if !bytes.Contains(body, []byte("api.checklyhq.com")) {+ t.Errorf("the refusal does not name the host, so a forgotten fake is hard to place: %s", body)+ }+ })++ t.Run("invalid/a request with no credential is refused", func(t *testing.T) {+ ts, _ := newServer(t)+ if code, body := do(t, ts, http.MethodGet, "", "/user", nil); code != http.StatusNotImplemented {+ t.Fatalf("returned %d, want 501: %s", code, body)+ }+ })+}diff --git a/tests/fakes/github/handle.go b/tests/fakes/github/handle.gonew file mode 100644index 0000000000..dca7034971--- /dev/null+++ b/tests/fakes/github/handle.go@@ -0,0 +1,54 @@+package github++import (+ "testing"++ "github.com/Infisical/infisical/tests/infra/fakenet"+)++// Handle is a test's view of one GitHub account inside fakenet.+//+// Everything generic comes from the embedded Scope: State, Seed, Fail, Calls,+// Received, and cleanup. Only the naming below is specific to GitHub.+type Handle struct {+ *fakenet.Scope[Account]+}++// Open returns the account a credential addresses.+//+// The caller passes the credential rather than the fixture, so this package stays+// independent of how a connection was created.+func Open(tt *testing.T, adminURL, credential string) *Handle {+ tt.Helper()+ return &Handle{fakenet.Open[Account](tt, adminURL, Service.Host(), credential)}+}++// Repo is a repository's secrets. Nil when the sync has never touched it, which is+// itself the assertion in a test about a sync that should not have run.+func (h *Handle) Repo(tt *testing.T, full string) *Store {+ tt.Helper()+ return h.State(tt).Stores["repos/"+full]+}++// OrgSecrets is an organization's secrets.+func (h *Handle) OrgSecrets(tt *testing.T, org string) *Store {+ tt.Helper()+ return h.State(tt).Stores["orgs/"+org]+}++// Env is a repository environment's secrets.+func (h *Handle) Env(tt *testing.T, full, env string) *Store {+ tt.Helper()+ return h.State(tt).Stores["repos/"+full+"/envs/"+env]+}++// RepoSecret seeds a secret that is already at the destination before Infisical+// touches it. The case a stub cannot express: a prune has to leave it alone.+func RepoSecret(repo, name, value string) any {+ return Account{Stores: map[string]*Store{+ "repos/" + repo: {Secrets: map[string]Secret{name: {Value: value}}},+ }}+}++// Login sets what GET /user reports.+func Login(login string) any { return Account{Login: login} }diff --git a/tests/fakes/github/state.go b/tests/fakes/github/state.gonew file mode 100644index 0000000000..9ec4d2f0a9--- /dev/null+++ b/tests/fakes/github/state.go@@ -0,0 +1,45 @@+// Package github fakes the parts of GitHub's API that Infisical calls.+//+// One fake for the service, not one per feature. App connections, secret sync,+// rotation and scanning all talk to the same GitHub with the same credential, so+// splitting them would mean two things claiming to be GitHub and free to disagree.+package github++import (+ "net/http"+ "sync"+ "time"+)++// Account is one GitHub account, addressed by the token a test invented.+type Account struct {+ Login string `json:"login"`+ Stores map[string]*Store `json:"stores"`++ mu sync.Mutex+ mux *http.ServeMux+}++// Store is a bag of Actions secrets.+//+// GitHubSyncScope has three values and they differ only in the path they address, so+// one type covers all of them:+//+// orgs/acme organization secrets+// repos/acme/app repository secrets+// repos/acme/app/envs/prod repository environment secrets+type Store struct {+ KeyID string `json:"keyId"`+ Secrets map[string]Secret `json:"secrets"`++ // Unexported so the admin API never carries the private half. GitHub issues a+ // public key per scope and takes a sealed box, and holding the other half is+ // what lets a test assert on the plaintext that was actually delivered.+ pub *[32]byte+ priv *[32]byte+}++type Secret struct {+ Value string `json:"value"`+ UpdatedAt time.Time `json:"updatedAt"`+}diff --git a/tests/fakes/license/fake.go b/tests/fakes/license/fake.gonew file mode 100644index 0000000000..86b9793e2f--- /dev/null+++ b/tests/fakes/license/fake.go@@ -0,0 +1,129 @@+package license++import (+ "encoding/json"+ "net/http"+ "sync"++ "github.com/Infisical/infisical/tests/infra/fakenet"+)++// Host is where the License Server lives as far as the instance is concerned.+//+// A name nobody owns. fakenet answers DNS for every hostname, so this needs no+// registration anywhere; it just has to be a name the real product would never+// reach by accident.+const Host = "license.infisical.test"++// Service answers as the License Server.+var Service = service{}++type service struct{}++func (service) Host() string { return Host }++// Scope is the organization in the path.+//+// Entitlements are per organization, which is the whole reason the harness runs in+// Cloud mode, so the organization is the natural unit of state here rather than a+// credential. The instance-wide endpoints carry no organization and share one scope.+func (service) Scope(r *http.Request) (string, bool) {+ if org := orgFromPath(r.URL.Path); org != "" {+ return org, true+ }+ return "instance", true+}++// New returns a fully entitled organization.+//+// Entitled by default, and that is not a convenience. 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 organization for about fifteen+// minutes. With the default in the fake there is nothing to install and no window in+// which an organization can be asked about before the answer exists.+func (service) New() fakenet.Fake { return &Org{plan: Enterprise()} }++// Org is one organization's entitlements.+type Org struct {+ mu sync.Mutex+ plan Plan+ mux *http.ServeMux+}++func (o *Org) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ o.mu.Lock()+ if o.mux == nil {+ o.mux = o.routes()+ }+ mux := o.mux+ o.mu.Unlock()+ mux.ServeHTTP(w, r)+}++func (o *Org) routes() *http.ServeMux {+ mux := http.NewServeMux()++ mux.HandleFunc("GET /v1/organizations/{orgId}/entitlements", func(w http.ResponseWriter, _ *http.Request) {+ o.mu.Lock()+ payload := o.plan.Payload()+ o.mu.Unlock()+ writeJSON(w, payload)+ })++ // Deleting an organization cancels its subscription, and the delete fails if+ // that call does. Every tenant registers its own removal on t.Cleanup, so+ // without this each test leaks its organization into the shared database for+ // the life of the run. The outcome is parsed rather than ignored, so an empty+ // body is not enough.+ mux.HandleFunc("POST /v1/organizations/{orgId}/subscription/cancel", func(w http.ResponseWriter, _ *http.Request) {+ writeJSON(w, map[string]any{"outcome": "subscription_canceled"})+ })++ // The usage reporter authenticates against the same server. Nothing asserts on+ // these, but an unanswered call is a failed request path and noise in the logs.+ for _, p := range []string{"GET /v1/products", "GET /v1/subscription"} {+ mux.HandleFunc(p, func(w http.ResponseWriter, _ *http.Request) {+ writeJSON(w, map[string]any{})+ })+ }+ return mux+}++func (o *Org) Snapshot() ([]byte, error) {+ o.mu.Lock()+ defer o.mu.Unlock()+ return json.Marshal(o.plan)+}++// Seed replaces the plan outright. Entitlements are not additive: a downgrade is the+// case worth testing, and merging would make it unexpressible.+func (o *Org) Seed(raw []byte) error {+ var p Plan+ if err := json.Unmarshal(raw, &p); err != nil {+ return err+ }+ o.mu.Lock()+ defer o.mu.Unlock()+ o.plan = p+ return nil+}++// orgFromPath pulls the id out of /v1/organizations/{id}/...+func orgFromPath(path string) string {+ const prefix = "/v1/organizations/"+ if len(path) <= len(prefix) || path[:len(prefix)] != prefix {+ return ""+ }+ rest := path[len(prefix):]+ for i := range len(rest) {+ if rest[i] == '/' {+ return rest[:i]+ }+ }+ return rest+}++func writeJSON(w http.ResponseWriter, body any) {+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(body)+}diff --git a/tests/harness/license/features.go b/tests/fakes/license/features.gosimilarity index 100%rename from tests/harness/license/features.gorename to tests/fakes/license/features.godiff --git a/tests/fakes/license/handle.go b/tests/fakes/license/handle.gonew file mode 100644index 0000000000..9a03fbb9e5--- /dev/null+++ b/tests/fakes/license/handle.go@@ -0,0 +1,31 @@+package license++import (+ "testing"++ "github.com/Infisical/infisical/tests/infra/fakenet"+)++// Env is what the instance needs to reach the fake instead of the real License+// Server.+//+// Setting the service key 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.+func Env() map[string]string {+ return map[string]string{+ "LICENSE_SERVER_V2_SERVICE_KEY": serviceKey(),+ "LICENSE_SERVER_URL": "https://" + Host,+ }+}++// Open returns a handle on one organization's entitlements.+//+// Stub on the ROOT organization id: fetchAndCacheCloudPlan resolves+// findRootOrgDetails and sends the root organization to the license server, so a+// sub-org resolves its parent's plan.+func Open(tt *testing.T, adminURL, rootOrgID string) *fakenet.Scope[Plan] {+ tt.Helper()+ return fakenet.Open[Plan](tt, adminURL, Host, rootOrgID)+}diff --git a/tests/harness/license/key.go b/tests/fakes/license/key.gosimilarity index 100%rename from tests/harness/license/key.gorename to tests/fakes/license/key.godiff --git a/tests/harness/license/license.go b/tests/fakes/license/license.gosimilarity index 100%rename from tests/harness/license/license.gorename to tests/fakes/license/license.godiff --git a/tests/harness/license/license_test.go b/tests/fakes/license/license_test.gosimilarity index 100%rename from tests/harness/license/license_test.gorename to tests/fakes/license/license_test.godiff --git a/tests/harness/license/plan.go b/tests/fakes/license/plan.gosimilarity index 100%rename from tests/harness/license/plan.gorename to tests/fakes/license/plan.godiff --git a/tests/fixture/appconnection/appconnection.go b/tests/fixture/appconnection/appconnection.goindex bd9bec14d8..7fa9e4b7cd 100644--- a/tests/fixture/appconnection/appconnection.go+++ b/tests/fixture/appconnection/appconnection.go@@ -1,9 +1,8 @@-// Package appconnection creates app connections against stubbed providers.+// Package appconnection creates app connections against faked providers.//-// Creating one calls the third party to check the credentials, so a connection and-// the stubs that stand in for its service arrive together: the fixture registers-// the provider's validation calls before it creates anything, or the create fails-// rather than the assertion.+// Creating one calls the third party to check the credentials. The fake answers by+// existing, so nothing has to be registered first; what the fixture carries is the+// credential, which is the key that connection's fake state is held under.package appconnectionimport (@@ -11,15 +10,13 @@ import ("testing""github.com/Infisical/infisical/tests/harness"- "github.com/Infisical/infisical/tests/infra/wiremock"+ "github.com/Infisical/infisical/tests/infra/fakenet""github.com/Infisical/infisical/tests/internal/id""github.com/Infisical/infisical/tests/provider"- "github.com/Infisical/infisical/tests/stub""github.com/google/uuid")-// Connection is one app connection and the stubs standing in for the service-// behind it.+// Connection is one app connection and the credential that addresses its fake.type Connection struct {ID uuid.UUIDName string@@ -76,13 +73,13 @@ func Try(tt *testing.T, tn *harness.Tenant, p provider.Provider, opts ...Option)tn: tn,}- scope := conn.Stub(tt)- for _, s := range p.Validate(conn.nonce) {- if cfg.rejectWith != 0 {- s.Status = cfg.rejectWith- s.JSONBody = map[string]any{"message": "harness: credential rejected"}- }- scope.Register(tt, s)+ // The fake answers the credential check by existing, so nothing has to be+ // registered for a connection to be created. Refusing one is the exception, and+ // it goes in before the create: the scope is the credential, which the fixture+ // already knows, so the rule is in place before the first call carries it.+ if cfg.rejectWith != 0 {+ fakenet.Open[any](tt, conn.FakenetAdmin(tt), p.Host, conn.nonce).+ Fail(tt, "", "*", cfg.rejectWith, 0)}connID, err := p.Create(tt.Context(), tn.Admin.API, conn.Name, conn.nonce)@@ -93,41 +90,35 @@ func Try(tt *testing.T, tn *harness.Tenant, p provider.Provider, opts ...Option)return conn, nil}-// Stub returns the stub scope for this connection.-//-// A method rather than a field so a suite without WireMock fails here naming the-// fix, where a field would be a nil dereference inside the stub client.-func (c *Connection) Stub(tt *testing.T) *stub.Scope {- tt.Helper()-- if c.Provider.Auth == nil {- tt.Fatalf("appconnection: provider %q defines no Auth discriminator.\n"+- "Without one its stubs would match every tenant's requests, so parallel tests "+- "would see each other's calls. Add Auth to the registry entry.", c.Provider.App)- }-- h := c.tn.Module(tt, wiremock.Key, "harness.Shared").(*wiremock.Handle)- sc := stub.New(tt, h.NewAdminClient(), c.Provider.Auth(c.nonce), c.nonce)- tt.Cleanup(func() { _ = sc.Remove(context.WithoutCancel(tt.Context())) })- return sc-}-// unstubbedHint turns "the provider call failed" into the URL nobody stubbed.//// The application reports a validation failure or a 501 and rarely names the URL,// so without this the test author is left guessing which call they missed.func unstubbedHint(tt *testing.T, tn *harness.Tenant) string {- h, ok := tn.Module(tt, wiremock.Key, "harness.Shared").(*wiremock.Handle)+ h, ok := tn.Module(tt, fakenet.Key, "harness.Shared").(*fakenet.Handle)if !ok {return ""}- calls, err := h.NewAdminClient().Unstubbed(context.WithoutCancel(tt.Context()))- if err != nil || len(calls) == 0 {+ denied, err := h.Denied(context.WithoutCancel(tt.Context()))+ if err != nil || len(denied) == 0 {return ""}- out := "Outbound calls that reached no stub:\n"- for _, c := range calls {- out += " " + c + "\n"+ out := "Outbound calls that reached no fake:\n"+ for _, d := range denied {+ out += " " + d.Method + " " + d.URL + ": " + d.Reason + "\n"}- return out+ return out + "Add a Service to fakenet.New in cmd/fakenet, or a route to the fake that owns that host.\n"+}++// Nonce is the credential this connection authenticates with, and therefore the key+// its fake state is held under inside fakenet.+func (c *Connection) Nonce() string { return c.nonce }++// FakenetAdmin is where this connection's fake can be read and driven.+//+// Returned as a URL rather than a typed handle so that a fake package never has to+// import this one: fixtures may depend on the harness, and fakes depend on neither.+func (c *Connection) FakenetAdmin(tt *testing.T) string {+ tt.Helper()+ return c.tn.Module(tt, fakenet.Key, "harness.Shared").(*fakenet.Handle).AdminURL()}diff --git a/tests/go.mod b/tests/go.modindex ff21d1c419..5d89ab2a96 100644--- a/tests/go.mod+++ b/tests/go.mod@@ -2,7 +2,13 @@ module github.com/Infisical/infisical/testsgo 1.27.0-require github.com/testcontainers/testcontainers-go v0.44.0+require (+ github.com/google/uuid v1.6.0+ github.com/moby/moby/api v1.55.0+ github.com/oapi-codegen/runtime v1.7.0+ github.com/testcontainers/testcontainers-go v0.44.0+ golang.org/x/crypto v0.54.0+)require (dario.cat/mergo v1.0.2 // indirect@@ -30,13 +36,11 @@ require (github.com/go-ole/go-ole v1.3.0 // indirectgithub.com/go-openapi/jsonpointer v0.23.1 // indirectgithub.com/go-openapi/swag/jsonname v0.26.0 // indirect- github.com/google/uuid v1.6.0 // indirectgithub.com/klauspost/compress v1.18.6 // indirectgithub.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirectgithub.com/magiconair/properties v1.8.10 // indirectgithub.com/moby/docker-image-spec v1.3.1 // indirectgithub.com/moby/go-archive v0.2.0 // indirect- github.com/moby/moby/api v1.55.0 // indirectgithub.com/moby/moby/client v0.5.0 // indirectgithub.com/moby/patternmatcher v0.6.1 // indirectgithub.com/moby/sys/sequential v0.7.0 // indirect@@ -44,7 +48,6 @@ require (github.com/moby/sys/userns v0.1.0 // indirectgithub.com/moby/term v0.5.2 // indirectgithub.com/oapi-codegen/oapi-codegen/v2 v2.8.0 // indirect- github.com/oapi-codegen/runtime v1.7.0 // indirectgithub.com/oasdiff/yaml v0.1.1 // indirectgithub.com/oasdiff/yaml3 v0.0.14 // indirectgithub.com/opencontainers/go-digest v1.0.0 // indirect@@ -67,7 +70,6 @@ require (go.opentelemetry.io/otel/metric v1.44.0 // indirectgo.opentelemetry.io/otel/trace v1.44.0 // indirectgo.yaml.in/yaml/v3 v3.0.4 // indirect- golang.org/x/crypto v0.54.0 // indirectgolang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 // indirectgolang.org/x/mod v0.38.0 // indirectgolang.org/x/sync v0.22.0 // indirectdiff --git a/tests/go.sum b/tests/go.sumindex 427c6189ac..3bb2485b85 100644--- a/tests/go.sum+++ b/tests/go.sum@@ -32,12 +32,13 @@ github.com/cpuguy83/dockercfg v0.3.2/go.mod h1:sugsbF4//dDlL/i+S+rtpIWp+5h0BHJHfgithub.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=-github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=+github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo=+github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=@@ -50,6 +51,7 @@ github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAgithub.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=+github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=github.com/getkin/kin-openapi v0.142.0 h1:izj0vBdFprMhitfzaX8sTqztsEQyvwhssBoB6n8NO7w=github.com/getkin/kin-openapi v0.142.0/go.mod h1:3BH9M9XDe/y9M5DSvEocVYAYq1w0qrhJHjC/vZi0AaY=@@ -65,6 +67,8 @@ github.com/go-openapi/jsonpointer v0.23.1 h1:1HBACs7XIwR2RcmItfdSFlALhGbe6S92p0rgithub.com/go-openapi/jsonpointer v0.23.1/go.mod h1:iWRmZTrGn7XwYhtPt/fvdSFj1OfNBngqRT2UG3BxSqY=github.com/go-openapi/swag/jsonname v0.26.0 h1:gV1NFX9M8avo0YSpmWogqfQISigCmpaiNci8cGECU5w=github.com/go-openapi/swag/jsonname v0.26.0/go.mod h1:urBBR8bZNoDYGr653ynhIx+gTeIz0ARZxHkAPktJK2M=+github.com/go-openapi/testify/v2 v2.4.2 h1:tiByHpvE9uHrrKjOszax7ZvKB7QOgizBWGBLuq0ePx4=+github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw=github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=@@ -119,7 +123,10 @@ github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYgithub.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=+github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=+github.com/oapi-codegen/nullable v1.1.0 h1:eAh8JVc5430VtYVnq00Hrbpag9PFRGWLjxR1/3KntMs=+github.com/oapi-codegen/nullable v1.1.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY=github.com/oapi-codegen/oapi-codegen/v2 v2.8.0 h1:s4hxMxuqtR8jPzXkBTtFwY/SBuj3gEAYikmbBSdtLMM=github.com/oapi-codegen/oapi-codegen/v2 v2.8.0/go.mod h1:yae2TI9IYB5vxQ35gFrpXh9L5H1eJv4MAUK1jumGMTo=github.com/oapi-codegen/runtime v1.7.0 h1:t7358VYPvNbWJ9gdAkIK/smVeHpBf6yp8VTsaZsb/7k=@@ -131,18 +138,19 @@ github.com/oasdiff/yaml3 v0.0.14/go.mod h1:csto2xfDjYccdUn/yw/bPjj/cYTdp6HtFA0J4github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=github.com/onsi/ginkgo v1.10.2/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=+github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc=github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=github.com/onsi/ginkgo/v2 v2.1.3/go.mod h1:vw5CSIxN1JObi/U8gcbwft7ZxR2dgaR70JSE3/PpL4c=github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=+github.com/onsi/gomega v1.19.0 h1:4ieX6qQjPP/BfC3mpsAtIGGlxTWPeA3Inl/7DtXw1tw=github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=-github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=@@ -152,6 +160,7 @@ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tgithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=+github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=@@ -202,7 +211,6 @@ golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8Ugolang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=-golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 h1:985EYyeCOxTpcgOTJpflJUwOeEz0CQOdPt73OzpE9F8=golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678 h1:1P7xPZEwZMoBoz0Yze5Nx2/4pxj6nw9ZqHWXqP0iRgQ=golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=@@ -215,6 +223,8 @@ golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=+golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=+golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=@@ -255,6 +265,8 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtngolang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE=golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=+golang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=+golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=@@ -272,11 +284,13 @@ gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=+gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=gopkg.in/yaml.v3 v3.0.0-20191026110619-0b21df46bc1d/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/tests/harness/harness.go b/tests/harness/harness.goindex 0a2351147d..7b7b05f244 100644--- a/tests/harness/harness.go+++ b/tests/harness/harness.go@@ -18,10 +18,10 @@ import ("sync""testing"+ "github.com/Infisical/infisical/tests/fakes/license""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"+ "github.com/Infisical/infisical/tests/infra/fakenet")// current is the stack Main built, read by From. One per test binary, which is what@@ -36,9 +36,11 @@ type Stack struct {pkg stringmainFile string- app *infisical.Handle- root infisical.Root- license *license.Server+ app *infisical.Handle+ root infisical.Root++ // defaultPlan is what a tenant gets unless it asks for something narrower.+ defaultPlan license.PlanadminOnce sync.OnceinstanceAdmin *Principal@@ -126,8 +128,21 @@ func bringUp(ctx context.Context, profile Profile, cfg *config, pkg string) (*Stif err != nil {return nil, nil, err}+ fnImg, err := fakenet.ResolveImage(ctx, root, log)+ if err != nil {+ return nil, nil, err+ }++ // Generated once and kept, because Infisical is handed this certificate when its+ // container is created and adopted by later binaries. Editing a fake rebuilds+ // fakenet; a CA minted per boot would leave the running Infisical trusting an+ // authority that no longer exists.+ caFile := filepath.Join(root, "tests", fakenet.CAFile)+ if _, err = fakenet.LoadOrCreateCA(caFile); err != nil {+ return nil, nil, err+ }- mods, scopes := profile.modules(img, cfg.extra...)+ mods, scopes := profile.modules(img, fnImg, caFile, cfg.extra...)plan, err := infra.Resolve(mods, scopes)if err != nil {return nil, nil, err@@ -138,16 +153,14 @@ func bringUp(ctx context.Context, profile Profile, cfg *config, pkg string) (*Streturn nil, nil, err}- // An Isolated package takes its own network so its WireMock can hold a host alias- // without competing with the shared one for the name. Shared containers stay on- // the shared network and are connected to this one below.+ // One network for everything, including Isolated packages.+ //+ // Isolated used to take its own, because two WireMocks on one network both+ // claimed api.github.com and Docker DNS round-robined between them. fakenet holds+ // no aliases -- it is reached as a resolver at a fixed address -- so that reason+ // is gone. Isolation for an Isolated package is about instance state, not the+ // network, and its containers are package-qualified by name anyway.stackNet := infra.NetworkName- if profile == Isolated {- stackNet = infra.PackageNetwork(pkg)- if err := runner.Network(ctx, stackNet); err != nil {- return nil, nil, err- }- }handles := map[infra.Key]infra.Handle{}var owned []infra.Handle@@ -160,43 +173,20 @@ func bringUp(ctx context.Context, profile Profile, cfg *config, pkg string) (*Stname.ScopeID = pkg}- net := stackNet- if scope == infra.Shared {- net = infra.NetworkName- }-- h, err := mod.Start(ctx, infra.NewDeps(handles, net, infra.Workspace(), name, runner, log))+ h, err := mod.Start(ctx, infra.NewDeps(handles, stackNet, infra.Workspace(), name, runner, log))if err != nil {stopAll(ctx, owned)return nil, nil, err}handles[mod.Key()] = h- // A Shared container lives on the shared network, so an Isolated stack has to- // be let in explicitly. The alias is the container name, because that is what- // Internal addressing resolves to.- if scope == infra.Shared && net != stackNet {- if err := runner.Connect(ctx, infra.ContainerName(name), stackNet); err != nil {- stopAll(ctx, owned)- return nil, nil, err- }- }-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- }- }+ stack := &Stack{profile: profile, modules: handles, log: log, pkg: pkg, app: app, defaultPlan: cfg.plan}if stack.root, err = infisical.Bootstrap(ctx, app.BaseURL(infra.External)); err != nil {stopAll(ctx, owned)diff --git a/tests/harness/infisical/infisical.go b/tests/harness/infisical/infisical.goindex 199dfb9c91..d396138f1f 100644--- a/tests/harness/infisical/infisical.go+++ b/tests/harness/infisical/infisical.go@@ -9,12 +9,12 @@ import ("context""fmt"- "github.com/Infisical/infisical/tests/harness/license"+ "github.com/Infisical/infisical/tests/fakes/license""github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/infra/fakenet""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 (@@ -71,8 +71,10 @@ func (m *module) Key() infra.Key { return Key }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} }+// all; fakenet is what makes outbound calls and entitlements controllable.+func (m *module) Optional() []infra.Key {+ return []infra.Key{mailpit.Key, fakenet.Key}+}func (m *module) Name() infra.NameParts {return infra.NameParts{Module: "infisical", Fingerprint: m.image.ShortID()}@@ -114,30 +116,30 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)}var files []infra.File- 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)-- // Browser proxying signs a certificate per host with WireMock's own CA, so- // without this every HTTPS call through the proxy fails verification. Node- // warns about a missing NODE_EXTRA_CA_CERTS and carries on, which makes the- // omission silent: HTTP keeps working and every real provider breaks.- ca, err := wm.CAFile(ctx)- if err != nil {+ var dns []string++ // Outbound interception is DNS, not a proxy. Every hostname resolves to fakenet,+ // which answers as the service or refuses by name, so no HTTP client has to+ // honour HTTP_PROXY. Docker's embedded resolver still answers container names+ // first, so Postgres and Redis are unaffected.+ if fn, ok := fakenet.From(d); ok {+ if err := fn.VerifyCA(ctx); err != nil {return nil, err}- files = append(files, infra.File{Src: ca, Dst: wiremock.CAPath})- env["NODE_EXTRA_CA_CERTS"] = wiremock.CAPath+ dns = append(dns, fn.Resolver())+ files = append(files, infra.File{Src: fn.CAPEMFile(), Dst: fakenet.CAPath})+ env["NODE_EXTRA_CA_CERTS"] = fakenet.CAPath++ // fakenet answers for public hostnames from a private address, which the+ // SSRF guard would otherwise refuse. Node also warns about a missing+ // NODE_EXTRA_CA_CERTS and carries on, so the file above is not optional:+ // without it HTTP keeps working and every real provider breaks.env["ALLOW_INTERNAL_IP_CONNECTIONS"] = "true"- // 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) {+ // The License Server is one more fake, reached the same way as any other+ // third party: by name, over TLS fakenet terminates. It is what makes+ // entitlements resolve per organization rather than per instance.+ for k, v := range license.Env() {env[k] = v}}@@ -151,6 +153,7 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)Env: env,Ports: []int{port},Files: files,+ DNS: dns,// /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 adiff --git a/tests/harness/license/server.go b/tests/harness/license/server.godeleted file mode 100644index a592783197..0000000000--- a/tests/harness/license/server.go+++ /dev/null@@ -1,114 +0,0 @@-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)- }-- // Deleting an organization cancels its subscription against the license server,- // and the delete fails if that call does. Every tenant registers its own removal- // on t.Cleanup, so without this each test leaks its organization into the shared- // database for the life of the run.- //- // The outcome is parsed rather than ignored, so an empty body is not enough: the- // delete fails validating the response it just got.- if _, err := s.wm.Register(ctx, wiremock.Stub{- Method: "POST",- URLRe: `/v1/organizations/[^/]+/subscription/cancel`,- Status: 200,- JSONBody: map[string]any{"outcome": "subscription_canceled"},- Priority: priorityFallback,- Metadata: map[string]string{"harness": "license-fallback"},- }); err != nil {- return fmt.Errorf("license: installing subscription cancellation: %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/harness/profile.go b/tests/harness/profile.goindex 4483324028..10dad19a6c 100644--- a/tests/harness/profile.go+++ b/tests/harness/profile.go@@ -3,30 +3,12 @@ package harnessimport ("github.com/Infisical/infisical/tests/harness/infisical""github.com/Infisical/infisical/tests/infra"+ "github.com/Infisical/infisical/tests/infra/fakenet""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")-// stubbedHosts are resolved to WireMock by Docker DNS instead of to the real-// service.-//-// Needed because Infisical's SSRF-safe client resolves a hostname up front and pins-// the socket to that IP, which leaves it dialling the real host on the proxy's port-// and hanging. The alias makes the pinned address WireMock's own, so the request-// lands on the proxy and WireMock still forges a certificate for the hostname from-// the CONNECT line. Providers on plain axios do not need an entry; they follow-// HTTP_PROXY on their own.-//-// One list for the whole run, not per suite: Docker DNS aliases are fixed when the-// container is created, and the container is shared. After changing this, run-// `make down` -- the name does not change, so a running WireMock would be adopted-// with the old aliases and the new host would quietly reach the internet.-var stubbedHosts = []string{- "api.github.com",-}-// 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@@ -60,7 +42,7 @@ func (p Profile) String() string {//// 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) {+func (p Profile) modules(img infisical.Image, fnImg fakenet.Image, caFile string, extra ...infra.Module) ([]infra.Module, map[infra.Key]infra.Scope) {own := infra.Sharedif p == Isolated {own = infra.Package@@ -70,14 +52,16 @@ func (p Profile) modules(img infisical.Image, extra ...infra.Module) ([]infra.Mopostgres.Module(),redis.Module(),mailpit.Module(),- wiremock.Module(wiremock.WithHostAliases(stubbedHosts...)),+ fakenet.Module(fakenet.WithImage(fnImg), fakenet.WithCAFile(caFile)),infisical.Module(infisical.WithImage(img)),}scopes := map[infra.Key]infra.Scope{- postgres.Key: own,- redis.Key: own,- mailpit.Key: infra.Shared,- wiremock.Key: own,+ postgres.Key: own,+ redis.Key: own,+ mailpit.Key: infra.Shared,+ // Shared even under Isolated: it holds a fixed address on the network, and+ // isolation between tenants is by credential rather than by server.+ fakenet.Key: infra.Shared,infisical.Key: own,}diff --git a/tests/harness/tenant.go b/tests/harness/tenant.goindex 5e9a3f1c04..f326981a37 100644--- a/tests/harness/tenant.go+++ b/tests/harness/tenant.go@@ -9,9 +9,10 @@ import ("testing""github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/license""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/fakenet""github.com/Infisical/infisical/tests/internal/apierr""github.com/google/uuid")@@ -148,12 +149,10 @@ func (s *Stack) NewTenant(t *testing.T, opts ...TenantOption) *Tenant {// 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)- }++ fn := t.stack.Require(tt, fakenet.Key, "harness.Shared").(*fakenet.Handle)+ license.Open(tt, fn.AdminURL(), t.OrgID.String()).Seed(tt, p)+t.plan = &pt.Verify(tt, p)}diff --git a/tests/harnesstest/isolated/profile_test.go b/tests/harnesstest/isolated/profile_test.goindex 1d78f95ce5..64bf62d6de 100644--- a/tests/harnesstest/isolated/profile_test.go+++ b/tests/harnesstest/isolated/profile_test.go@@ -3,23 +3,18 @@ package harnesstest_testimport ("testing"+ "github.com/Infisical/infisical/tests/fakes/github""github.com/Infisical/infisical/tests/fixture/appconnection""github.com/Infisical/infisical/tests/harness"- "github.com/Infisical/infisical/tests/internal/spec""github.com/Infisical/infisical/tests/provider")-func TestIsolated_OwnsItsStubbing(t *testing.T) {- spec.Why(t, `The only thing unique to this profile that the harness itself owns. An- Isolated package runs its own WireMock, and a host alias belongs to the network- rather than the container. Before the profile took a network of its own, both- WireMocks claimed api.github.com on one network and Docker DNS round-robined- between them, so a stub registered here was missed by requests landing on the- shared one. This is the regression test for that.`)+func TestIsolated_ReachesTheSharedFakenet(t *testing.T) {conn := appconnection.New(t, harness.From(t).NewTenant(t), provider.GitHub)+ gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())- if n := conn.Stub(t).Received(t, "GET", "/user"); n != 1 {- t.Fatalf("the credential check reached this package's stub %d times, want 1", n)+ if n := gh.Received(t, "GET", "/user"); n != 1 {+ t.Fatalf("the credential check reached fakenet %d times, want 1", n)}}diff --git a/tests/harnesstest/shared/licensing_test.go b/tests/harnesstest/shared/licensing_test.goindex 792acb017b..8f945ec784 100644--- a/tests/harnesstest/shared/licensing_test.go+++ b/tests/harnesstest/shared/licensing_test.go@@ -3,8 +3,8 @@ package harnesstest_testimport ("testing"+ "github.com/Infisical/infisical/tests/fakes/license""github.com/Infisical/infisical/tests/harness"- "github.com/Infisical/infisical/tests/harness/license""github.com/Infisical/infisical/tests/internal/spec")diff --git a/tests/harnesstest/shared/stubbing_test.go b/tests/harnesstest/shared/stubbing_test.goindex 8e7eab926d..9c09d7d78a 100644--- a/tests/harnesstest/shared/stubbing_test.go+++ b/tests/harnesstest/shared/stubbing_test.go@@ -4,6 +4,7 @@ import ("net/http""testing"+ "github.com/Infisical/infisical/tests/fakes/github""github.com/Infisical/infisical/tests/fixture/appconnection""github.com/Infisical/infisical/tests/harness""github.com/Infisical/infisical/tests/internal/spec"@@ -14,49 +15,53 @@ func TestOutbound_IsIntercepted(t *testing.T) {t.Parallel()h := harness.From(t)- t.Run("ok/an outbound call reaches the stub", func(t *testing.T) {+ t.Run("ok/an outbound call reaches the fake", func(t *testing.T) {t.Parallel()- spec.Why(t, `The one test the whole stubbing design rests on. The connection is- created with no host, so GitHub's client resolves api.github.com, and the only- way that request can reach WireMock is the forward proxy and the injected CA.- If it stops passing, no integration test anywhere is testing anything real.`)+ spec.Why(t, `The one test the whole design rests on. The connection is created with+ no host, so GitHub's client resolves api.github.com, and the only way that+ request can arrive here is fakenet answering DNS and presenting a certificate+ the instance was told to trust. If it stops passing, no integration test+ anywhere is testing anything real.`)conn := appconnection.New(t, h.NewTenant(t), provider.GitHub)+ gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())- if n := conn.Stub(t).Received(t, "GET", "/user"); n != 1 {- t.Fatalf("the credential check reached the stub %d times, want 1", n)+ if n := gh.Received(t, "GET", "/user"); n != 1 {+ t.Fatalf("the credential check reached the fake %d times, want 1", n)}})- t.Run("cross-tenant/two connections stubbing one path stay separate", func(t *testing.T) {+ t.Run("cross-tenant/two connections to one service stay separate", func(t *testing.T) {t.Parallel()- spec.Why(t, `One WireMock serves every tenant, so isolation is by discriminator- rather than by server. Each connection authenticates with its own credential- and the journal is filtered on it, which is why no org id has to be threaded- through a stub.`)+ spec.Why(t, `One fakenet serves every tenant, so isolation is by credential rather+ than by server. Each connection authenticates with its own, and state is held+ under it, which is why no org id has to be threaded anywhere.`)a := appconnection.New(t, h.NewTenant(t), provider.GitHub)b := appconnection.New(t, h.NewTenant(t), provider.GitHub)// Both created a connection, so both made the same call to the same path.for name, conn := range map[string]*appconnection.Connection{"a": a, "b": b} {- if n := conn.Stub(t).Received(t, "GET", "/user"); n != 1 {+ gh := github.Open(t, conn.FakenetAdmin(t), conn.Nonce())+ if n := gh.Received(t, "GET", "/user"); n != 1 {t.Errorf("connection %s counted %d requests, want only its own 1", name, n)}}})- t.Run("invalid/what the stub answers is load bearing", func(t *testing.T) {+ t.Run("invalid/what the fake answers is load bearing", func(t *testing.T) {t.Parallel()spec.Why(t, `The interception test above proves a request arrived. On its own that- is not enough: if the application ignored the response, every stubbed value a- test asserts on would be decoration. Changing the answer has to change the- outcome.`)+ is not enough: if the application ignored the response, every value a test+ asserts on would be decoration. Changing the answer has to change the outcome.+ The refusal is a fakenet rule registered against the credential before the+ connection exists, which doubles as the failure-injection path.`)_, err := appconnection.Try(t, h.NewTenant(t), provider.GitHub,appconnection.RejectCredentials(http.StatusUnauthorized))if err == nil {- t.Fatal("the connection was created even though the stub rejected the credential")+ t.Fatal("the connection was created even though the credential check was refused")}})+}diff --git a/tests/infra/container.go b/tests/infra/container.goindex b5b25df667..97ed288497 100644--- a/tests/infra/container.go+++ b/tests/infra/container.go@@ -32,8 +32,21 @@ type ContainerSpec struct {// Network is which network to join. Empty means the runner's current one.Network string- Files []File- Labels map[string]string++ // IP pins the container's address on that network.+ //+ // Only fakenet needs one. Infisical is told where to resolve DNS when its+ // container is created and is then adopted by later test binaries, so that+ // address has to survive fakenet being rebuilt.+ IP string++ // DNS replaces the container's resolvers. Docker's embedded resolver still+ // answers container names first and forwards only what it cannot, so sibling+ // containers keep resolving normally.+ DNS []string++ Files []File+ Labels map[string]string// Ready is applied by the container engine while the container starts. It// answers "is it up".diff --git a/tests/infra/fakenet/admin.go b/tests/infra/fakenet/admin.gonew file mode 100644index 0000000000..7fef3487aa--- /dev/null+++ b/tests/infra/fakenet/admin.go@@ -0,0 +1,129 @@+package fakenet++import (+ "encoding/json"+ "io"+ "net/http"+)++// AdminPrefix is the control surface, served on its own port so the application can+// never reach it. It is generic: the engine moves bytes and never interprets a+// fake's state or seed document.+const AdminPrefix = "/__fake"++// Admin returns the control API.+func (s *Server) Admin(ca *CA) http.Handler {+ mux := http.NewServeMux()++ mux.HandleFunc("GET "+AdminPrefix+"/health", func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte("ok"))+ })++ // What to print when a test failed for want of a fake. The application reports a+ // validation failure and rarely names the URL, so without this the author is left+ // guessing which call they missed.+ mux.HandleFunc("GET "+AdminPrefix+"/denied", func(w http.ResponseWriter, _ *http.Request) {+ s.mu.Lock()+ out := append([]Denied(nil), s.denied...)+ s.mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(out)+ })++ mux.HandleFunc("GET "+AdminPrefix+"/ca", func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/x-pem-file")+ _, _ = w.Write(ca.CertPEM())+ })++ mux.HandleFunc("GET "+AdminPrefix+"/scopes/{host}/{key}/state", func(w http.ResponseWriter, r *http.Request) {+ sc, err := s.adminScope(r)+ if err != nil {+ adminErr(w, err)+ return+ }+ body, mErr := sc.fake.Snapshot()+ if mErr != nil {+ http.Error(w, mErr.Error(), http.StatusInternalServerError)+ return+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write(body)+ })++ mux.HandleFunc("POST "+AdminPrefix+"/scopes/{host}/{key}/seed", func(w http.ResponseWriter, r *http.Request) {+ sc, err := s.adminScope(r)+ if err != nil {+ adminErr(w, err)+ return+ }+ raw, _ := io.ReadAll(r.Body)+ if sErr := sc.fake.Seed(raw); sErr != nil {+ http.Error(w, sErr.Error(), http.StatusBadRequest)+ return+ }+ w.WriteHeader(http.StatusNoContent)+ })++ mux.HandleFunc("POST "+AdminPrefix+"/scopes/{host}/{key}/rules", func(w http.ResponseWriter, r *http.Request) {+ sc, err := s.adminScope(r)+ if err != nil {+ adminErr(w, err)+ return+ }+ var rule Rule+ if dErr := json.NewDecoder(r.Body).Decode(&rule); dErr != nil {+ http.Error(w, dErr.Error(), http.StatusBadRequest)+ return+ }+ s.mu.Lock()+ sc.rules = append(sc.rules, &rule)+ s.mu.Unlock()+ w.WriteHeader(http.StatusNoContent)+ })++ mux.HandleFunc("GET "+AdminPrefix+"/scopes/{host}/{key}/calls", func(w http.ResponseWriter, r *http.Request) {+ sc, err := s.adminScope(r)+ if err != nil {+ adminErr(w, err)+ return+ }+ s.mu.Lock()+ calls := append([]Call(nil), sc.calls...)+ s.mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(calls)+ })++ mux.HandleFunc("DELETE "+AdminPrefix+"/scopes/{host}/{key}", func(w http.ResponseWriter, r *http.Request) {+ s.mu.Lock()+ delete(s.scopes, scopeID{r.PathValue("host"), r.PathValue("key")})+ s.mu.Unlock()+ w.WriteHeader(http.StatusNoContent)+ })++ return mux+}++// adminScope resolves a scope, creating it if the test is seeding before the product+// has made its first call.+func (s *Server) adminScope(r *http.Request) (*scope, error) {+ host, key := r.PathValue("host"), r.PathValue("key")+ s.mu.Lock()+ svc, ok := s.services[host]+ s.mu.Unlock()+ if !ok {+ return nil, errUnknownHost(host)+ }+ return s.scope(host, svc, key), nil+}++type errUnknownHost string++func (e errUnknownHost) Error() string {+ return "fakenet: no fake registered for host " + string(e) ++ "\nAdd its Service to fakenet.New in cmd/fakenet."+}++func adminErr(w http.ResponseWriter, err error) {+ http.Error(w, err.Error(), http.StatusNotFound)+}diff --git a/tests/infra/fakenet/ca.go b/tests/infra/fakenet/ca.gonew file mode 100644index 0000000000..9bc57b3443--- /dev/null+++ b/tests/infra/fakenet/ca.go@@ -0,0 +1,193 @@+package fakenet++import (+ "crypto/ecdsa"+ "crypto/elliptic"+ "crypto/rand"+ "crypto/tls"+ "crypto/x509"+ "crypto/x509/pkix"+ "encoding/pem"+ "fmt"+ "math/big"+ "os"+ "path/filepath"+ "sync"+ "time"+)++// CA signs a certificate per hostname on demand.+//+// Per name rather than one certificate carrying every faked host as a SAN, because a+// host nobody faked still has to complete a handshake before it can be told, in a+// 501, that it was never faked. A fixed SAN list cannot answer for a name it has+// never heard of.+type CA struct {+ cert *x509.Certificate+ key *ecdsa.PrivateKey+ pem []byte++ mu sync.Mutex+ cache map[string]*tls.Certificate+}++// LoadOrCreateCA reads the CA at path, creating it if absent.+//+// It has to outlive the container. Infisical is handed this certificate once, when+// its container is created, and is then adopted by later test binaries; a CA minted+// at boot would be replaced every time a fake is edited, and the running Infisical+// would trust an authority that no longer exists.+func LoadOrCreateCA(path string) (*CA, error) {+ if b, err := os.ReadFile(path); err == nil {+ ca, pErr := parseCA(b)+ if pErr == nil {+ return ca, nil+ }+ // A truncated or half-written file is not worth a manual recovery step.+ if rErr := os.Remove(path); rErr != nil {+ return nil, fmt.Errorf("fakenet: removing unreadable CA %s: %w", path, rErr)+ }+ }++ ca, keyPEM, err := newCA()+ if err != nil {+ return nil, err+ }+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ return nil, err+ }+ if err := os.WriteFile(path, append(append([]byte{}, ca.pem...), keyPEM...), 0o600); err != nil {+ return nil, fmt.Errorf("fakenet: writing CA to %s: %w", path, err)+ }+ return ca, nil+}++func newCA() (*CA, []byte, error) {+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ if err != nil {+ return nil, nil, err+ }+ tmpl := &x509.Certificate{+ SerialNumber: big.NewInt(1),+ Subject: pkix.Name{+ // Named so that anyone who finds it in a real trust store knows at once+ // what it is and that it does not belong there.+ CommonName: "Infisical test harness fakenet CA (test use only)",+ Organization: []string{"Infisical blackbox test harness"},+ },+ NotBefore: time.Now().Add(-time.Hour),+ NotAfter: time.Now().AddDate(10, 0, 0),+ KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature,+ BasicConstraintsValid: true,+ IsCA: true,+ }+ der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)+ if err != nil {+ return nil, nil, err+ }+ cert, err := x509.ParseCertificate(der)+ if err != nil {+ return nil, nil, err+ }+ keyDER, err := x509.MarshalECPrivateKey(key)+ if err != nil {+ return nil, nil, err+ }+ return &CA{+ cert: cert,+ key: key,+ pem: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}),+ cache: map[string]*tls.Certificate{},+ },+ pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER}),+ nil+}++func parseCA(b []byte) (*CA, error) {+ var certDER, keyDER []byte+ for {+ block, rest := pem.Decode(b)+ if block == nil {+ break+ }+ switch block.Type {+ case "CERTIFICATE":+ certDER = block.Bytes+ case "EC PRIVATE KEY":+ keyDER = block.Bytes+ }+ b = rest+ }+ if certDER == nil || keyDER == nil {+ return nil, fmt.Errorf("fakenet: CA file is missing a certificate or a key")+ }+ cert, err := x509.ParseCertificate(certDER)+ if err != nil {+ return nil, err+ }+ key, err := x509.ParseECPrivateKey(keyDER)+ if err != nil {+ return nil, err+ }+ return &CA{+ cert: cert,+ key: key,+ pem: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}),+ cache: map[string]*tls.Certificate{},+ }, nil+}++// CertPEM is what the application trusts, through NODE_EXTRA_CA_CERTS or, for a Go+// service, SSL_CERT_FILE.+func (c *CA) CertPEM() []byte { return c.pem }++// TLSConfig serves any hostname a client asks for.+func (c *CA) TLSConfig() *tls.Config {+ return &tls.Config{+ GetCertificate: c.certFor,+ // http/1.1 only. Node's undici negotiates h2 given the chance and this server+ // speaks one protocol.+ NextProtos: []string{"http/1.1"},+ MinVersion: tls.VersionTLS12,+ }+}++func (c *CA) certFor(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {+ name := hello.ServerName+ if name == "" {+ // No SNI means the client dialled an IP. Nothing can be forged for that, so+ // let the handshake fail against a name the error will report.+ name = "no-sni.invalid"+ }++ c.mu.Lock()+ defer c.mu.Unlock()+ if got, ok := c.cache[name]; ok {+ return got, nil+ }++ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ if err != nil {+ return nil, err+ }+ serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))+ if err != nil {+ return nil, err+ }+ der, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{+ SerialNumber: serial,+ Subject: pkix.Name{CommonName: name},+ DNSNames: []string{name},+ NotBefore: time.Now().Add(-time.Hour),+ NotAfter: time.Now().AddDate(1, 0, 0),+ KeyUsage: x509.KeyUsageDigitalSignature,+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},+ }, c.cert, &key.PublicKey, c.key)+ if err != nil {+ return nil, err+ }++ out := &tls.Certificate{Certificate: [][]byte{der, c.cert.Raw}, PrivateKey: key}+ c.cache[name] = out+ return out, nil+}diff --git a/tests/infra/fakenet/client.go b/tests/infra/fakenet/client.gonew file mode 100644index 0000000000..1ad5bb9b9c--- /dev/null+++ b/tests/infra/fakenet/client.go@@ -0,0 +1,142 @@+package fakenet++import (+ "bytes"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+ "testing"+ "time"+)++// Scope is a test's handle on one caller's state inside fakenet.+//+// Generic over the fake's own state type, so every fake gets seeding, reading,+// failure injection and the call log without writing any of it. A fake package adds+// only names: a typed accessor or two and its seed fragments.+type Scope[S any] struct {+ base string+ host string+ key string+ http *http.Client+}++// Open returns a handle on one scope and removes it when the test ends.+//+// The key is the credential the product will authenticate with, which is what lets+// two parallel tenants share one fakenet without seeing each other.+func Open[S any](tt *testing.T, adminURL, host, key string) *Scope[S] {+ tt.Helper()+ sc := &Scope[S]{+ base: strings.TrimSuffix(adminURL, "/"),+ host: host,+ key: key,+ http: &http.Client{Timeout: 10 * time.Second},+ }+ tt.Cleanup(func() { sc.remove() })+ return sc+}++// State is the fake's own state, as it stands now.+//+// A snapshot rather than a live pointer, because the fake lives in a container. Read+// it at the point of assertion rather than holding it across an action.+func (s *Scope[S]) State(tt *testing.T) *S {+ tt.Helper()+ var out S+ if err := s.do(http.MethodGet, "/state", nil, &out); err != nil {+ tt.Fatalf("fakenet: reading state: %v", err)+ }+ return &out+}++// Seed merges fragments into the fake before the product touches it.+func (s *Scope[S]) Seed(tt *testing.T, fragments ...any) {+ tt.Helper()+ for _, f := range fragments {+ if err := s.do(http.MethodPost, "/seed", f, nil); err != nil {+ tt.Fatalf("fakenet: seeding: %v", err)+ }+ }+}++// Fail makes matching requests answer with status instead of reaching the fake.+// times of 0 applies to every matching request. Path may end in * to match a prefix.+func (s *Scope[S]) Fail(tt *testing.T, method, path string, status, times int) {+ tt.Helper()+ if err := s.do(http.MethodPost, "/rules", Rule{+ Method: method, Path: path, Status: status, Times: times,+ }, nil); err != nil {+ tt.Fatalf("fakenet: adding a rule: %v", err)+ }+}++// Calls is every request this scope received, newest last.+func (s *Scope[S]) Calls(tt *testing.T) []Call {+ tt.Helper()+ var out []Call+ if err := s.do(http.MethodGet, "/calls", nil, &out); err != nil {+ tt.Fatalf("fakenet: reading the call log: %v", err)+ }+ return out+}++// Received counts this scope's requests to a method and path.+func (s *Scope[S]) Received(tt *testing.T, method, path string) int {+ tt.Helper()+ n := 0+ for _, c := range s.Calls(tt) {+ if strings.EqualFold(c.Method, method) && c.Path == path {+ n+++ }+ }+ return n+}++func (s *Scope[S]) remove() {+ req, err := http.NewRequest(http.MethodDelete, s.scopeURL(""), nil)+ if err != nil {+ return+ }+ if res, dErr := s.http.Do(req); dErr == nil {+ _ = res.Body.Close()+ }+}++func (s *Scope[S]) scopeURL(suffix string) string {+ return s.base + AdminPrefix + "/scopes/" + url.PathEscape(s.host) + "/" + url.PathEscape(s.key) + suffix+}++func (s *Scope[S]) do(method, suffix string, in, out any) error {+ var body io.Reader+ if in != nil {+ raw, err := json.Marshal(in)+ if err != nil {+ return err+ }+ body = bytes.NewReader(raw)+ }+ req, err := http.NewRequest(method, s.scopeURL(suffix), body)+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", "application/json")++ res, err := s.http.Do(req)+ if err != nil {+ return fmt.Errorf("%s %s: %w", method, suffix, err)+ }+ defer func() { _ = res.Body.Close() }()++ raw, _ := io.ReadAll(res.Body)+ if res.StatusCode >= 300 {+ return fmt.Errorf("%s %s returned %d: %s", method, suffix, res.StatusCode, strings.TrimSpace(string(raw)))+ }+ if out != nil {+ return json.Unmarshal(raw, out)+ }+ return nil+}diff --git a/tests/infra/fakenet/dns.go b/tests/infra/fakenet/dns.gonew file mode 100644index 0000000000..da8e9be6df--- /dev/null+++ b/tests/infra/fakenet/dns.go@@ -0,0 +1,78 @@+package fakenet++import (+ "encoding/binary"+ "fmt"+ "net"+)++// ServeDNS answers every A query with selfIP. It only returns on a listen failure.+//+// This is what makes the suite hermetic, and it is not optional. Measured: with plain+// Docker network aliases and no DNS of our own, a hostname nobody faked resolves+// through to the real internet and gets a real answer. Pointing the application's+// resolver here means every name leads to fakenet, so an unfaked host gets a 501+// naming it instead of reaching a live API.+//+// Docker's embedded resolver still answers container names first and only forwards+// what it cannot, so postgres and redis keep resolving normally.+func ServeDNS(addr, selfIP string) error {+ ip := net.ParseIP(selfIP).To4()+ if ip == nil {+ return fmt.Errorf("fakenet: %q is not an IPv4 address", selfIP)+ }++ pc, err := net.ListenPacket("udp", addr)+ if err != nil {+ return fmt.Errorf("fakenet: dns listen on %s: %w", addr, err)+ }++ buf := make([]byte, 512)+ for {+ n, from, rErr := pc.ReadFrom(buf)+ if rErr != nil || n < 12 {+ continue+ }+ resp, ok := answer(buf[:n], ip)+ if !ok {+ continue+ }+ _, _ = pc.WriteTo(resp, from)+ }+}++// answer builds a reply by echoing the header and question and appending one A+// record. Hand-rolled because the alternative is a dependency for about forty lines+// of well-specified byte layout.+func answer(q []byte, ip net.IP) ([]byte, bool) {+ off := 12+ for off < len(q) && q[off] != 0 {+ l := int(q[off])+ if l >= 0xC0 || off+1+l > len(q) {+ return nil, false // a pointer in a question is malformed+ }+ off += 1 + l+ }+ off++ // the terminating zero label+ if off+4 > len(q) {+ return nil, false+ }+ qtype := binary.BigEndian.Uint16(q[off : off+2])+ end := off + 4++ resp := make([]byte, 0, end+16)+ resp = append(resp, q[:end]...)+ resp[2] = 0x81 // QR=1, plus the RD bit the client set+ resp[3] = 0x80 // RA=1+ binary.BigEndian.PutUint16(resp[6:8], 0)++ // Anything other than A gets NOERROR with no answers rather than silence, so a+ // client asking AAAA first falls straight through to A instead of waiting out a+ // resolver timeout.+ if qtype == 1 {+ binary.BigEndian.PutUint16(resp[6:8], 1)+ resp = append(resp, 0xC0, 0x0C, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4)+ resp = append(resp, ip...)+ }+ return resp, true+}diff --git a/tests/infra/fakenet/fakenet.go b/tests/infra/fakenet/fakenet.gonew file mode 100644index 0000000000..60f25e2cb8--- /dev/null+++ b/tests/infra/fakenet/fakenet.go@@ -0,0 +1,267 @@+// Package fakenet is the harness's fake internet: one server holding a working+// implementation of every third party Infisical calls out to.+//+// Fakes, not stubs. A fake holds real state and mutates as the product drives it, so+// a test asserts on what the destination ended up holding rather than on which+// requests were sent. That difference is the whole reason this exists: a secret sync+// computes what to delete from what the destination returns, so stubbing that list+// means asserting against a fixture we invented.+//+// Interception is DNS rather than proxy. Every hostname resolves here, so no client+// has to honour HTTP_PROXY, which the AWS, GCP and Azure SDKs never did.+package fakenet++import (+ "encoding/json"+ "log"+ "net/http"+ "strings"+ "sync"+ "time"+)++// Service is one third-party API.+type Service interface {+ // Host is the name the product's client has hardcoded. It has to be hardcoded+ // for a test to mean anything: a configurable base URL pointed straight at+ // fakenet would prove the fake works and nothing about interception.+ Host() string++ // Scope says which caller a request belongs to, by reading the credential off+ // it. Two parallel tenants call the same path and are told apart by what they+ // authenticate with, so no organization id is threaded anywhere.+ Scope(*http.Request) (key string, ok bool)++ // New builds an empty world for one scope.+ New() Fake+}++// Fake is one scope's state.+//+// Snapshot marshals rather than returning a value, so a fake serialises under its own+// lock. Returning the struct and marshalling it later would race with a request+// mutating it.+type Fake interface {+ http.Handler+ Snapshot() ([]byte, error)+ Seed([]byte) error+}++// Call is one request a scope received.+type Call struct {+ Method string `json:"method"`+ Path string `json:"path"`+ Status int `json:"status"`+ At time.Time `json:"at"`+}++// Rule overrides a fake for a matching request. This is failure injection: no real+// API has "fail the next call with a 500", so it cannot be a fake's own behaviour.+type Rule struct {+ Method string `json:"method"`+ Path string `json:"path"`+ Status int `json:"status"`+ Body string `json:"body"`++ // Times is how many matching requests it applies to. Zero means every one.+ Times int `json:"times"`+}++type scopeID struct{ host, key string }++type scope struct {+ fake Fake+ rules []*Rule+ calls []Call+}++// Server holds every fake and dispatches to them.+type Server struct {+ mu sync.Mutex+ services map[string]Service+ scopes map[scopeID]*scope++ // denied is every call that reached no fake. Kept globally rather than per+ // scope because a refusal happens before a scope can be resolved, and it is+ // exactly what a test needs printed when a create failed for want of a fake.+ denied []Denied+}++// Denied is one outbound call that reached no fake.+type Denied struct {+ Method string `json:"method"`+ URL string `json:"url"`+ Reason string `json:"reason"`+ At time.Time `json:"at"`+}++func New(services ...Service) *Server {+ s := &Server{services: map[string]Service{}, scopes: map[scopeID]*scope{}}+ for _, svc := range services {+ s.services[svc.Host()] = svc+ }+ return s+}++// Hosts is every hostname fakenet answers for.+func (s *Server) Hosts() []string {+ out := make([]string, 0, len(s.services))+ for h := range s.services {+ out = append(out, h)+ }+ return out+}++// ServeHTTP is the fake-serving handler, reached over TLS on 443.+func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {+ host := hostOf(r)++ s.mu.Lock()+ svc, known := s.services[host]+ s.mu.Unlock()++ // Every hostname resolves here, so an unfaked one arrives as a normal request+ // rather than failing to connect. Answering it with a 501 naming the URL is what+ // replaces WireMock's deny-all: a forgotten fake has to fail loudly, or a test+ // passes without exercising anything.+ if !known {+ s.refuse(w, r, host, "no fake is registered for this host")+ return+ }++ key, ok := svc.Scope(r)+ if !ok || key == "" {+ s.refuse(w, r, host, "the request carried no credential, so it cannot be attributed to a test")+ return+ }++ sc := s.scope(host, svc, key)++ rec := &recorder{ResponseWriter: w, status: http.StatusOK}+ if rule := s.takeRule(sc, r); rule != nil {+ rec.WriteHeader(rule.Status)+ if rule.Body != "" {+ _, _ = rec.Write([]byte(rule.Body))+ }+ } else {+ sc.fake.ServeHTTP(rec, r)+ }++ s.mu.Lock()+ sc.calls = append(sc.calls, Call{Method: r.Method, Path: r.URL.Path, Status: rec.status, At: time.Now().UTC()})+ s.mu.Unlock()++ // One line per outbound call, always. Container logs are captured to a file+ // anyway, and this is the first thing worth reading when a sync did not do what+ // a test expected: it says whether the call happened at all, and under which+ // credential.+ log.Printf("%-6s %s%s -> %d scope=%s", r.Method, host, r.URL.Path, rec.status, short(key))+}++func short(key string) string {+ if len(key) > 12 {+ return key[:12] + "..."+ }+ return key+}++// scope returns a scope, creating it the first time a credential is seen.+//+// On demand rather than registered, which is why creating an app connection works+// with no test setup: Infisical validates the credential, fakenet meets it for the+// first time, and answers.+func (s *Server) scope(host string, svc Service, key string) *scope {+ s.mu.Lock()+ defer s.mu.Unlock()+ id := scopeID{host, key}+ sc, ok := s.scopes[id]+ if !ok {+ sc = &scope{fake: svc.New()}+ s.scopes[id] = sc+ }+ return sc+}++func (s *Server) takeRule(sc *scope, r *http.Request) *Rule {+ s.mu.Lock()+ defer s.mu.Unlock()+ for i, rule := range sc.rules {+ if !matches(rule, r) {+ continue+ }+ if rule.Times > 0 {+ rule.Times--+ if rule.Times == 0 {+ sc.rules = append(sc.rules[:i], sc.rules[i+1:]...)+ }+ }+ return rule+ }+ return nil+}++func matches(rule *Rule, r *http.Request) bool {+ if rule.Method != "" && !strings.EqualFold(rule.Method, r.Method) {+ return false+ }+ switch {+ case rule.Path == "" || rule.Path == "*":+ return true+ case strings.HasSuffix(rule.Path, "*"):+ return strings.HasPrefix(r.URL.Path, strings.TrimSuffix(rule.Path, "*"))+ default:+ return rule.Path == r.URL.Path+ }+}++// hostOf strips the port, which is present on a proxied request and absent on a+// direct one.+func hostOf(r *http.Request) string {+ h := r.Host+ if i := strings.IndexByte(h, ':'); i >= 0 {+ h = h[:i]+ }+ return h+}++// refuse answers a call nothing can serve, and records it.+//+// 501 rather than a dropped connection, because a refused connection reads to the+// application as a network blip and is often retried.+func (s *Server) refuse(w http.ResponseWriter, r *http.Request, host, reason string) {+ url := "https://" + host + r.URL.Path+ msg := "fakenet has no fake for " + r.Method + " " + url + ": " + reason++ s.mu.Lock()+ s.denied = append(s.denied, Denied{Method: r.Method, URL: url, Reason: reason, At: time.Now().UTC()})+ s.mu.Unlock()++ log.Printf("%-6s %s%s -> 501 %s", r.Method, host, r.URL.Path, reason)++ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusNotImplemented)+ _ = json.NewEncoder(w).Encode(map[string]string{"message": msg})+}++// recorder captures the status for the call log without buffering the body.+type recorder struct {+ http.ResponseWriter+ status int+ written bool+}++func (rec *recorder) WriteHeader(code int) {+ if rec.written {+ return+ }+ rec.status = code+ rec.written = true+ rec.ResponseWriter.WriteHeader(code)+}++func (rec *recorder) Write(b []byte) (int, error) {+ if !rec.written {+ rec.written = true+ }+ return rec.ResponseWriter.Write(b)+}diff --git a/tests/infra/fakenet/module.go b/tests/infra/fakenet/module.gonew file mode 100644index 0000000000..1c827f5b41--- /dev/null+++ b/tests/infra/fakenet/module.go@@ -0,0 +1,280 @@+package fakenet++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync"++ "github.com/Infisical/infisical/tests/infra"+)++const (+ Key = infra.Key("fakenet")++ adminPort = 8080+ httpsPort = 443+ dnsPort = 53++ // IP is fixed so Infisical can be told to resolve here when its container is+ // created and keep working after fakenet is rebuilt. Inside infra.NetworkSubnet;+ // .53 for the resolver it runs.+ IP = "10.201.0.53"++ // CAPath is where the harness places the CA inside the application container.+ CAPath = "/fakenet-ca.pem"++ localTag = "infisical-fakenet:local"+)++// CAFile is where the CA lives on the host, relative to the tests module.+//+// Generated once and reused, because Infisical is handed this certificate when its+// container is created and adopted by later binaries. A CA minted per boot would be+// replaced every time a fake is edited and the running Infisical would trust an+// authority that no longer exists. `inf down` removes it alongside the containers,+// so the two can never disagree.+const CAFile = ".cache/fakenet-ca.pem"++// Image is a built fakenet image.+type Image struct {+ Ref string+ ID string+}++func (i Image) ShortID() string {+ id := strings.TrimPrefix(i.ID, "sha256:")+ if len(id) > 12 {+ return id[:12]+ }+ return id+}++// ResolveImage builds fakenet and returns the image Docker produced.+//+// The binary is compiled on the host and copied into scratch rather than built in a+// golang stage: the module cache is already warm from running tests, so this is about+// a second, where an in-Docker build would download the whole module graph.+func ResolveImage(ctx context.Context, repoRoot string, log infra.Logger) (Image, error) {+ release, err := infra.Lock("fakenet-build")+ if err != nil {+ return Image{}, err+ }+ defer release()++ dir, err := os.MkdirTemp("", "fakenet-build-*")+ if err != nil {+ return Image{}, err+ }+ defer func() { _ = os.RemoveAll(dir) }()++ goarch, err := dockerArch(ctx)+ if err != nil {+ return Image{}, err+ }++ tests := filepath.Join(repoRoot, "tests")+ build := exec.CommandContext(ctx, "go", "build", "-trimpath", "-o", filepath.Join(dir, "fakenet"), "./cmd/fakenet")+ build.Dir = tests+ build.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+goarch, "CGO_ENABLED=0")+ if out, bErr := build.CombinedOutput(); bErr != nil {+ return Image{}, fmt.Errorf("fakenet: building the server: %w\n%s", bErr, out)+ }++ iid := filepath.Join(dir, "iid")+ out, err := exec.CommandContext(ctx, "docker", "build",+ "-f", filepath.Join(tests, "cmd", "fakenet", "Dockerfile"),+ "-t", localTag, "--iidfile", iid, dir).CombinedOutput()+ if err != nil {+ return Image{}, fmt.Errorf("fakenet: docker build failed: %w\n%s", err, out)+ }+ b, err := os.ReadFile(iid)+ if err != nil {+ return Image{}, fmt.Errorf("fakenet: reading image id: %w", err)+ }++ img := Image{Ref: localTag, ID: strings.TrimSpace(string(b))}+ log.Infof("image %s -> %s", localTag, img.ShortID())+ return img, nil+}++// dockerArch asks the daemon what it runs. The binary is cross-compiled on the host,+// and an amd64 binary in an arm64 container fails as "exec format error", which reads+// like a corrupt image rather than a build mistake.+func dockerArch(ctx context.Context) (string, error) {+ out, err := exec.CommandContext(ctx, "docker", "info", "--format", "{{.Architecture}}").Output()+ if err != nil {+ return "", fmt.Errorf("fakenet: asking docker for its architecture: %w", err)+ }+ switch arch := strings.TrimSpace(string(out)); arch {+ case "aarch64", "arm64":+ return "arm64", nil+ case "x86_64", "amd64":+ return "amd64", nil+ default:+ return "", fmt.Errorf("fakenet: unsupported docker architecture %q", arch)+ }+}++type module struct {+ image Image+ caFile string+}++type Option func(*module)++func WithImage(i Image) Option { return func(m *module) { m.image = i } }++// WithCAFile is the host path of the CA to serve with.+func WithCAFile(path string) Option { return func(m *module) { m.caFile = path } }++func Module(opts ...Option) infra.Module {+ m := &module{}+ for _, o := range opts {+ o(m)+ }+ return m+}++func (m *module) Key() infra.Key { return Key }+func (m *module) Requires() []infra.Key { return nil }+func (m *module) Optional() []infra.Key { return nil }++func (m *module) Name() infra.NameParts {+ return infra.NameParts{Module: "fakenet", 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("fakenet: no image; pass WithImage(ResolveImage(...))")+ }+ if m.caFile == "" {+ return nil, fmt.Errorf("fakenet: no CA; pass WithCAFile(...)")+ }++ // Only one container can hold the fixed address, so an older generation left+ // running makes this one fail to start. Removing it first turns a confusing+ // "address already in use" into an ordinary rebuild.+ if err := reapOtherGenerations(ctx, infra.ContainerName(m.Name())); err != nil {+ return nil, err+ }++ c, err := d.Run(ctx, infra.ContainerSpec{+ Image: m.image.Ref,+ Ports: []int{adminPort, httpsPort},+ IP: IP,+ Env: map[string]string{"FAKENET_IP": IP},+ Files: []infra.File{{Src: m.caFile, Dst: CAPath, Mode: 0o600}},+ Ready: infra.ForHTTP(AdminPrefix + "/health").WithPort("8080/tcp"),+ })+ if err != nil {+ return nil, err+ }+ return &Handle{c: c, caFile: m.caFile}, nil+}++// reapOtherGenerations removes fakenet containers other than the one about to start.+// Editing a fake changes the image id and therefore the container name, so without+// this every edit leaves its predecessor holding the address.+func reapOtherGenerations(ctx context.Context, keep string) error {+ out, err := exec.CommandContext(ctx, "docker", "ps", "-aq",+ "--filter", "label="+infra.LabelModule+"=fakenet").Output()+ if err != nil {+ return fmt.Errorf("fakenet: listing previous containers: %w", err)+ }+ for _, id := range strings.Fields(string(out)) {+ name, nErr := exec.CommandContext(ctx, "docker", "inspect", "-f", "{{.Name}}", id).Output()+ if nErr != nil {+ continue+ }+ if strings.TrimPrefix(strings.TrimSpace(string(name)), "/") == keep {+ continue+ }+ _ = exec.CommandContext(ctx, "docker", "rm", "-f", id).Run()+ }+ return nil+}++// Handle is a running fakenet.+type Handle struct {+ c infra.Container+ caFile string++ caOnce sync.Once+ caPEM []byte+ caErr error+}++func (h *Handle) Endpoint(m infra.Mode) infra.Endpoint { return h.c.Endpoint(m, adminPort) }+func (h *Handle) Stop(ctx context.Context) error { return h.c.Stop(ctx) }++// AdminURL is the control surface. Always External: the test process talks to it, and+// the application never can.+func (h *Handle) AdminURL() string { return h.Endpoint(infra.External).URL("http") }++// Resolver is what the application container gets as its DNS server.+func (h *Handle) Resolver() string { return IP }++// CAPEMFile is the host path of the CA the application must trust.+func (h *Handle) CAPEMFile() string { return h.caFile }++// VerifyCA checks the running container is serving the CA we hold, which an adopted+// container from a previous CA would not be.+func (h *Handle) VerifyCA(ctx context.Context) error {+ h.caOnce.Do(func() { h.caPEM, h.caErr = h.fetchCA(ctx) })+ if h.caErr != nil {+ return h.caErr+ }+ want, err := os.ReadFile(h.caFile)+ if err != nil {+ return err+ }+ if strings.TrimSpace(string(want)) == "" || !strings.Contains(string(want), strings.TrimSpace(string(h.caPEM))) {+ return fmt.Errorf("fakenet: the running container serves a different CA than %s.\n"++ "Run `make down` so the stack is rebuilt against one CA", h.caFile)+ }+ return nil+}++func (h *Handle) fetchCA(ctx context.Context) ([]byte, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.AdminURL()+AdminPrefix+"/ca", nil)+ if err != nil {+ return nil, err+ }+ res, err := http.DefaultClient.Do(req)+ if err != nil {+ return nil, fmt.Errorf("fakenet: fetching the CA: %w", err)+ }+ defer func() { _ = res.Body.Close() }()+ if res.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("fakenet: fetching the CA returned %d", res.StatusCode)+ }+ return io.ReadAll(res.Body)+}++func From(d infra.Deps) (*Handle, bool) { return d.Get[*Handle](Key) }++// Denied is every outbound call that reached no fake, newest last.+func (h *Handle) Denied(ctx context.Context) ([]Denied, error) {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, h.AdminURL()+AdminPrefix+"/denied", nil)+ if err != nil {+ return nil, err+ }+ res, err := http.DefaultClient.Do(req)+ if err != nil {+ return nil, err+ }+ defer func() { _ = res.Body.Close() }()++ var out []Denied+ if dErr := json.NewDecoder(res.Body).Decode(&out); dErr != nil {+ return nil, dErr+ }+ return out, nil+}diff --git a/tests/infra/names.go b/tests/infra/names.goindex 972b3ecb91..d95e78ed7b 100644--- a/tests/infra/names.go+++ b/tests/infra/names.go@@ -13,12 +13,15 @@ const Prefix = "inf"// Isolated suite can still reach the shared Mailpit. It holds no state.const NetworkName = Prefix + "-net"-// PackageNetwork is the network an Isolated package gets to itself.+// NetworkSubnet is fixed so fakenet can take a fixed address on it.//-// Its own, because a host alias belongs to the network: two WireMocks claiming-// api.github.com on one network make Docker DNS round-robin between them, so a stub-// registered on one is missed by a request that lands on the other.-func PackageNetwork(pkg string) string { return NetworkName + "-" + Sanitize(pkg) }+// Infisical is told which resolver to use when its container is created and is then+// adopted by later test binaries, so that address has to survive fakenet being+// rebuilt. Docker will not assign a fixed address on a network whose subnet it chose.+//+// Outside Docker's default 172.16-172.31 pools, so creating this network cannot+// collide with whatever else is already running on the machine.+const NetworkSubnet = "10.201.0.0/16"var unsafeNameChars = regexp.MustCompile(`[^a-zA-Z0-9_.-]+`)diff --git a/tests/infra/runner.go b/tests/infra/runner.goindex cffb8cfa45..fa1f38776d 100644--- a/tests/infra/runner.go+++ b/tests/infra/runner.go@@ -4,6 +4,7 @@ import ("context""fmt""io"+ "net/netip""os""os/exec""strconv"@@ -11,6 +12,8 @@ import ("sync""time"+ "github.com/moby/moby/api/types/container"+ dockernetwork "github.com/moby/moby/api/types/network""github.com/testcontainers/testcontainers-go"tcexec "github.com/testcontainers/testcontainers-go/exec""github.com/testcontainers/testcontainers-go/network"@@ -64,19 +67,29 @@ func NewRunner(workspace string, log Logger) Runner {// package network afterwards. testcontainers' network.New generates a random name per// process, which would give every test binary its own island.//-// Shelled out rather than using the Docker API, because importing the moby network-// types reintroduces an ambiguous import between github.com/moby/moby and-// github.com/moby/moby/api. This runs once per machine, so a subprocess is free.+// Shelled out rather than using the Docker API. This runs once per machine, so a+// subprocess is free, and it keeps network creation independent of testcontainers.+//+// The subnet is fixed because fakenet needs a fixed address on it. An existing+// network with a different subnet is refused rather than silently reused, since the+// symptom would otherwise be Docker rejecting fakenet's address much later.func (r *dockerRunner) Network(ctx context.Context, name string) error {if r.netName == name {return nil}- if err := exec.CommandContext(ctx, "docker", "network", "inspect", name).Run(); err == nil {+ if out, err := exec.CommandContext(ctx, "docker", "network", "inspect",+ "-f", "{{range .IPAM.Config}}{{.Subnet}}{{end}}", name).Output(); err == nil {+ if got := strings.TrimSpace(string(out)); got != NetworkSubnet {+ return fmt.Errorf("infra: network %s has subnet %q, want %s.\n"++ "fakenet needs a fixed address, which needs a known subnet.\n"++ "Run `make down` once to recreate the network", name, got, NetworkSubnet)+ }r.netName = namereturn nil}out, err := exec.CommandContext(ctx, "docker", "network", "create",+ "--subnet", NetworkSubnet,"--label", LabelScope+"=shared","--label", LabelWorkspace+"="+r.workspace,name,@@ -146,6 +159,36 @@ func (r *dockerRunner) Run(ctx context.Context, spec ContainerSpec) (Container,}aliases := append([]string{alias}, spec.Aliases...)opts = append(opts, network.WithNetworkName(aliases, net))++ if spec.IP != "" {+ addr, err := netip.ParseAddr(spec.IP)+ if err != nil {+ return Container{}, fmt.Errorf("infra: %s has an unparseable IP %q: %w", spec.Name, spec.IP, err)+ }+ netName := net+ opts = append(opts, testcontainers.WithEndpointSettingsModifier(+ func(settings map[string]*dockernetwork.EndpointSettings) {+ s, ok := settings[netName]+ if !ok {+ s = &dockernetwork.EndpointSettings{}+ settings[netName] = s+ }+ s.IPAMConfig = &dockernetwork.EndpointIPAMConfig{IPv4Address: addr}+ }))+ }+ }+ if len(spec.DNS) > 0 {+ resolvers := make([]netip.Addr, 0, len(spec.DNS))+ for _, d := range spec.DNS {+ addr, err := netip.ParseAddr(d)+ if err != nil {+ return Container{}, fmt.Errorf("infra: %s has an unparseable DNS address %q: %w", spec.Name, d, err)+ }+ resolvers = append(resolvers, addr)+ }+ opts = append(opts, testcontainers.WithHostConfigModifier(func(hc *container.HostConfig) {+ hc.DNS = resolvers+ }))}for _, f := range spec.Files {mode := f.Modediff --git a/tests/infra/stack_test.go b/tests/infra/stack_test.goindex 66c7f7544e..ed49f5805d 100644--- a/tests/infra/stack_test.go+++ b/tests/infra/stack_test.go@@ -8,7 +8,6 @@ import ("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""github.com/Infisical/infisical/tests/internal/spec")@@ -61,7 +60,6 @@ func TestStack_AllModulesComeUpTogether(t *testing.T) {postgres.Module(),redis.Module(),mailpit.Module(),- wiremock.Module(),}, infra.Shared)t.Run("ok/every module reports a usable external address", func(t *testing.T) {@@ -88,10 +86,4 @@ func TestStack_AllModulesComeUpTogether(t *testing.T) {}})- t.Run("ok/wiremock serves its admin API", func(t *testing.T) {- wm := handles[wiremock.Key].(*wiremock.Handle)- if got := wm.AdminURL(infra.External); got == "" {- t.Fatal("no admin URL")- }- })}diff --git a/tests/infra/wiremock/client.go b/tests/infra/wiremock/client.godeleted file mode 100644index 4bd843e8be..0000000000--- a/tests/infra/wiremock/client.go+++ /dev/null@@ -1,236 +0,0 @@-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-- // URLAnyPattern matches the whole URL including the query, where URLRe matches- // the path only. Needed for a catch-all, which cannot know the path.- URLAnyPattern string-- Headers map[string]Matcher- Query map[string]Matcher- Status int- JSONBody any- Body string- Priority int- Metadata map[string]string-- // Transformers are WireMock response transformers. "response-template" lets Body- // interpolate the request, which is how a rejection can name what it rejected.- Transformers []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.URLAnyPattern != "":- req["urlPattern"] = s.URLAnyPattern- 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"}- }- if s.Body != "" {- resp["body"] = s.Body- }- if len(s.Transformers) > 0 {- resp["transformers"] = s.Transformers- }-- 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)) }--// PriorityDenyAll is below every stub a test registers, so the catch-all only wins-// when nothing else matched. WireMock reads a lower number as higher priority.-const PriorityDenyAll = 100--// MetadataDenyAll tags the catch-all, so the journal can be asked what went-// unstubbed.-const MetadataDenyAll = "harness-deny-all"--// DenyUnstubbed makes an outbound call nothing stubbed fail loudly.-//-// Browser proxying forwards anything it has no mapping for to the real host, so-// without this the suite silently reaches the internet: a test that forgets a stub-// passes against the live API, and a container phones home at boot. Neither is-// acceptable in a suite that has to be hermetic and parallel.-//-// 501 rather than a connection error, because a refused connection reads to the-// application as a network blip and is often retried.-func (c *Client) DenyUnstubbed(ctx context.Context) error {- _, err := c.Register(ctx, Stub{- Method: "ANY",- URLAnyPattern: ".*",- Status: http.StatusNotImplemented,- // Composed from the parts rather than {{request.absoluteUrl}}, which renders- // empty for a proxied request even though the journal records it correctly.- Body: "The harness has no stub for {{request.method}} " +- "{{request.scheme}}://{{request.host}}{{request.url}}\n" +- "Register one with conn.Stub(t), or add the host to the provider registry.\n",- Transformers: []string{"response-template"},- Priority: PriorityDenyAll,- Metadata: map[string]string{"harness": MetadataDenyAll},- })- return err-}--// Unstubbed returns the outbound calls that reached the catch-all, newest first.-//-// What to print when a test fails having forgotten a stub: the journal knows the-// exact URL, and the application's own error rarely carries it.-func (c *Client) Unstubbed(ctx context.Context) ([]string, error) {- var out struct {- Requests []struct {- Request struct {- Method string `json:"method"`- AbsoluteURL string `json:"absoluteUrl"`- } `json:"request"`- StubMapping struct {- Metadata map[string]string `json:"metadata"`- } `json:"stubMapping"`- } `json:"requests"`- }- if err := c.do(ctx, http.MethodGet, "/requests?limit=200", nil, &out); err != nil {- return nil, err- }-- var calls []string- for _, r := range out.Requests {- if r.StubMapping.Metadata["harness"] == MetadataDenyAll {- calls = append(calls, r.Request.Method+" "+r.Request.AbsoluteURL)- }- }- return calls, nil-}diff --git a/tests/infra/wiremock/wiremock.go b/tests/infra/wiremock/wiremock.godeleted file mode 100644index 5cdb8278f0..0000000000--- a/tests/infra/wiremock/wiremock.go+++ /dev/null@@ -1,176 +0,0 @@-// Package wiremock runs a WireMock container in browser-proxying mode.-//-// It intercepts at the network boundary rather than inside the process, which is the-// point: a Go reimplementation of the API inherits it unchanged, unlike the in-app-// nock control API the Python BDD suite uses.-package wiremock--import (- "context"- "fmt"- "io"- "net/http"- "os"- "sync"-- "github.com/Infisical/infisical/tests/infra"-)--const (- Key = infra.Key("wiremock")-- port = 8080-- // CAPath is where the harness places WireMock's CA inside the application- // container, for NODE_EXTRA_CA_CERTS.- CAPath = "/wiremock-ca.pem"-)--type module struct {- image string- aliases []string- flags []string-}--type Option func(*module)--func WithImage(img string) Option { return func(m *module) { m.image = img } }--// WithHostAliases resolves the given hostnames to WireMock over Docker DNS.-//-// The escape hatch for clients that ignore HTTP_PROXY, which is most cloud SDKs.-// Aliases are fixed at container start, so under a Shared profile this list is-// run-wide; a package needing a private alias has to take its own stack.-func WithHostAliases(hosts ...string) Option {- return func(m *module) { m.aliases = append(m.aliases, hosts...) }-}--func WithFlags(flags ...string) Option {- return func(m *module) { m.flags = append(m.flags, flags...) }-}--func Module(opts ...Option) infra.Module {- m := &module{- image: "wiremock/wiremock:3.13.1",- flags: []string{- "--enable-browser-proxying",- "--trust-all-proxy-targets",- // The journal is global and unbounded by default. Every query filters by- // tenant, and resetRequests must never be called, so the only bound is- // this cap.- "--max-request-journal-entries", "20000",- },- }- for _, o := range opts {- o(m)- }- return m-}--func (m *module) Key() infra.Key { return Key }-func (m *module) Requires() []infra.Key { return nil }-func (m *module) Optional() []infra.Key { return nil }-func (m *module) Name() infra.NameParts { return infra.NameParts{Module: "wiremock"} }--func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error) {- c, err := d.Run(ctx, infra.ContainerSpec{- Image: m.image,- Command: m.flags,- Ports: []int{port},- Aliases: m.aliases,- Ready: infra.ForHTTP("/__admin/mappings").WithPort("8080/tcp"),- })- if err != nil {- return nil, err- }-- h := &Handle{c: c}-- // Here rather than in the caller, so nothing can slip out before it. WireMock- // starts before anything that would make an outbound call, and a container that- // boots against an unguarded proxy reaches the real internet in the meantime --- // which is what happened while this lived in harness.bringUp.- if err := h.NewAdminClient().DenyUnstubbed(ctx); err != nil {- return nil, err- }- return h, nil-}--// Handle is a running WireMock.-type Handle struct {- c infra.Container-- caOnce sync.Once- caPath string- caErr error-}--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) }--// AdminURL is where stubs are registered and the journal is queried. External: the-// Go test process talks to it.-func (h *Handle) AdminURL(m infra.Mode) string {- return h.Endpoint(m).URL("http") + "/__admin"-}--// ProxyURL is what the application container gets as HTTP_PROXY. Internal: a-// container talks to it.-func (h *Handle) ProxyURL(m infra.Mode) string {- return h.Endpoint(m).URL("http")-}--// CAFile writes WireMock's CA to a host file and returns the path.-//-// Browser proxying terminates TLS with a certificate this CA signs, so without it in-// the application's trust store every HTTPS call through the proxy fails-// verification. Only HTTP would work, and every real provider is HTTPS.-//-// Fetched from the live container rather than generated, because WireMock mints its-// CA at startup: an adopted container has the CA of whoever created it.-func (h *Handle) CAFile(ctx context.Context) (string, error) {- h.caOnce.Do(func() { h.caPath, h.caErr = h.fetchCA(ctx) })- return h.caPath, h.caErr-}--func (h *Handle) fetchCA(ctx context.Context) (string, error) {- url := h.AdminURL(infra.External) + "/certs/wiremock-ca.crt"- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)- if err != nil {- return "", err- }- res, err := http.DefaultClient.Do(req)- if err != nil {- return "", fmt.Errorf("wiremock: fetching the CA: %w", err)- }- defer res.Body.Close()- if res.StatusCode != http.StatusOK {- return "", fmt.Errorf("wiremock: fetching the CA returned %d", res.StatusCode)- }- pem, err := io.ReadAll(res.Body)- if err != nil {- return "", fmt.Errorf("wiremock: reading the CA: %w", err)- }-- f, err := os.CreateTemp("", "wiremock-ca-*.pem")- if err != nil {- return "", err- }- defer f.Close()- if _, err := f.Write(pem); err != nil {- return "", err- }- return f.Name(), nil-}--// NoProxy keeps traffic to the harness's own containers off the proxy. Without it,-// Infisical would try to reach Postgres through WireMock.-func NoProxy(hosts ...string) string {- out := "localhost,127.0.0.1"- for _, h := range hosts {- out += "," + h- }- return out-}--func From(d infra.Deps) (*Handle, bool) { return d.Get[*Handle](Key) }diff --git a/tests/provider/provider.go b/tests/provider/provider.goindex a0396fc0c2..fe8c9cf28a 100644--- a/tests/provider/provider.go+++ b/tests/provider/provider.go@@ -1,10 +1,10 @@// Package provider is what the harness knows about the third parties Infisical// calls out to.//-// One entry per service, added when a suite first needs it. The point of the-// registry is that a test says "GitHub" and gets the hostname, the credential-// shape, the auth header to discriminate on and the calls that have to be stubbed-// before a connection can even be created -- none of which belong in a test file.+// One entry per service, added when a suite first needs it. It carries only what+// creating a connection needs: the app slug, the hostname the client hardcodes, and+// the call itself. How the service behaves once reached belongs to its fake under+// fakes/, not here.package providerimport (@@ -14,7 +14,6 @@ import ("fmt""github.com/Infisical/infisical/tests/clients/api"- "github.com/Infisical/infisical/tests/infra/wiremock""github.com/google/uuid")@@ -23,23 +22,12 @@ type Provider struct {// App is the name in errors and the /api/v1/app-connections/<app> segment.App string- // Host is what the provider's client has hardcoded. It has to be hardcoded for- // the test to mean anything: a configurable base URL could be pointed straight- // at WireMock, which would prove the stub works and nothing about interception.+ // Host is what the provider's client has hardcoded, and is the key its fake is+ // registered under. It has to be hardcoded for the test to mean anything: a+ // configurable base URL could be pointed straight at fakenet, which would prove+ // the fake works and nothing about interception.Host string- // Auth turns a connection's credential into request matchers that identify it.- //- // This is the discriminator. Two tenants stubbing the same method and path at- // the same time are told apart by the credential the application sends, which- // is unique per connection, so neither sees the other's requests. No org id has- // to be threaded anywhere -- the application already proves who it is.- Auth func(nonce string) map[string]wiremock.Matcher-- // Validate is what must be stubbed before a connection can be created, because- // creating one calls the live API to check the credentials.- Validate func(nonce string) []wiremock.Stub-// Create makes the connection through the generated client.Create func(ctx context.Context, c *api.ClientWithResponses, name, nonce string) (uuid.UUID, error)}@@ -54,29 +42,10 @@ var GitHub = Provider{App: "github",Host: "api.github.com",- Auth: func(nonce string) map[string]wiremock.Matcher {- return map[string]wiremock.Matcher{"Authorization": wiremock.EqualTo("Bearer " + nonce)}- },-- // GET /user, which validateGitHubConnectionCredentials calls for the PAT method.- // Nothing parses the body, but a realistic one keeps the stub honest if a later- // caller starts reading it.- Validate: func(string) []wiremock.Stub {- return []wiremock.Stub{{- Method: "GET",- URLPath: "/user",- JSONBody: map[string]any{- "login": "harness",- "id": 1,- "type": "User",- },- }}- },-Create: func(ctx context.Context, c *api.ClientWithResponses, name, nonce string) (uuid.UUID, error) {// Host and instanceType are both left unset, which is what pins the call to- // api.github.com. Setting host would let the request reach WireMock without- // the proxy, and the test would prove nothing about interception.+ // api.github.com. Setting host would point the client straight at fakenet,+ // and the test would prove nothing about interception.var creds api.CreateGitHubAppConnectionJSONBody_2_Credentialsif err := creds.FromCreateGitHubAppConnectionJSONBody2Credentials1(api.CreateGitHubAppConnectionJSONBody2Credentials1{PersonalAccessToken: nonce}); err != nil {diff --git a/tests/stub/stub.go b/tests/stub/stub.godeleted file mode 100644index a6757675f6..0000000000--- a/tests/stub/stub.go+++ /dev/null@@ -1,106 +0,0 @@-// Package stub registers WireMock mappings that can only match one caller.-//-// One WireMock serves the whole run, so isolation is by discriminator rather than-// by server: a scope carries request matchers that identify whoever owns it, every-// stub it registers inherits them, and every journal query filters on them. Two-// parallel tests stubbing the same method and path cannot see each other, and that-// is enforced when the stub is built rather than detected afterwards.-package stub--import (- "context"- "testing"-- "github.com/Infisical/infisical/tests/infra/wiremock"-)--// Scope registers stubs for one owner and counts what it received.-type Scope struct {- client *wiremock.Client-- // match identifies the owner. Applied to every stub and every journal query.- match map[string]wiremock.Matcher-- // tag groups this scope's mappings so cleanup removes only them.- tag string-}--// New returns a scope. match must identify the owner and nothing else; an empty one-// would produce stubs that answer every tenant's requests.-func New(tt *testing.T, c *wiremock.Client, match map[string]wiremock.Matcher, tag string) *Scope {- tt.Helper()- if len(match) == 0 {- tt.Fatal("stub: a scope needs a discriminator.\n" +- "Without one its stubs would match every tenant's requests and the journal " +- "counts would include other tests' calls.")- }- return &Scope{client: c, match: match, tag: tag}-}--// Remove deletes this scope's mappings, leaving everyone else's alone.-func (s *Scope) Remove(ctx context.Context) error {- return s.client.RemoveByMetadata(ctx, "scope", s.tag)-}--// On starts a stub for a call the owner will make.-func (s *Scope) On(tt *testing.T, method, path string) *Builder {- tt.Helper()- return &Builder{scope: s, stub: wiremock.Stub{Method: method, URLPath: path}}-}--// Received counts the owner's requests to a method and path.-func (s *Scope) Received(tt *testing.T, method, path string) int {- tt.Helper()-- n, err := s.client.Requests(tt.Context(), map[string]any{- "method": method,- "urlPath": path,- "headers": s.match,- })- if err != nil {- tt.Fatalf("stub: reading the request journal: %v", err)- }- return n-}--// Register applies the discriminator and the scope tag, then installs the mapping.-func (s *Scope) Register(tt *testing.T, st wiremock.Stub) {- tt.Helper()-- headers := make(map[string]wiremock.Matcher, len(s.match)+len(st.Headers))- for k, v := range s.match {- headers[k] = v- }- for k, v := range st.Headers {- headers[k] = v- }- st.Headers = headers- st.Metadata = map[string]string{"scope": s.tag}-- if _, err := s.client.Register(tt.Context(), st); err != nil {- tt.Fatalf("stub: registering %s %s: %v", st.Method, st.URLPath, err)- }-}--// Builder finishes a stub started by On.-type Builder struct {- scope *Scope- stub wiremock.Stub-}--// Query narrows the stub to requests carrying a query parameter.-func (b *Builder) Query(name, value string) *Builder {- if b.stub.Query == nil {- b.stub.Query = map[string]wiremock.Matcher{}- }- b.stub.Query[name] = wiremock.EqualTo(value)- return b-}--// Return registers the stub with a status and an optional JSON body.-func (b *Builder) Return(tt *testing.T, status int, body any) {- tt.Helper()- b.stub.Status = status- b.stub.JSONBody = body- b.scope.Register(tt, b.stub)-}