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 mailhog container to smtp in fakenet
=78cd157ff964
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdindex e666291907..1704a1a15e 100644--- a/tests/CLAUDE.md+++ b/tests/CLAUDE.md@@ -270,11 +270,11 @@ has one, they have stopped meaning anything.h := harness.From(t) // the stack this package's TestMain builttn := h.NewTenant(t) // fresh organization with its own admintn.Admin // *Principal: .API, .Token, .Email, .Kind, .ID-tn.Address("alice") // alice@<orgslug>.test+tn.Address("alice") // alice@<tenant-nonce>.test-tn.NewUser(t, harness.WithName("alice")) // real user, invited through Mailpit+tn.NewUser(t, harness.WithName("alice")) // real user, invited through mailtn.NewIdentity(t, harness.OrgRole("admin")) // machine identity-tn.Mail(t) // Mailpit scoped to this tenant+tn.Mail(t).Expect(t, addr, smtp.Subject("x")) // waits on this tenant's mailtn.SetPlan(t, license.Enterprise().Without(license.RBAC))tn.Client(t, token) // a client on this tenant's bucket@@ -362,6 +362,10 @@ gh.ExpectNoEvent[github.SecretCreated](t, nil) // waits 3s by defaultafter an async action passes before the action lands; the auto-sync-off test didexactly that and could not fail.+Mail works the same way: the SMTP fake publishes `smtp.message-received` once per+recipient, scoped to the tenant's mail domain. `tn.Mail(t).Expect` covers the usual+case; `tn.Mail(t).ExpectNoEvent[smtp.MessageReceived]` asserts nothing was sent.+Waiting on Infisical itself, such as a sync's status, still polls its API, since thatis where the product reports its own errors.@@ -485,7 +489,7 @@ branch, rather than letting an approval request read as success.`GET api.github.com/user -> 200 scope=7116dd6caf34...`. It answers "did the call happenat all, and under which credential" before anything else.3. **`GET /__fake/denied`** on fakenet's admin port lists calls that reached no fake.-4. **Mailpit UI** on its mapped port, for anything email.+4. **`GET /__fake/events`** on fakenet's admin port streams every event, mail included.5. **`make status`** lists harness containers.If an outbound call is refused, the host has no fake: register its `Service` indiff --git a/tests/cmd/fakenet/Dockerfile b/tests/cmd/fakenet/Dockerfileindex 228599cf75..91244eb6cf 100644--- a/tests/cmd/fakenet/Dockerfile+++ b/tests/cmd/fakenet/Dockerfile@@ -3,5 +3,5 @@# second where an in-Docker build would download the whole module graph.FROM scratchCOPY fakenet /fakenet-EXPOSE 53/udp 443 8080+EXPOSE 25 53/udp 443 8080ENTRYPOINT ["/fakenet"]diff --git a/tests/cmd/fakenet/main.go b/tests/cmd/fakenet/main.goindex 0ff058d3c8..6c64252788 100644--- a/tests/cmd/fakenet/main.go+++ b/tests/cmd/fakenet/main.go@@ -1,7 +1,8 @@// Command fakenet serves the harness's fakes.//-// Three listeners, and each exists for a different reason:+// Four listeners, and each exists for a different reason://+// 25 SMTP, where Infisical delivers mail// 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@@ -14,6 +15,7 @@ import ("github.com/Infisical/infisical/tests/fakes/github""github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fakes/smtp""github.com/Infisical/infisical/tests/infra/fakenet")@@ -33,6 +35,11 @@ func main() {license.Service,)+ mail := smtp.New(func(domain string) fakenet.Emitter { return srv.Emitter(smtp.Host, domain) })+ if err := mail.Start(); err != nil {+ log.Fatalf("fakenet: smtp listener: %v", err)+ }+go func() { log.Fatalf("fakenet: %v", fakenet.ServeDNS(":53", selfIP)) }()go func() {diff --git a/tests/fakes/smtp/handle.go b/tests/fakes/smtp/handle.gonew file mode 100644index 0000000000..f256bf3008--- /dev/null+++ b/tests/fakes/smtp/handle.go@@ -0,0 +1,57 @@+package smtp++import (+ "strings"+ "testing"++ "github.com/Infisical/infisical/tests/infra/fakenet"+)++// Inbox is one mail domain's messages, as events. ExpectEvent and ExpectNoEvent on+// MessageReceived are there for anything Expect does not cover.+type Inbox struct {+ *fakenet.Events+ domain string+}++// Track starts collecting a domain's mail. Call it before Infisical can send there,+// the same way a credential is tracked before it is handed over.+func Track(tt *testing.T, adminURL, domain string) {+ tt.Helper()+ fakenet.Track(tt, adminURL, Host, domain)+}++func Open(adminURL, domain string) *Inbox {+ return &Inbox{Events: fakenet.OpenEvents(adminURL, Host, domain), domain: domain}+}++// Filter narrows what Expect accepts.+type Filter func(Message) bool++// Subject accepts a message whose subject contains s.+func Subject(s string) Filter {+ return func(m Message) bool { return strings.Contains(m.Subject, s) }+}++// Expect waits for an unclaimed message to addr that every filter accepts, and claims+// it.+func (in *Inbox) Expect(tt *testing.T, addr string, filters ...Filter) Message {+ tt.Helper()+ addr = strings.ToLower(addr)+ if !strings.HasSuffix(addr, "@"+in.domain) {+ tt.Fatalf("smtp: this inbox is scoped to @%s but was asked for %s.\n"++ "Reading another tenant's mail would make the test order-dependent; use tn.Address(local)",+ in.domain, addr)+ }+ return in.ExpectEvent[MessageReceived](tt, func(e MessageReceived) bool {+ if e.Recipient != addr {+ return false+ }+ for _, f := range filters {+ if !f(e.Message) {+ return false+ }+ }+ return true+ }).Message+}diff --git a/tests/fakes/smtp/parse.go b/tests/fakes/smtp/parse.gonew file mode 100644index 0000000000..277131c331--- /dev/null+++ b/tests/fakes/smtp/parse.go@@ -0,0 +1,107 @@+package smtp++import (+ "bytes"+ "encoding/base64"+ "io"+ "mime"+ "mime/multipart"+ "mime/quotedprintable"+ "net/mail"+ "strings"++ smtpmock "github.com/mocktools/go-smtp-mock/v2"+)++func parse(raw smtpmock.Message) Message {+ m := Message{From: envelopeAddr(raw.MailfromRequest())}+ for _, pair := range raw.RcpttoRequestResponse() {+ if len(pair) == 2 && strings.HasPrefix(pair[1], "250") {+ m.To = append(m.To, strings.ToLower(envelopeAddr(pair[0])))+ }+ }++ msg, err := mail.ReadMessage(strings.NewReader(raw.MsgRequest()))+ if err != nil {+ m.ParseError = err.Error()+ m.Body = raw.MsgRequest()+ return m+ }++ dec := new(mime.WordDecoder)+ if subject, dErr := dec.DecodeHeader(msg.Header.Get("Subject")); dErr == nil {+ m.Subject = subject+ } else {+ m.Subject = msg.Header.Get("Subject")+ }++ var parts []string+ if err := collectText(msg.Header.Get("Content-Type"), msg.Header.Get("Content-Transfer-Encoding"), msg.Body, &parts); err != nil {+ m.ParseError = err.Error()+ }+ m.Body = strings.Join(parts, "\n")+ return m+}++// envelopeAddr pulls the address out of "MAIL FROM:<a@b>" or "RCPT TO:<a@b>".+func envelopeAddr(cmd string) string {+ start, end := strings.IndexByte(cmd, '<'), strings.LastIndexByte(cmd, '>')+ if start < 0 || end <= start {+ return ""+ }+ return cmd[start+1 : end]+}++func collectText(contentType, encoding string, body io.Reader, into *[]string) error {+ mediaType, params, err := mime.ParseMediaType(contentType)+ if err != nil {+ mediaType = "text/plain"+ }++ if strings.HasPrefix(mediaType, "multipart/") {+ mr := multipart.NewReader(body, params["boundary"])+ for {+ part, pErr := mr.NextRawPart()+ if pErr == io.EOF {+ return nil+ }+ if pErr != nil {+ return pErr+ }+ if cErr := collectText(part.Header.Get("Content-Type"), part.Header.Get("Content-Transfer-Encoding"), part, into); cErr != nil {+ return cErr+ }+ }+ }++ if !strings.HasPrefix(mediaType, "text/") {+ return nil+ }+ decoded, err := io.ReadAll(decode(encoding, body))+ if err != nil {+ return err+ }+ *into = append(*into, string(decoded))+ return nil+}++func decode(encoding string, body io.Reader) io.Reader {+ switch strings.ToLower(strings.TrimSpace(encoding)) {+ case "quoted-printable":+ return quotedprintable.NewReader(body)+ case "base64":+ raw, _ := io.ReadAll(body)+ return base64.NewDecoder(base64.StdEncoding, bytes.NewReader(stripWhitespace(raw)))+ default:+ return body+ }+}++func stripWhitespace(b []byte) []byte {+ return bytes.Map(func(r rune) rune {+ if r == '\r' || r == '\n' || r == ' ' || r == '\t' {+ return -1+ }+ return r+ }, b)+}diff --git a/tests/fakes/smtp/smtp.go b/tests/fakes/smtp/smtp.gonew file mode 100644index 0000000000..2bc440a146--- /dev/null+++ b/tests/fakes/smtp/smtp.go@@ -0,0 +1,102 @@+// Package smtp is the mail server Infisical sends to, run inside fakenet.+//+// smtpmock speaks the protocol and keeps raw transcripts; this package parses each one+// and publishes it as a MessageReceived event, scoped to the recipient's domain. Each+// tenant mails within its own domain, so tenants never see each other's mail.+package smtp++import (+ "log"+ "strings"+ "time"++ "github.com/Infisical/infisical/tests/infra/fakenet"+ smtpmock "github.com/mocktools/go-smtp-mock/v2"+)++// Port is where Infisical delivers.+const Port = 25++// Host is the event host every mail event is published under.+const Host = "smtp"++// Message is a delivered mail, parsed.+type Message struct {+ From string `json:"from"`+ To []string `json:"to"`+ Subject string `json:"subject"`++ // Body is the plain text and HTML parts joined. Callers search it for a link or a+ // code rather than caring which part carried it.+ Body string `json:"body"`++ // ParseError is set when the transcript could not be read as MIME. The message is+ // still published, so a test fails on the content rather than on a missing mail.+ ParseError string `json:"parseError,omitempty"`+}++// MessageReceived is published once per recipient, so a message to two addresses+// satisfies an expectation for each.+type MessageReceived struct {+ Recipient string `json:"recipient"`+ Message Message `json:"message"`+}++func (MessageReceived) EventName() string { return "smtp.message-received" }++// EmitterFor returns the emitter for one recipient domain.+type EmitterFor func(domain string) fakenet.Emitter++type Server struct {+ mock *smtpmock.Server+ emitter EmitterFor+}++func New(emitter EmitterFor) *Server { return newServer(Port, emitter) }++func newServer(port int, emitter EmitterFor) *Server {+ return &Server{+ mock: smtpmock.New(smtpmock.ConfigurationAttr{+ HostAddress: "0.0.0.0",+ PortNumber: port,+ // nodemailer reuses a connection for several messages and sends one+ // message to several recipients.+ MultipleRcptto: true,+ MultipleMessageReceiving: true,+ }),+ emitter: emitter,+ }+}++// Start listens and publishes each message as it completes.+func (s *Server) Start() error {+ if err := s.mock.Start(); err != nil {+ return err+ }+ go s.publishLoop()+ return nil+}++func (s *Server) Stop() error { return s.mock.Stop() }++// publishLoop polls because smtpmock has no delivery hook. MessagesAndPurge rather+// than WaitForMessagesAndPurge: the latter copies and clears under separate locks, so+// a message landing in between is lost.+func (s *Server) publishLoop() {+ for range time.Tick(20 * time.Millisecond) {+ for _, raw := range s.mock.MessagesAndPurge() {+ if !raw.IsConsistent() {+ log.Printf("smtp: dropping an incomplete transaction from %s", raw.MailfromRequest())+ continue+ }+ m := parse(raw)+ for _, rcpt := range m.To {+ _, domain, ok := strings.Cut(rcpt, "@")+ if !ok {+ continue+ }+ s.emitter(domain).Publish(MessageReceived{Recipient: rcpt, Message: m})+ }+ }+ }+}diff --git a/tests/fakes/smtp/smtp_test.go b/tests/fakes/smtp/smtp_test.gonew file mode 100644index 0000000000..7ba6188dba--- /dev/null+++ b/tests/fakes/smtp/smtp_test.go@@ -0,0 +1,142 @@+package smtp++import (+ "context"+ "fmt"+ "net/http/httptest"+ "net/smtp"+ "path/filepath"+ "testing"++ "github.com/Infisical/infisical/tests/infra/fakenet"+ "github.com/stretchr/testify/require"+)++// Shaped like nodemailer's output: multipart/alternative, quoted-printable, an+// encoded subject, and a soft line break through the middle of the invite link.+const nodemailerShaped = "From: Infisical Harness <[email protected]>\r\n" ++ "To: [email protected]\r\n" ++ "Subject: =?UTF-8?Q?Infisical_organization_invitation?=\r\n" ++ "MIME-Version: 1.0\r\n" ++ "Content-Type: multipart/alternative; boundary=\"--_b1\"\r\n" ++ "\r\n" ++ "----_b1\r\n" ++ "Content-Type: text/plain; charset=utf-8\r\n" ++ "Content-Transfer-Encoding: quoted-printable\r\n" ++ "\r\n" ++ "Join: http://localhost:8080/signupinvite?token=3Dabc123&to=3Dalice%40acme.=\r\n" ++ "test\r\n" ++ "----_b1\r\n" ++ "Content-Type: text/html; charset=utf-8\r\n" ++ "Content-Transfer-Encoding: base64\r\n" ++ "\r\n" ++ "PGEgaHJlZj0iaHR0cDovL2V4YW1wbGUudGVzdCI+QWNjZXB0PC9hPg==\r\n" ++ "----_b1--\r\n"++type rig struct {+ smtpAddr string+ adminURL string+}++// newRig runs the SMTP fake against a real fakenet event log and opens this test's+// event stream, as fakenet and harness.Main do.+func newRig(t *testing.T) *rig {+ t.Helper()+ srv := fakenet.New()+ ca, err := fakenet.LoadOrCreateCA(filepath.Join(t.TempDir(), "ca.pem"))+ require.NoError(t, err)+ admin := httptest.NewServer(srv.Admin(ca))+ t.Cleanup(admin.Close)++ mail := newServer(0, func(domain string) fakenet.Emitter { return srv.Emitter(Host, domain) })+ require.NoError(t, mail.Start())+ t.Cleanup(func() { _ = mail.Stop() })++ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)+ require.NoError(t, fakenet.Listen(ctx, admin.URL, ""))++ return &rig{smtpAddr: fmt.Sprintf("127.0.0.1:%d", mail.mock.PortNumber()), adminURL: admin.URL}+}++func (r *rig) inbox(t *testing.T, domain string) *Inbox {+ t.Helper()+ Track(t, r.adminURL, domain)+ return Open(r.adminURL, domain)+}++func (r *rig) send(t *testing.T, to []string, msg string) {+ t.Helper()+ require.NoError(t, smtp.SendMail(r.smtpAddr, nil, "[email protected]", to, []byte(msg)))+}++func TestInbox_Expect(t *testing.T) {+ t.Run("should decode a nodemailer-shaped message for its recipient", func(t *testing.T) {+ // Setup+ r := newRig(t)+ in := r.inbox(t, "acme.test")++ // Action+ r.send(t, []string{"[email protected]"}, nodemailerShaped)++ // Assert+ got := in.Expect(t, "[email protected]", Subject("invitation"))+ require.Empty(t, got.ParseError)+ require.Equal(t, "[email protected]", got.From)+ require.Equal(t, "Infisical organization invitation", got.Subject)+ require.Contains(t, got.Body, "token=abc123&to=alice%40acme.test", "quoted-printable was not decoded")+ require.Contains(t, got.Body, `<a href="http://example.test">Accept</a>`, "base64 was not decoded")+ })++ t.Run("should not deliver one domain's mail to another domain's inbox", func(t *testing.T) {+ // Setup+ r := newRig(t)+ one, two := r.inbox(t, "one.test"), r.inbox(t, "two.test")++ // Action+ r.send(t, []string{"[email protected]"}, "Subject: for one\r\n\r\nbody\r\n")++ // Assert+ one.Expect(t, "[email protected]")+ two.ExpectNoEvent[MessageReceived](t, nil)+ })++ t.Run("should match the recipient regardless of case", func(t *testing.T) {+ // Setup+ r := newRig(t)+ in := r.inbox(t, "acme.test")++ // Action+ r.send(t, []string{"[email protected]"}, "Subject: hi\r\n\r\nbody\r\n")++ // Assert+ in.Expect(t, "[email protected]")+ })++ t.Run("should satisfy one expectation per recipient when a message goes to several", func(t *testing.T) {+ // Setup+ r := newRig(t)+ in := r.inbox(t, "x.test")++ // Action+ r.send(t, []string{"[email protected]", "[email protected]"}, "Subject: both\r\n\r\nbody\r\n")++ // Assert+ require.Contains(t, in.Expect(t, "[email protected]").Body, "body")+ require.Contains(t, in.Expect(t, "[email protected]").Body, "body")+ })++ t.Run("should claim each message once", func(t *testing.T) {+ // Setup+ r := newRig(t)+ in := r.inbox(t, "acme.test")+ r.send(t, []string{"[email protected]"}, "Subject: first\r\n\r\nbody\r\n")+ in.Expect(t, "[email protected]")++ // Action+ r.send(t, []string{"[email protected]"}, "Subject: second\r\n\r\nbody\r\n")++ // Assert+ require.Equal(t, "second", in.Expect(t, "[email protected]").Subject)+ })+}diff --git a/tests/fixture/project.go b/tests/fixture/project.goindex c66339b1f7..f8e99b16a7 100644--- a/tests/fixture/project.go+++ b/tests/fixture/project.go@@ -77,7 +77,7 @@ type principalConfig struct {roles []string}-// WithPrincipalName also picks a user's mailbox: alice means alice@<orgslug>.test.+// WithPrincipalName also picks a user's mailbox: alice means alice@<tenant-nonce>.test.func WithPrincipalName(n string) PrincipalOption {return func(c *principalConfig) { c.name = n }}diff --git a/tests/go.mod b/tests/go.modindex 4c84cc2146..74dea0cd58 100644--- a/tests/go.mod+++ b/tests/go.mod@@ -5,6 +5,7 @@ go 1.27.0require (github.com/google/uuid v1.6.0github.com/moby/moby/api v1.55.0+ github.com/mocktools/go-smtp-mock/v2 v2.5.4github.com/oapi-codegen/runtime v1.7.0github.com/stretchr/testify v1.11.1github.com/testcontainers/testcontainers-go v0.44.0diff --git a/tests/go.sum b/tests/go.sumindex 3bb2485b85..c5e811bac4 100644--- a/tests/go.sum+++ b/tests/go.sum@@ -122,6 +122,8 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/ggithub.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=github.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/mocktools/go-smtp-mock/v2 v2.5.4 h1:U89Y4SuOhDFUfboMYUtXzWDp7hNLrofRa5yNqGSESSM=+github.com/mocktools/go-smtp-mock/v2 v2.5.4/go.mod h1:qBGjYXy5jKKVFhDnB39DYQfn4hWfcqWAlJTcvrku3rg=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=diff --git a/tests/harness/infisical/infisical.go b/tests/harness/infisical/infisical.goindex 6b3922dbb1..b73d4fc7c2 100644--- a/tests/harness/infisical/infisical.go+++ b/tests/harness/infisical/infisical.go@@ -10,9 +10,9 @@ import ("fmt""github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fakes/smtp""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")@@ -70,10 +70,10 @@ func (m *module) Key() infra.Key { return Key }// fail at connect time rather than parse time if absent.func (m *module) Requires() []infra.Key { return []infra.Key{postgres.Key, redis.Key} }-// Optional is consumed if declared. SMTP is what makes user creation possible at-// all; fakenet is what makes outbound calls and entitlements controllable.+// Optional is consumed if declared. fakenet is what makes outbound calls, mail and+// entitlements controllable, and mail is what makes user creation possible at all.func (m *module) Optional() []infra.Key {- return []infra.Key{mailpit.Key, fakenet.Key}+ return []infra.Key{fakenet.Key}}func (m *module) Name() infra.NameParts {@@ -104,18 +104,7 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)env["INFISICAL_RUN_MODES"] = m.runModes}- _, wantSMTP := mailpit.From(d)- if mp, ok := mailpit.From(d); ok {- e := mp.Endpoint(infra.Internal)- env["SMTP_HOST"] = e.Host- env["SMTP_PORT"] = fmt.Sprint(e.Port)- env["SMTP_FROM_ADDRESS"] = "[email protected]"- env["SMTP_FROM_NAME"] = "Infisical Harness"- // SMTP_REQUIRE_TLS defaults to true in env.ts. Against Mailpit that is the- // usual reason a first attempt silently sends nothing.- env["SMTP_REQUIRE_TLS"] = "false"- }-+ _, wantSMTP := fakenet.From(d)var files []infra.Filevar dns []string@@ -143,6 +132,14 @@ func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error)for k, v := range license.Env() {env[k] = v}++ env["SMTP_HOST"] = fakenet.IP+ env["SMTP_PORT"] = fmt.Sprint(smtp.Port)+ env["SMTP_FROM_ADDRESS"] = "[email protected]"+ env["SMTP_FROM_NAME"] = "Infisical Harness"+ // Defaults to true in env.ts, and the fake offers no STARTTLS, so leaving it+ // on makes every send fail.+ env["SMTP_REQUIRE_TLS"] = "false"}for k, v := range m.env {diff --git a/tests/harness/infisical/infisical_test.go b/tests/harness/infisical/infisical_test.goindex 628d3216b8..67cd0b7f59 100644--- a/tests/harness/infisical/infisical_test.go+++ b/tests/harness/infisical/infisical_test.go@@ -8,7 +8,6 @@ import ("github.com/Infisical/infisical/tests/harness/infisical""github.com/Infisical/infisical/tests/infra"- "github.com/Infisical/infisical/tests/infra/mailpit""github.com/Infisical/infisical/tests/infra/postgres""github.com/Infisical/infisical/tests/infra/redis""github.com/Infisical/infisical/tests/internal/spec"@@ -33,7 +32,7 @@ func bootStack(t *testing.T, opts ...infisical.Option) *infisical.Handle {img, err := infisical.ResolveImage(ctx, root, log)require.NoError(t, err)- mods := []infra.Module{postgres.Module(), redis.Module(), mailpit.Module(),+ mods := []infra.Module{postgres.Module(), redis.Module(),infisical.Module(append([]infisical.Option{infisical.WithImage(img)}, opts...)...)}scopes := map[infra.Key]infra.Scope{}for _, m := range mods {diff --git a/tests/harness/principal.go b/tests/harness/principal.goindex 5b7d328d2d..ac684f642d 100644--- a/tests/harness/principal.go+++ b/tests/harness/principal.go@@ -7,9 +7,10 @@ import ("testing""github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fakes/smtp""github.com/Infisical/infisical/tests/harness/infisical""github.com/Infisical/infisical/tests/infra"- "github.com/Infisical/infisical/tests/infra/mailpit"+ "github.com/Infisical/infisical/tests/infra/fakenet""github.com/Infisical/infisical/tests/internal/apierr""github.com/Infisical/infisical/tests/internal/id""github.com/Infisical/infisical/tests/internal/mail"@@ -33,7 +34,7 @@ type principalConfig struct {}// WithName names the principal. For a user it also picks the mailbox, so-// WithName("alice") means alice@<orgslug>.test.+// WithName("alice") means alice@<tenant-nonce>.test.func WithName(name string) PrincipalOption {return func(c *principalConfig) { c.name = name }}@@ -53,14 +54,15 @@ func newPrincipalConfig(prefix string, opts []PrincipalOption) principalConfig {return cfg}-// Mail returns a view of Mailpit scoped to this tenant's domain.+// Mail returns this tenant's inbox. Wait on it with Expect, or ExpectEvent for+// anything Expect does not cover.//// A method rather than a field: it fails with the option to add when the suite has no-// Mailpit, where a field would be a nil dereference three frames inside the client.-func (t *Tenant) Mail(tt *testing.T) *mail.Inbox {+// fakenet, where a field would be a nil dereference three frames inside the client.+func (t *Tenant) Mail(tt *testing.T) *smtp.Inbox {tt.Helper()- h := t.stack.Require(tt, mailpit.Key, "harness.Shared").(*mailpit.Handle)- return mail.NewInbox(h.API(infra.External).URL("http"), t.OrgSlug+".test")+ h := t.stack.Require(tt, fakenet.Key, "harness.Shared").(*fakenet.Handle)+ return smtp.Open(h.AdminURL(), t.mailDomain)}// NewUser creates a real user in this tenant's organization.@@ -68,7 +70,7 @@ func (t *Tenant) Mail(tt *testing.T) *mail.Inbox {// The whole invite flow, because there is no shortcut. The invite response carries// the signup link only when SMTP is unconfigured (org-membership-user-factory.ts),// and the harness configures SMTP on purpose, so the link has to come out of the-// mailbox. That is what makes Mailpit load-bearing rather than decorative.+// mailbox. That is what makes the mail fake load-bearing rather than decorative.//// Five calls: invite, verify, complete-account, select-organization, and the mail// read in between. The last one is not just fetching a scoped token --@@ -105,10 +107,7 @@ func (t *Tenant) newUser(tt *testing.T, cfg principalConfig, inviterToken stringtt.Fatalf("harness: inviting %s returned %d: %s", addr, invited.StatusCode(), apierr.Body(invited.Body))}- msg, err := t.Mail(tt).Await(ctx, addr, mail.Subject("invitation"))- if err != nil {- tt.Fatalf("harness: %v", err)- }+ msg := t.Mail(tt).Expect(tt, addr, smtp.Subject("invitation"))inviteToken, err := mail.Param(msg, "token")if err != nil {tt.Fatalf("harness: %v", err)diff --git a/tests/harness/profile.go b/tests/harness/profile.goindex 10dad19a6c..2c6e093585 100644--- a/tests/harness/profile.go+++ b/tests/harness/profile.go@@ -4,7 +4,6 @@ import ("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")@@ -39,9 +38,6 @@ func (p Profile) String() string {// shared container is adopted by name and takes its environment at creation, so if// one package declared WireMock and another did not, whichever started the instance// first would silently decide whether it runs in cloud mode for everyone.-//-// Mailpit stays shared even under Isolated: it holds no instance state, isolation-// between tenants is by address, and a second one buys nothing.func (p Profile) modules(img infisical.Image, fnImg fakenet.Image, caFile string, extra ...infra.Module) ([]infra.Module, map[infra.Key]infra.Scope) {own := infra.Sharedif p == Isolated {@@ -51,16 +47,15 @@ func (p Profile) modules(img infisical.Image, fnImg fakenet.Image, caFile stringmods := []infra.Module{postgres.Module(),redis.Module(),- mailpit.Module(),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,// Shared even under Isolated: it holds a fixed address on the network, and- // isolation between tenants is by credential rather than by server.+ // isolation between tenants is by credential or mail address rather than by+ // server.fakenet.Key: infra.Shared,infisical.Key: own,}diff --git a/tests/harness/tenant.go b/tests/harness/tenant.goindex f326981a37..bd13df7e25 100644--- a/tests/harness/tenant.go+++ b/tests/harness/tenant.go@@ -10,10 +10,12 @@ import ("github.com/Infisical/infisical/tests/clients/api""github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fakes/smtp""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/internal/apierr"+ "github.com/Infisical/infisical/tests/internal/id""github.com/google/uuid")@@ -37,8 +39,9 @@ type Tenant struct {// ip is this tenant's rate-limit bucket. See infisical.ForwardedFor.ip string- stack *Stack- plan *license.Plan+ mailDomain string+ stack *Stack+ plan *license.Plan}// Kind is what sort of actor a Principal is. Authorization differs by actor type in@@ -77,7 +80,7 @@ type Principal struct {// Address returns a mailbox inside this tenant's own domain, so two parallel tests// inviting "alice" never collide.func (t *Tenant) Address(local string) string {- return local + "@" + t.OrgSlug + ".test"+ return local + "@" + t.mailDomain}// TenantOption adjusts a new tenant.@@ -126,11 +129,15 @@ func (s *Stack) NewTenant(t *testing.T, opts ...TenantOption) *Tenant {}org := created.JSON200.Organization- tenant := &Tenant{OrgID: org.Id, OrgSlug: org.Slug, ip: ip, stack: s, plan: cfg.plan}+ // A nonce rather than the org slug: the event stream only carries scopes that+ // start with this binary's prefix, and the server picks the slug.+ mailDomain := id.Nonce() + ".test"+ smtp.Track(t, s.Require(t, fakenet.Key, "harness.Shared").(*fakenet.Handle).AdminURL(), mailDomain)+ tenant := &Tenant{OrgID: org.Id, OrgSlug: org.Slug, mailDomain: mailDomain, ip: ip, stack: s, plan: cfg.plan}// The root binds itself to the new organization only to invite its administrator,// and its token goes no further than this function. What a test receives is an- // ordinary user at admin@<orgslug>.test, unique to this tenant.+ // ordinary user at admin@<tenant-nonce>.test, unique to this tenant.rootScoped := s.scopeToOrg(t, rootUnscoped, org.Id, ip)tenant.Admin = tenant.newUser(t, principalConfig{name: "admin", orgRole: "admin"}, rootScoped)diff --git a/tests/harnesstest/shared/principal_test.go b/tests/harnesstest/shared/principal_test.goindex 8e692f47e0..d76bdea05d 100644--- a/tests/harnesstest/shared/principal_test.go+++ b/tests/harnesstest/shared/principal_test.go@@ -54,7 +54,7 @@ func TestUser_IsInvitedThroughMail(t *testing.T) {t.Run("should keep users apart when two tenants invite the same local part", func(t *testing.T) {t.Parallel()- spec.Why(t, `One Mailpit serves the run, so mail isolation is by address. Equal+ spec.Why(t, `One SMTP server serves the run, so mail isolation is by address. Equaldomains would let parallel tests read each other's invitations.`)// Setupdiff --git a/tests/infra/fakenet/client.go b/tests/infra/fakenet/client.goindex 9e15caeed9..030c4dc4a5 100644--- a/tests/infra/fakenet/client.go+++ b/tests/infra/fakenet/client.go@@ -18,6 +18,12 @@ import (// 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 {+ Events+}++// Events is a test's view of what one scope published, for waiting on it with+// ExpectEvent. A fake with no state to seed or read uses it on its own.+type Events struct {base stringhost stringkey string@@ -30,14 +36,20 @@ type Scope[S any] struct {// 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]{+ sc := &Scope[S]{Events: *OpenEvents(adminURL, host, key)}+ tt.Cleanup(func() { sc.remove() })+ return sc+}++// OpenEvents returns the events of one scope. The scope still has to be tracked+// before the product uses the key; see Track.+func OpenEvents(adminURL, host, key string) *Events {+ return &Events{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.diff --git a/tests/infra/fakenet/expect.go b/tests/infra/fakenet/expect.goindex 942e2a0602..4514d52492 100644--- a/tests/infra/fakenet/expect.go+++ b/tests/infra/fakenet/expect.go@@ -38,7 +38,7 @@ func Since(m Mark) WaitOption { return func(c *waitConfig) { c.since = m.seq } }//// Read from the server rather than from what this process has received, so a mark// taken while events are still in flight is not behind them.-func (s *Scope[S]) Mark(tt *testing.T) Mark {+func (s *Events) Mark(tt *testing.T) Mark {tt.Helper()res, err := s.http.Get(s.base + AdminPrefix + "/events/seq")if err != nil {@@ -63,7 +63,7 @@ func (s *Scope[S]) Mark(tt *testing.T) Mark {// Each event satisfies at most one expectation, so expecting the same thing twice// needs two occurrences. Events that already happened count, which is what lets this// follow a call that blocks until the product is done.-func (s *Scope[S]) ExpectEvent[E Event](tt *testing.T, match func(E) bool, opts ...WaitOption) E {+func (s *Events) ExpectEvent[E Event](tt *testing.T, match func(E) bool, opts ...WaitOption) E {tt.Helper()st, b := s.buffer(tt)e, err := expectEvent(st, b, s.key, newWaitConfig(defaultExpectWithin, opts), match)@@ -77,7 +77,7 @@ func (s *Scope[S]) ExpectEvent[E Event](tt *testing.T, match func(E) bool, opts// arrives within the window. A nil match accepts any.//// Events already claimed by an ExpectEvent are accounted for and do not fail it.-func (s *Scope[S]) ExpectNoEvent[E Event](tt *testing.T, match func(E) bool, opts ...WaitOption) {+func (s *Events) ExpectNoEvent[E Event](tt *testing.T, match func(E) bool, opts ...WaitOption) {tt.Helper()st, b := s.buffer(tt)if err := expectNoEvent(st, b, s.key, newWaitConfig(defaultExpectNoWithin, opts), match); err != nil {@@ -93,7 +93,7 @@ func newWaitConfig(within time.Duration, opts []WaitOption) waitConfig {return cfg}-func (s *Scope[S]) buffer(tt *testing.T) (*stream, *buffer) {+func (s *Events) buffer(tt *testing.T) (*stream, *buffer) {tt.Helper()st := streamFor(tt, s.base)st.mu.Lock()diff --git a/tests/infra/fakenet/fakenet.go b/tests/infra/fakenet/fakenet.goindex c5674beef1..7817810942 100644--- a/tests/infra/fakenet/fakenet.go+++ b/tests/infra/fakenet/fakenet.go@@ -179,12 +179,18 @@ func (s *Server) scope(host string, svc Service, key string) *scope {id := scopeID{host, key}sc, ok := s.scopes[id]if !ok {- sc = &scope{fake: svc.New(Emitter{log: s.events, host: host, key: key})}+ sc = &scope{fake: svc.New(s.Emitter(host, key))}s.scopes[id] = sc}return sc}+// Emitter publishes under host and key for a fake that is not an HTTP Service and so+// is never handed one per scope.+func (s *Server) Emitter(host, key string) Emitter {+ return Emitter{log: s.events, host: host, key: key}+}+func (s *Server) takeRule(sc *scope, r *http.Request) *Rule {s.mu.Lock()defer s.mu.Unlock()diff --git a/tests/infra/mailpit/mailpit.go b/tests/infra/mailpit/mailpit.godeleted file mode 100644index 85f2929c38..0000000000--- a/tests/infra/mailpit/mailpit.go+++ /dev/null@@ -1,64 +0,0 @@-// Package mailpit runs a Mailpit container: a fake SMTP server with a search API.-//-// Chosen over the dev stack's MailHog for the search API and per-message delete,-// both of which a parallel suite needs. Isolation between tenants is by address-// (alice@<orgslug>.test), not by running more than one server.-package mailpit--import (- "context"-- "github.com/Infisical/infisical/tests/infra"-)--const (- Key = infra.Key("mailpit")-- smtpPort = 1025- apiPort = 8025-)--type module struct{ image string }--type Option func(*module)--func WithImage(img string) Option { return func(m *module) { m.image = img } }--func Module(opts ...Option) infra.Module {- m := &module{image: "axllent/mailpit:latest"}- 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: "mailpit"} }--func (m *module) Start(ctx context.Context, d infra.Deps) (infra.Handle, error) {- c, err := d.Run(ctx, infra.ContainerSpec{- Image: m.image,- Ports: []int{smtpPort, apiPort},- Ready: infra.ForHTTP("/api/v1/info").WithPort("8025/tcp"),- })- if err != nil {- return nil, err- }- return &Handle{c: c}, nil-}--// Handle is a running Mailpit.-type Handle struct{ c infra.Container }--// Endpoint is the SMTP endpoint, which is what a container needs. The test process-// wants API instead.-func (h *Handle) Endpoint(m infra.Mode) infra.Endpoint { return h.c.Endpoint(m, smtpPort) }-func (h *Handle) Stop(ctx context.Context) error { return h.c.Stop(ctx) }--// API is the HTTP endpoint the harness reads messages from. Almost always External:-// the Go test process polls it, not a container.-func (h *Handle) API(m infra.Mode) infra.Endpoint { return h.c.Endpoint(m, apiPort) }--func From(d infra.Deps) (*Handle, bool) { return d.Get[*Handle](Key) }diff --git a/tests/infra/module_test.go b/tests/infra/module_test.goindex 83cff1bd97..3fae257667 100644--- a/tests/infra/module_test.go+++ b/tests/infra/module_test.go@@ -101,10 +101,10 @@ func TestResolve(t *testing.T) {// Action_, err := Resolve(mods(- fakeModule{key: "infisical", optional: []Key{"mailpit"}},- fakeModule{key: "mailpit"},+ fakeModule{key: "infisical", optional: []Key{"fakenet"}},+ fakeModule{key: "fakenet"},),- map[Key]Scope{"infisical": Package, "mailpit": Shared},+ map[Key]Scope{"infisical": Package, "fakenet": Shared},)// Assertdiff --git a/tests/infra/names.go b/tests/infra/names.goindex d95e78ed7b..9d3f0ebe8c 100644--- a/tests/infra/names.go+++ b/tests/infra/names.go@@ -10,7 +10,7 @@ import (const Prefix = "inf"// NetworkName is the shared network. Package-scoped containers join it too, so an-// Isolated suite can still reach the shared Mailpit. It holds no state.+// Isolated suite can still reach the shared fakenet. It holds no state.const NetworkName = Prefix + "-net"// NetworkSubnet is fixed so fakenet can take a fixed address on it.diff --git a/tests/infra/runner.go b/tests/infra/runner.goindex fa1f38776d..139ebefc9c 100644--- a/tests/infra/runner.go+++ b/tests/infra/runner.go@@ -107,7 +107,7 @@ func (r *dockerRunner) Network(ctx context.Context, name string) error {//// Needed because a Shared container is created once, on the shared network, and an// Isolated stack lives on its own: without this its Infisical could not reach the-// shared Mailpit. Adopting a container does not re-apply network options, so this+// shared fakenet. Adopting a container does not re-apply network options, so this// has to be an explicit step rather than something Run can do.func (r *dockerRunner) Connect(ctx context.Context, container, net string, aliases ...string) error {args := []string{"network", "connect"}diff --git a/tests/infra/stack_test.go b/tests/infra/stack_test.goindex 35d8f17d21..4618e4412f 100644--- a/tests/infra/stack_test.go+++ b/tests/infra/stack_test.go@@ -5,7 +5,6 @@ import ("testing""github.com/Infisical/infisical/tests/infra"- "github.com/Infisical/infisical/tests/infra/mailpit""github.com/Infisical/infisical/tests/infra/postgres""github.com/Infisical/infisical/tests/infra/redis""github.com/Infisical/infisical/tests/internal/spec"@@ -54,7 +53,6 @@ func TestStack_AllModulesComeUpTogether(t *testing.T) {handles := startAll(t, []infra.Module{postgres.Module(),redis.Module(),- mailpit.Module(),}, infra.Shared)t.Run("should report a usable external address for every module", func(t *testing.T) {@@ -71,11 +69,4 @@ func TestStack_AllModulesComeUpTogether(t *testing.T) {"%s internal host is a host address", key)}})-- t.Run("should expose mailpit SMTP and API on different ports", func(t *testing.T) {- mp := handles[mailpit.Key].(*mailpit.Handle)- require.NotEqual(t, mp.Endpoint(infra.Internal).Port, mp.API(infra.Internal).Port,- "the application dials one and the harness reads the other")- })-}diff --git a/tests/internal/mail/mail.go b/tests/internal/mail/mail.goindex 8d0617bf9c..2c55748360 100644--- a/tests/internal/mail/mail.go+++ b/tests/internal/mail/mail.go@@ -1,109 +1,16 @@-// Package mail reads messages out of Mailpit.-//-// One Mailpit serves the whole run, so isolation is by address rather than by server:-// an Inbox is scoped to one tenant's mail domain and refuses to look outside it. Two-// parallel tenants can both invite "alice" without seeing each other's mail.+// Package mail pulls what a test needs out of a delivered message: a link, a query+// parameter, or a numeric code.package mailimport (- "context"- "encoding/json""fmt"- "net/http""net/url""strings"- "time"- "github.com/Infisical/infisical/tests/internal/wait"+ "github.com/Infisical/infisical/tests/fakes/smtp")-// Message is the part of a Mailpit message the harness cares about.-type Message struct {- ID string- From string- To []string- Subject string-- // Body is the plain text and HTML parts joined. Callers search it for a link or a- // code rather than caring which part carried it.- Body string-}--// Inbox reads one tenant's mail.-type Inbox struct {- api string- domain string- hc *http.Client-}--// NewInbox returns a view over Mailpit scoped to domain.-func NewInbox(api, domain string) *Inbox {- return &Inbox{api: strings.TrimRight(api, "/"), domain: domain, hc: &http.Client{Timeout: 10 * time.Second}}-}--// Filter narrows what Await will accept.-type Filter func(Message) bool--// Subject accepts a message whose subject contains s.-func Subject(s string) Filter {- return func(m Message) bool { return strings.Contains(m.Subject, s) }-}--// Await blocks until a message to addr matching every filter arrives.-//-// Mail is sent inline with the request that triggers it, so this is normally one round-// trip. It still polls, because "normally" is not "always" and a fixed sleep would-// either be slower than needed or flaky.-func (in *Inbox) Await(ctx context.Context, addr string, filters ...Filter) (Message, error) {- if !strings.HasSuffix(addr, "@"+in.domain) {- return Message{}, fmt.Errorf(- "mail: this inbox is scoped to @%s but was asked for %s.\n"+- "Reading another tenant's mail would make the test order-dependent; use tn.Address(local)",- in.domain, addr)- }-- // Tracked across attempts so the timeout can say how many arrived and matched- // nothing, which is a different bug from none arriving at all.- delivered := 0-- msg, err := wait.For(ctx, func(ctx context.Context) (Message, bool, error) {- msgs, err := in.search(ctx, "to:"+addr)- if err != nil {- return Message{}, false, err- }- delivered = len(msgs)-- // One unreadable message does not abandon the rest of the round: Mailpit can- // report an id before the body is retrievable, and the match may be the- // message after it.- var lastErr error- for _, m := range msgs {- full, mErr := in.message(ctx, m.ID)- if mErr != nil {- lastErr = mErr- continue- }- if matches(full, filters) {- return full, true, nil- }- }- return Message{}, false, lastErr- }, wait.Timeout(20*time.Second))-- if err != nil {- return Message{}, fmt.Errorf("mail: no message for %s (%d delivered, none matched): %w", addr, delivered, err)- }- return msg, nil-}--func matches(m Message, filters []Filter) bool {- for _, f := range filters {- if !f(m) {- return false- }- }- return true-}+type Message = smtp.Message// Link returns the first URL in the body whose query carries param.//@@ -152,65 +59,6 @@ func urlsIn(body string) []string {return out}-type searchResponse struct {- Messages []struct {- ID string `json:"ID"`- } `json:"messages"`-}--func (in *Inbox) search(ctx context.Context, query string) ([]Message, error) {- var res searchResponse- if err := in.get(ctx, "/api/v1/search?query="+url.QueryEscape(query)+"&limit=50", &res); err != nil {- return nil, err- }- out := make([]Message, 0, len(res.Messages))- for _, m := range res.Messages {- out = append(out, Message{ID: m.ID})- }- return out, nil-}--type messageResponse struct {- ID string `json:"ID"`- Subject string `json:"Subject"`- Text string `json:"Text"`- HTML string `json:"HTML"`- From struct {- Address string `json:"Address"`- } `json:"From"`- To []struct {- Address string `json:"Address"`- } `json:"To"`-}--func (in *Inbox) message(ctx context.Context, id string) (Message, error) {- var res messageResponse- if err := in.get(ctx, "/api/v1/message/"+url.PathEscape(id), &res); err != nil {- return Message{}, err- }- m := Message{ID: res.ID, Subject: res.Subject, From: res.From.Address, Body: res.Text + "\n" + res.HTML}- for _, to := range res.To {- m.To = append(m.To, to.Address)- }- return m, nil-}--func (in *Inbox) get(ctx context.Context, path string, into any) error {- req, err := http.NewRequestWithContext(ctx, http.MethodGet, in.api+path, nil)- if err != nil {- return err- }- res, err := in.hc.Do(req)- if err != nil {- return fmt.Errorf("mail: %s: %w", path, err)- }- defer res.Body.Close()- if res.StatusCode != http.StatusOK {- return fmt.Errorf("mail: %s returned %d", path, res.StatusCode)- }- return json.NewDecoder(res.Body).Decode(into)-}-// Code returns the first run of exactly n digits in the body.//// The signup and MFA mails carry a numeric code rather than a link, so Param