Skip to content

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

feat: switched to event system for fake check

=e703307bf512
diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md
index 074f4330d9..1bc0cddd50 100644
--- a/tests/CLAUDE.md
+++ b/tests/CLAUDE.md
@@ -295,6 +295,45 @@ invented.
sends it on every outbound call, so parallel tenants never see each other and no org id
is threaded anywhere.
+### Waiting on what a fake did
+
+Fakes publish events when their state changes, and a test waits on the event rather
+than polling state:
+
+```go
+mark := gh.Mark(t)
+secret.Delete(t, proj, "dev", "DROP")
+s.trigger(t)
+
+gh.ExpectEvent[github.SecretDeleted](t, func(e github.SecretDeleted) bool {
+ return e.SecretName == "DROP"
+}, fakenet.Since(mark))
+
+gh.ExpectNoEvent[github.SecretCreated](t, nil) // waits 3s by default
+```
+
+- **Events that already happened count**, so it works after a call that blocks.
+- **Each event satisfies one `ExpectEvent`.** Expecting the same thing twice needs
+ two occurrences; `ExpectNoEvent` ignores events already claimed.
+- **Order only when you ask** with `Mark` and `Since`.
+- **Absence needs `ExpectNoEvent`, never an immediate state read.** A read straight
+ after an async action passes before the action lands; the auto-sync-off test did
+ exactly that and could not fail.
+
+Waiting on Infisical itself, such as a sync's status, still polls its API, since that
+is where the product reports its own errors.
+
+An event is a type that names itself, `<service>.<resource>-<past-tense verb>`:
+
+```go
+type SecretDeleted struct{ SecretDetail }
+func (SecretDeleted) EventName() string { return "github.secret-deleted" }
+```
+
+Publish it from the fake with `a.events.Publish(...)` wherever state changes. Whatever
+mints a credential calls `fakenet.Track` before handing it to Infisical, which
+`appconnection` already does.
+
### Adding a fake
One package under `fakes/<service>/`:
diff --git a/tests/fakes/github/events.go b/tests/fakes/github/events.go
new file mode 100644
index 0000000000..f030febc51
--- /dev/null
+++ b/tests/fakes/github/events.go
@@ -0,0 +1,16 @@
+package github
+
+// SecretDetail identifies a secret within an account. Scope is the store address,
+// such as repos/acme/app or orgs/acme.
+type SecretDetail struct {
+ Scope string `json:"scope"`
+ SecretName string `json:"secretName"`
+}
+
+type SecretCreated struct{ SecretDetail }
+type SecretUpdated struct{ SecretDetail }
+type SecretDeleted struct{ SecretDetail }
+
+func (SecretCreated) EventName() string { return "github.secret-created" }
+func (SecretUpdated) EventName() string { return "github.secret-updated" }
+func (SecretDeleted) EventName() string { return "github.secret-deleted" }
diff --git a/tests/fakes/github/fake.go b/tests/fakes/github/fake.go
index 8cfae0d33d..77e5b4ddf8 100644
--- a/tests/fakes/github/fake.go
+++ b/tests/fakes/github/fake.go
@@ -31,8 +31,8 @@ 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{}}
+func (service) New(events fakenet.Emitter) fakenet.Fake {
+ a := &Account{Login: "harness", Stores: map[string]*Store{}, events: events}
a.mux = a.routes()
return a
}
@@ -154,10 +154,13 @@ func (a *Account) put(w http.ResponseWriter, r *http.Request) {
_, existed := st.Secrets[name]
st.Secrets[name] = Secret{Value: string(plain), UpdatedAt: time.Now().UTC()}
+ detail := SecretDetail{Scope: storeKey(r), SecretName: name}
if existed {
+ a.events.Publish(SecretUpdated{detail})
w.WriteHeader(http.StatusNoContent)
return
}
+ a.events.Publish(SecretCreated{detail})
w.WriteHeader(http.StatusCreated)
}
@@ -171,6 +174,7 @@ func (a *Account) remove(w http.ResponseWriter, r *http.Request) {
return
}
delete(st.Secrets, name)
+ a.events.Publish(SecretDeleted{SecretDetail{Scope: storeKey(r), SecretName: name}})
w.WriteHeader(http.StatusNoContent)
}
diff --git a/tests/fakes/github/state.go b/tests/fakes/github/state.go
index 9ec4d2f0a9..2c26488e57 100644
--- a/tests/fakes/github/state.go
+++ b/tests/fakes/github/state.go
@@ -9,6 +9,8 @@ import (
"net/http"
"sync"
"time"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
)
// Account is one GitHub account, addressed by the token a test invented.
@@ -16,8 +18,9 @@ type Account struct {
Login string `json:"login"`
Stores map[string]*Store `json:"stores"`
- mu sync.Mutex
- mux *http.ServeMux
+ mu sync.Mutex
+ mux *http.ServeMux
+ events fakenet.Emitter
}
// Store is a bag of Actions secrets.
diff --git a/tests/fakes/license/fake.go b/tests/fakes/license/fake.go
index 86b9793e2f..8766045225 100644
--- a/tests/fakes/license/fake.go
+++ b/tests/fakes/license/fake.go
@@ -41,7 +41,7 @@ func (service) Scope(r *http.Request) (string, bool) {
// 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()} }
+func (service) New(fakenet.Emitter) fakenet.Fake { return &Org{plan: Enterprise()} }
// Org is one organization's entitlements.
type Org struct {
diff --git a/tests/fixture/appconnection/appconnection.go b/tests/fixture/appconnection/appconnection.go
index a14117d304..0e4945dd03 100644
--- a/tests/fixture/appconnection/appconnection.go
+++ b/tests/fixture/appconnection/appconnection.go
@@ -73,6 +73,10 @@ func Try(tt *testing.T, tn *harness.Tenant, p provider.Provider, opts ...Option)
tn: tn,
}
+ // Before the credential reaches Infisical, so no event published under it can
+ // arrive before its buffer exists.
+ fakenet.Track(tt, conn.FakenetAdmin(tt), p.Host, conn.nonce)
+
// 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
diff --git a/tests/harness/harness.go b/tests/harness/harness.go
index 7b7b05f244..308f31bcce 100644
--- a/tests/harness/harness.go
+++ b/tests/harness/harness.go
@@ -22,6 +22,7 @@ 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/internal/id"
)
// current is the stack Main built, read by From. One per test binary, which is what
@@ -92,6 +93,14 @@ func run(m *testing.M, profile Profile, cfg *config, mainFile string) (int, erro
}
defer stopAll(ctx, owned)
+ // Opened before any test runs, so nothing a test triggers can happen before it is
+ // listening.
+ if fn, ok := stack.modules[fakenet.Key].(*fakenet.Handle); ok {
+ if err := fakenet.Listen(ctx, fn.AdminURL(), id.Binary()); err != nil {
+ return 0, err
+ }
+ }
+
stack.mainFile = mainFile
current = stack
return m.Run(), nil
diff --git a/tests/infra/fakenet/admin.go b/tests/infra/fakenet/admin.go
index 7fef3487aa..5200675565 100644
--- a/tests/infra/fakenet/admin.go
+++ b/tests/infra/fakenet/admin.go
@@ -30,6 +30,15 @@ func (s *Server) Admin(ca *CA) http.Handler {
_ = json.NewEncoder(w).Encode(out)
})
+ mux.HandleFunc("GET "+AdminPrefix+"/events", s.serveEvents)
+
+ // The latest sequence number, read from the server rather than from what a client
+ // has received, so a mark taken while events are still in flight is not behind.
+ mux.HandleFunc("GET "+AdminPrefix+"/events/seq", func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]uint64{"seq": s.events.current()})
+ })
+
mux.HandleFunc("GET "+AdminPrefix+"/ca", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/x-pem-file")
_, _ = w.Write(ca.CertPEM())
diff --git a/tests/infra/fakenet/events.go b/tests/infra/fakenet/events.go
new file mode 100644
index 0000000000..8ca7a53644
--- /dev/null
+++ b/tests/infra/fakenet/events.go
@@ -0,0 +1,149 @@
+package fakenet
+
+import (
+ "encoding/json"
+ "fmt"
+ "log"
+ "net/http"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// Event is something a fake did that a test may wait for. The type names itself, so
+// a detail can never be published under the wrong name.
+type Event interface{ EventName() string }
+
+// EventRecord is one published event as it travels to a test.
+type EventRecord struct {
+ Seq uint64 `json:"seq"`
+ Host string `json:"host"`
+ Scope string `json:"scope"`
+ Event string `json:"event"`
+ At time.Time `json:"at"`
+ Details json.RawMessage `json:"eventDetails"`
+}
+
+// Emitter publishes events for one scope, so a fake cannot attribute an event to
+// another caller.
+type Emitter struct {
+ log *eventLog
+ host string
+ key string
+}
+
+func (e Emitter) Publish(ev Event) {
+ if e.log == nil {
+ return
+ }
+ details, err := json.Marshal(ev)
+ if err != nil {
+ log.Printf("fakenet: dropping %s, its details do not marshal: %v", ev.EventName(), err)
+ return
+ }
+ e.log.append(EventRecord{
+ Host: e.host,
+ Scope: e.key,
+ Event: ev.EventName(),
+ At: time.Now().UTC(),
+ Details: details,
+ })
+}
+
+// historyCap bounds memory while leaving room to resume a dropped stream.
+const historyCap = 50_000
+
+type eventLog struct {
+ mu sync.Mutex
+ records []EventRecord
+ lastSeq uint64
+ changed chan struct{}
+}
+
+func newEventLog() *eventLog { return &eventLog{changed: make(chan struct{})} }
+
+func (l *eventLog) append(rec EventRecord) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.lastSeq++
+ rec.Seq = l.lastSeq
+ l.records = append(l.records, rec)
+ if len(l.records) > historyCap {
+ l.records = l.records[len(l.records)-historyCap:]
+ }
+ close(l.changed)
+ l.changed = make(chan struct{})
+}
+
+// since returns records after seq, whether history no longer reaches back that far,
+// and a channel closed on the next append.
+func (l *eventLog) since(seq uint64) (out []EventRecord, gap bool, changed <-chan struct{}) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if len(l.records) > 0 && l.records[0].Seq > seq+1 {
+ gap = true
+ }
+ for _, r := range l.records {
+ if r.Seq > seq {
+ out = append(out, r)
+ }
+ }
+ return out, gap, l.changed
+}
+
+func (l *eventLog) current() uint64 {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return l.lastSeq
+}
+
+// serveEvents streams events as SSE: history first, then live.
+//
+// One stream per test binary, filtered by credential prefix, so a binary never
+// receives the traffic of packages running beside it.
+func (s *Server) serveEvents(w http.ResponseWriter, r *http.Request) {
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "streaming unsupported", http.StatusInternalServerError)
+ return
+ }
+ prefix := r.URL.Query().Get("prefix")
+
+ var after uint64
+ resuming := false
+ if v := r.Header.Get("Last-Event-ID"); v != "" {
+ after, _ = strconv.ParseUint(v, 10, 64)
+ resuming = true
+ }
+
+ w.Header().Set("Content-Type", "text/event-stream")
+ w.Header().Set("Cache-Control", "no-cache")
+ w.WriteHeader(http.StatusOK)
+ flusher.Flush()
+
+ for {
+ records, gap, changed := s.events.since(after)
+ if gap && resuming {
+ // Resume reached past retained history, so events were lost. Saying so
+ // lets the client fail the affected expectations instead of hanging.
+ _, _ = fmt.Fprint(w, "event: gap\ndata: {}\n\n")
+ }
+ resuming = false
+ for _, rec := range records {
+ after = rec.Seq
+ if !strings.HasPrefix(rec.Scope, prefix) {
+ continue
+ }
+ body, _ := json.Marshal(rec)
+ _, _ = fmt.Fprintf(w, "id: %d\ndata: %s\n\n", rec.Seq, body)
+ }
+ flusher.Flush()
+
+ select {
+ case <-r.Context().Done():
+ return
+ case <-changed:
+ }
+ }
+}
diff --git a/tests/infra/fakenet/events_test.go b/tests/infra/fakenet/events_test.go
new file mode 100644
index 0000000000..082136a1d6
--- /dev/null
+++ b/tests/infra/fakenet/events_test.go
@@ -0,0 +1,283 @@
+package fakenet
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+const testHost = "items.test"
+
+type ItemCreated struct {
+ Name string `json:"name"`
+}
+type ItemDeleted struct {
+ Name string `json:"name"`
+}
+
+func (ItemCreated) EventName() string { return "items.item-created" }
+func (ItemDeleted) EventName() string { return "items.item-deleted" }
+
+type itemService struct{}
+
+func (itemService) Host() string { return testHost }
+func (itemService) Scope(r *http.Request) (string, bool) {
+ return strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
+}
+func (itemService) New(events Emitter) Fake { return &itemFake{events: events} }
+
+type itemFake struct{ events Emitter }
+
+func (f *itemFake) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ name := strings.TrimPrefix(r.URL.Path, "/items/")
+ switch r.Method {
+ case http.MethodPost:
+ f.events.Publish(ItemCreated{Name: name})
+ case http.MethodDelete:
+ f.events.Publish(ItemDeleted{Name: name})
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
+func (f *itemFake) Snapshot() ([]byte, error) { return json.Marshal(struct{}{}) }
+func (f *itemFake) Seed([]byte) error { return nil }
+
+type rig struct {
+ fakes *httptest.Server
+ admin string
+}
+
+// newRig serves one fakenet in-process and opens a stream for prefix, as harness.Main
+// does for a test binary.
+func newRig(t *testing.T, prefix string) *rig {
+ t.Helper()
+ srv := New(itemService{})
+ ca, err := LoadOrCreateCA(filepath.Join(t.TempDir(), "ca.pem"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ fakes := httptest.NewServer(srv)
+ admin := httptest.NewServer(srv.Admin(ca))
+ t.Cleanup(fakes.Close)
+ t.Cleanup(admin.Close)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ if err := Listen(ctx, admin.URL, prefix); err != nil {
+ t.Fatal(err)
+ }
+ return &rig{fakes: fakes, admin: admin.URL}
+}
+
+func (r *rig) call(t *testing.T, method, key, name string) {
+ t.Helper()
+ req, err := http.NewRequestWithContext(t.Context(), method, r.fakes.URL+"/items/"+name, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Host = testHost
+ req.Header.Set("Authorization", "Bearer "+key)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = res.Body.Close()
+}
+
+func (r *rig) scope(t *testing.T, key string) *Scope[struct{}] {
+ t.Helper()
+ Track(t, r.admin, testHost, key)
+ return Open[struct{}](t, r.admin, testHost, key)
+}
+
+func nameIs[E interface{ ItemCreated | ItemDeleted }](want string) func(E) bool {
+ return func(e E) bool {
+ switch v := any(e).(type) {
+ case ItemCreated:
+ return v.Name == want
+ case ItemDeleted:
+ return v.Name == want
+ }
+ return false
+ }
+}
+
+func expectErr[E Event](t *testing.T, sc *Scope[struct{}], match func(E) bool, opts ...WaitOption) error {
+ t.Helper()
+ st, b := sc.buffer(t)
+ _, err := expectEvent(st, b, sc.key, newWaitConfig(defaultExpectWithin, opts), match)
+ return err
+}
+
+func TestEvents_Expect(t *testing.T) {
+ t.Run("ok/an event that already happened is found", func(t *testing.T) {
+ r := newRig(t, "p1")
+ sc := r.scope(t, "p1-a")
+ r.call(t, http.MethodPost, "p1-a", "DB_URL")
+
+ got := sc.ExpectEvent[ItemCreated](t, nameIs[ItemCreated]("DB_URL"))
+ if got.Name != "DB_URL" {
+ t.Errorf("got %q", got.Name)
+ }
+ })
+
+ t.Run("ok/an event that arrives while waiting is found", func(t *testing.T) {
+ r := newRig(t, "p2")
+ sc := r.scope(t, "p2-a")
+ go func() {
+ time.Sleep(200 * time.Millisecond)
+ req, _ := http.NewRequest(http.MethodPost, r.fakes.URL+"/items/LATE", nil)
+ req.Host = testHost
+ req.Header.Set("Authorization", "Bearer p2-a")
+ if res, err := http.DefaultClient.Do(req); err == nil {
+ _ = res.Body.Close()
+ }
+ }()
+ sc.ExpectEvent[ItemCreated](t, nameIs[ItemCreated]("LATE"))
+ })
+
+ t.Run("invalid/each event satisfies one expectation", func(t *testing.T) {
+ r := newRig(t, "p3")
+ sc := r.scope(t, "p3-a")
+ r.call(t, http.MethodPost, "p3-a", "ONCE")
+
+ sc.ExpectEvent[ItemCreated](t, nameIs[ItemCreated]("ONCE"))
+ err := expectErr(t, sc, nameIs[ItemCreated]("ONCE"), Within(300*time.Millisecond))
+ if err == nil || !strings.Contains(err.Error(), "already claimed") {
+ t.Fatalf("a second expectation reused the event or misreported it: %v", err)
+ }
+ })
+
+ t.Run("ok/different types do not depend on order", func(t *testing.T) {
+ r := newRig(t, "p4")
+ sc := r.scope(t, "p4-a")
+ r.call(t, http.MethodPost, "p4-a", "X")
+ r.call(t, http.MethodDelete, "p4-a", "X")
+
+ sc.ExpectEvent[ItemDeleted](t, nil)
+ sc.ExpectEvent[ItemCreated](t, nil)
+ })
+
+ t.Run("invalid/since ignores what happened before the mark", func(t *testing.T) {
+ r := newRig(t, "p5")
+ sc := r.scope(t, "p5-a")
+ r.call(t, http.MethodPost, "p5-a", "X")
+ mark := sc.Mark(t)
+
+ if err := expectErr[ItemCreated](t, sc, nil, Since(mark), Within(300*time.Millisecond)); err == nil {
+ t.Fatal("an event before the mark satisfied an expectation since it")
+ }
+ r.call(t, http.MethodPost, "p5-a", "X")
+ sc.ExpectEvent[ItemCreated](t, nil, Since(mark))
+ })
+
+ t.Run("cross-tenant/one credential never sees another's events", func(t *testing.T) {
+ r := newRig(t, "p6")
+ mine, theirs := r.scope(t, "p6-a"), r.scope(t, "p6-b")
+ r.call(t, http.MethodPost, "p6-b", "THEIRS")
+
+ theirs.ExpectEvent[ItemCreated](t, nil)
+ if err := expectErr[ItemCreated](t, mine, nil, Within(300*time.Millisecond)); err == nil {
+ t.Fatal("an event published under another credential was delivered to this one")
+ }
+ })
+
+ t.Run("ok/the stream only carries this binary's prefix", func(t *testing.T) {
+ r := newRig(t, "p7")
+ foreign := r.scope(t, "other-a")
+ r.call(t, http.MethodPost, "other-a", "X")
+
+ if err := expectErr[ItemCreated](t, foreign, nil, Within(300*time.Millisecond)); err == nil {
+ t.Fatal("an event outside this binary's prefix reached it")
+ }
+ })
+}
+
+func TestEvents_ExpectNo(t *testing.T) {
+ expectNoErr := func(t *testing.T, sc *Scope[struct{}]) error {
+ st, b := sc.buffer(t)
+ return expectNoEvent[ItemCreated](st, b, sc.key, newWaitConfig(300*time.Millisecond, nil), nil)
+ }
+
+ t.Run("ok/nothing published passes", func(t *testing.T) {
+ r := newRig(t, "n1")
+ if err := expectNoErr(t, r.scope(t, "n1-a")); err != nil {
+ t.Fatal(err)
+ }
+ })
+
+ t.Run("invalid/an unused matching event fails", func(t *testing.T) {
+ r := newRig(t, "n2")
+ sc := r.scope(t, "n2-a")
+ r.call(t, http.MethodPost, "n2-a", "X")
+ if err := expectNoErr(t, sc); err == nil {
+ t.Fatal("ExpectNoEvent passed with a matching event present")
+ }
+ })
+
+ t.Run("ok/an event already claimed is accounted for", func(t *testing.T) {
+ r := newRig(t, "n3")
+ sc := r.scope(t, "n3-a")
+ r.call(t, http.MethodPost, "n3-a", "X")
+ sc.ExpectEvent[ItemCreated](t, nil)
+ if err := expectNoErr(t, sc); err != nil {
+ t.Fatalf("a claimed event failed ExpectNoEvent: %v", err)
+ }
+ })
+}
+
+func TestEvents_Failure(t *testing.T) {
+ cases := []struct {
+ name string
+ do func(r *rig, t *testing.T)
+ want string
+ }{
+ {"nothing arrived", func(*rig, *testing.T) {}, "no events arrived in this scope"},
+ {"something else arrived", func(r *rig, t *testing.T) { r.call(t, http.MethodDelete, "f-a", "X") }, "no items.item-created arrived"},
+ {"rejected by the predicate", func(r *rig, t *testing.T) { r.call(t, http.MethodPost, "f-a", "WRONG") }, "none matched"},
+ }
+ for _, tc := range cases {
+ t.Run("invalid/"+tc.name+" is reported as such", func(t *testing.T) {
+ r := newRig(t, "f")
+ sc := r.scope(t, "f-a")
+ tc.do(r, t)
+
+ err := expectErr(t, sc, nameIs[ItemCreated]("RIGHT"), Within(500*time.Millisecond))
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("message does not say %q:\n%v", tc.want, err)
+ }
+ })
+ }
+}
+
+func TestEvents_Loss(t *testing.T) {
+ t.Run("invalid/overflow fails rather than dropping silently", func(t *testing.T) {
+ st := &stream{buffers: map[scopeID]*buffer{}}
+ b := &buffer{changed: make(chan struct{})}
+ st.buffers[scopeID{testHost, "k"}] = b
+ for i := range bufferCap + 1 {
+ st.deliver(EventRecord{Seq: uint64(i + 1), Host: testHost, Scope: "k", Event: "items.item-created", Details: []byte(`{}`)})
+ }
+ _, err := expectEvent[ItemDeleted](st, b, "k", waitConfig{within: time.Second}, nil)
+ if err == nil || !strings.Contains(err.Error(), "were not kept") {
+ t.Fatalf("overflow was not reported: %v", err)
+ }
+ })
+
+ t.Run("invalid/resuming past retained history is a gap", func(t *testing.T) {
+ l := newEventLog()
+ for range historyCap + 10 {
+ l.append(EventRecord{Scope: "k"})
+ }
+ if _, gap, _ := l.since(1); !gap {
+ t.Fatal("resuming from before retained history did not report a gap")
+ }
+ if _, gap, _ := l.since(l.current()); gap {
+ t.Fatal("resuming from the latest event reported a gap")
+ }
+ })
+}
diff --git a/tests/infra/fakenet/expect.go b/tests/infra/fakenet/expect.go
new file mode 100644
index 0000000000..942e2a0602
--- /dev/null
+++ b/tests/infra/fakenet/expect.go
@@ -0,0 +1,249 @@
+package fakenet
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+)
+
+const (
+ defaultExpectWithin = 10 * time.Second
+ defaultExpectNoWithin = 3 * time.Second
+ failureListCap = 20
+)
+
+// Mark is a point in the event stream. Events at or before it are ignored by an
+// expectation that passes Since(mark).
+type Mark struct{ seq uint64 }
+
+// WaitOption adjusts an expectation.
+type WaitOption func(*waitConfig)
+
+type waitConfig struct {
+ within time.Duration
+ since uint64
+}
+
+// Within bounds how long an expectation waits.
+func Within(d time.Duration) WaitOption { return func(c *waitConfig) { c.within = d } }
+
+// Since ignores events at or before the mark, for when order matters.
+func Since(m Mark) WaitOption { return func(c *waitConfig) { c.since = m.seq } }
+
+// Mark records the current point in the stream.
+//
+// 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 {
+ tt.Helper()
+ res, err := s.http.Get(s.base + AdminPrefix + "/events/seq")
+ if err != nil {
+ tt.Fatalf("fakenet: reading the event sequence: %v", err)
+ }
+ defer func() { _ = res.Body.Close() }()
+ if res.StatusCode != http.StatusOK {
+ tt.Fatalf("fakenet: reading the event sequence returned %d", res.StatusCode)
+ }
+ var out struct {
+ Seq uint64 `json:"seq"`
+ }
+ if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
+ tt.Fatalf("fakenet: reading the event sequence: %v", err)
+ }
+ return Mark{seq: out.Seq}
+}
+
+// ExpectEvent waits for an unused event of type E that match accepts, marks it used,
+// and returns it. A nil match accepts any.
+//
+// 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 {
+ tt.Helper()
+ st, b := s.buffer(tt)
+ e, err := expectEvent(st, b, s.key, newWaitConfig(defaultExpectWithin, opts), match)
+ if err != nil {
+ tt.Fatal(err)
+ }
+ return e
+}
+
+// ExpectNoEvent fails if an unused event of type E that match accepts exists or
+// 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) {
+ tt.Helper()
+ st, b := s.buffer(tt)
+ if err := expectNoEvent(st, b, s.key, newWaitConfig(defaultExpectNoWithin, opts), match); err != nil {
+ tt.Fatal(err)
+ }
+}
+
+func newWaitConfig(within time.Duration, opts []WaitOption) waitConfig {
+ cfg := waitConfig{within: within}
+ for _, o := range opts {
+ o(&cfg)
+ }
+ return cfg
+}
+
+func (s *Scope[S]) buffer(tt *testing.T) (*stream, *buffer) {
+ tt.Helper()
+ st := streamFor(tt, s.base)
+ st.mu.Lock()
+ b := st.buffers[scopeID{s.host, s.key}]
+ st.mu.Unlock()
+ if b == nil {
+ tt.Fatalf("fakenet: no events are tracked for scope %s on %s.\n"+
+ "Whatever minted the credential must call fakenet.Track before handing it to Infisical",
+ short(s.key), s.host)
+ }
+ return st, b
+}
+
+func expectEvent[E Event](st *stream, b *buffer, key string, cfg waitConfig, match func(E) bool) (E, error) {
+ var zero E
+ name := zero.EventName()
+ deadline := time.After(cfg.within)
+
+ for {
+ st.mu.Lock()
+ if err := lossLocked(st, b, key); err != nil {
+ st.mu.Unlock()
+ return zero, err
+ }
+ if i, e, ok := findLocked(b, cfg, name, match); ok {
+ b.used[i] = true
+ st.mu.Unlock()
+ return e, nil
+ }
+ changed := b.changed
+ st.mu.Unlock()
+
+ select {
+ case <-changed:
+ case <-deadline:
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ return zero, errors.New(describeMiss(name, cfg, b, key))
+ }
+ }
+}
+
+func expectNoEvent[E Event](st *stream, b *buffer, key string, cfg waitConfig, match func(E) bool) error {
+ var zero E
+ name := zero.EventName()
+ deadline := time.After(cfg.within)
+
+ for {
+ st.mu.Lock()
+ if err := lossLocked(st, b, key); err != nil {
+ st.mu.Unlock()
+ return err
+ }
+ if i, _, ok := findLocked(b, cfg, name, match); ok {
+ rec := b.records[i]
+ st.mu.Unlock()
+ return fmt.Errorf("fakenet: %s matched within %s, expected none (scope %s)\n #%d %s",
+ name, cfg.within, short(key), rec.Seq, rec.Details)
+ }
+ changed := b.changed
+ st.mu.Unlock()
+
+ select {
+ case <-changed:
+ case <-deadline:
+ return nil
+ }
+ }
+}
+
+// findLocked returns the earliest unused event of the named type after the mark that
+// match accepts. Called with the stream lock held.
+func findLocked[E Event](b *buffer, cfg waitConfig, name string, match func(E) bool) (int, E, bool) {
+ var zero E
+ for i, rec := range b.records {
+ if rec.Seq <= cfg.since || b.used[i] || rec.Event != name {
+ continue
+ }
+ var e E
+ if json.Unmarshal(rec.Details, &e) != nil {
+ continue
+ }
+ if match == nil || match(e) {
+ return i, e, true
+ }
+ }
+ return 0, zero, false
+}
+
+func lossLocked(st *stream, b *buffer, key string) error {
+ switch {
+ case st.gap:
+ return errors.New("fakenet: the event stream reconnected past retained history, so events were lost")
+ case b.overflow:
+ return fmt.Errorf("fakenet: more than %d events for scope %s, the rest were not kept", bufferCap, short(key))
+ }
+ return nil
+}
+
+// describeMiss separates the three reasons an expectation fails: nothing arrived,
+// something else arrived, or this event arrived but the predicate rejected it. The
+// predicate is a func and cannot be printed, so near misses stand in for it.
+func describeMiss(name string, cfg waitConfig, b *buffer, key string) string {
+ var same, other []EventRecord
+ claimed := 0
+ for i, rec := range b.records {
+ if rec.Seq <= cfg.since {
+ continue
+ }
+ switch {
+ case rec.Event != name:
+ other = append(other, rec)
+ case b.used[i]:
+ claimed++
+ default:
+ same = append(same, rec)
+ }
+ }
+
+ var out strings.Builder
+ fmt.Fprintf(&out, "fakenet: waited %s for %s (scope %s)\n", cfg.within, name, short(key))
+ switch {
+ case claimed > 0 && len(same) == 0:
+ fmt.Fprintf(&out, "\n %s arrived %d times, all already claimed by an earlier ExpectEvent;"+
+ " each event satisfies one expectation, so this one needs a further occurrence\n", name, claimed)
+ case len(same) == 0 && len(other) == 0:
+ out.WriteString("\n no events arrived in this scope, so the product never reached the fake under this credential\n")
+ case len(same) > 0:
+ fmt.Fprintf(&out, "\n %s arrived %d times, none matched:\n", name, len(same))
+ writeRecords(&out, same, false)
+ default:
+ fmt.Fprintf(&out, "\n no %s arrived\n", name)
+ }
+ if len(other) > 0 {
+ out.WriteString("\n other events in this scope:\n")
+ writeRecords(&out, other, true)
+ }
+ return out.String()
+}
+
+func writeRecords(out *strings.Builder, recs []EventRecord, withName bool) {
+ if len(recs) > failureListCap {
+ fmt.Fprintf(out, " (%d earlier omitted)\n", len(recs)-failureListCap)
+ recs = recs[len(recs)-failureListCap:]
+ }
+ for _, r := range recs {
+ if withName {
+ fmt.Fprintf(out, " #%d %s %s\n", r.Seq, r.Event, r.Details)
+ } else {
+ fmt.Fprintf(out, " #%d %s\n", r.Seq, r.Details)
+ }
+ }
+}
diff --git a/tests/infra/fakenet/fakenet.go b/tests/infra/fakenet/fakenet.go
index 60f25e2cb8..c5674beef1 100644
--- a/tests/infra/fakenet/fakenet.go
+++ b/tests/infra/fakenet/fakenet.go
@@ -32,8 +32,9 @@ type Service interface {
// 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
+ // New builds an empty world for one scope. Events published through the emitter
+ // are attributed to that scope.
+ New(events Emitter) Fake
}
// Fake is one scope's state.
@@ -85,6 +86,8 @@ type Server struct {
// 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
+
+ events *eventLog
}
// Denied is one outbound call that reached no fake.
@@ -96,7 +99,7 @@ type Denied struct {
}
func New(services ...Service) *Server {
- s := &Server{services: map[string]Service{}, scopes: map[scopeID]*scope{}}
+ s := &Server{services: map[string]Service{}, scopes: map[scopeID]*scope{}, events: newEventLog()}
for _, svc := range services {
s.services[svc.Host()] = svc
}
@@ -176,7 +179,7 @@ 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()}
+ sc = &scope{fake: svc.New(Emitter{log: s.events, host: host, key: key})}
s.scopes[id] = sc
}
return sc
diff --git a/tests/infra/fakenet/stream.go b/tests/infra/fakenet/stream.go
new file mode 100644
index 0000000000..f873908da4
--- /dev/null
+++ b/tests/infra/fakenet/stream.go
@@ -0,0 +1,192 @@
+package fakenet
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// bufferCap bounds one credential's events. Overflow fails the test rather than
+// losing events silently.
+const bufferCap = 5_000
+
+type buffer struct {
+ records []EventRecord
+ used []bool
+ overflow bool
+ changed chan struct{}
+}
+
+type stream struct {
+ adminURL string
+ prefix string
+
+ mu sync.Mutex
+ buffers map[scopeID]*buffer
+ lastSeq uint64
+ gap bool
+}
+
+var (
+ streamsMu sync.Mutex
+ streams = map[string]*stream{}
+)
+
+// Listen opens this binary's event stream and keeps it open, resuming after a drop.
+//
+// prefix is the start every credential this binary mints shares, so the server sends
+// only this binary's events. It returns once the first connection is established, so
+// an unreachable fakenet fails in TestMain rather than as a timeout in some test.
+func Listen(ctx context.Context, adminURL, prefix string) error {
+ adminURL = strings.TrimSuffix(adminURL, "/")
+ st := &stream{adminURL: adminURL, prefix: prefix, buffers: map[scopeID]*buffer{}}
+
+ streamsMu.Lock()
+ streams[adminURL] = st
+ streamsMu.Unlock()
+
+ connected := make(chan error, 1)
+ go st.run(ctx, connected)
+
+ select {
+ case err := <-connected:
+ return err
+ case <-time.After(10 * time.Second):
+ return fmt.Errorf("fakenet: event stream at %s did not connect within 10s", adminURL)
+ }
+}
+
+// Track starts collecting events for one credential and stops when the test ends.
+//
+// Called by whatever mints the credential, before handing it to Infisical. Nothing
+// can publish under a credential Infisical has not received, so no event for it can
+// arrive before its buffer exists.
+func Track(tt *testing.T, adminURL, host, key string) {
+ tt.Helper()
+ st := streamFor(tt, adminURL)
+ id := scopeID{host, key}
+
+ st.mu.Lock()
+ st.buffers[id] = &buffer{changed: make(chan struct{})}
+ st.mu.Unlock()
+
+ tt.Cleanup(func() {
+ st.mu.Lock()
+ delete(st.buffers, id)
+ st.mu.Unlock()
+ })
+}
+
+func streamFor(tt *testing.T, adminURL string) *stream {
+ tt.Helper()
+ streamsMu.Lock()
+ st := streams[strings.TrimSuffix(adminURL, "/")]
+ streamsMu.Unlock()
+ if st == nil {
+ tt.Fatalf("fakenet: no event stream for %s. harness.Main opens one; a test outside the harness must call fakenet.Listen", adminURL)
+ }
+ return st
+}
+
+func (st *stream) run(ctx context.Context, connected chan<- error) {
+ first := true
+ for ctx.Err() == nil {
+ err := st.consume(ctx, func() {
+ if first {
+ first = false
+ connected <- nil
+ }
+ })
+ if first {
+ first = false
+ connected <- err
+ return
+ }
+ select {
+ case <-ctx.Done():
+ case <-time.After(200 * time.Millisecond):
+ }
+ }
+}
+
+func (st *stream) consume(ctx context.Context, onOpen func()) error {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet,
+ st.adminURL+AdminPrefix+"/events?prefix="+url.QueryEscape(st.prefix), nil)
+ if err != nil {
+ return err
+ }
+ st.mu.Lock()
+ if st.lastSeq > 0 {
+ req.Header.Set("Last-Event-ID", strconv.FormatUint(st.lastSeq, 10))
+ }
+ st.mu.Unlock()
+
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return fmt.Errorf("fakenet: opening the event stream: %w", err)
+ }
+ defer func() { _ = res.Body.Close() }()
+ if res.StatusCode != http.StatusOK {
+ return fmt.Errorf("fakenet: event stream returned %d", res.StatusCode)
+ }
+ onOpen()
+
+ scanner := bufio.NewScanner(res.Body)
+ scanner.Buffer(make([]byte, 64*1024), 4*1024*1024)
+ gapNext := false
+ for scanner.Scan() {
+ line := scanner.Text()
+ switch {
+ case line == "event: gap":
+ gapNext = true
+ case strings.HasPrefix(line, "data: "):
+ if gapNext {
+ gapNext = false
+ st.markGap()
+ continue
+ }
+ var rec EventRecord
+ if json.Unmarshal([]byte(strings.TrimPrefix(line, "data: ")), &rec) == nil {
+ st.deliver(rec)
+ }
+ }
+ }
+ return scanner.Err()
+}
+
+func (st *stream) deliver(rec EventRecord) {
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ st.lastSeq = rec.Seq
+
+ b, ok := st.buffers[scopeID{rec.Host, rec.Scope}]
+ if !ok {
+ return
+ }
+ if len(b.records) >= bufferCap {
+ b.overflow = true
+ } else {
+ b.records = append(b.records, rec)
+ b.used = append(b.used, false)
+ }
+ close(b.changed)
+ b.changed = make(chan struct{})
+}
+
+func (st *stream) markGap() {
+ st.mu.Lock()
+ defer st.mu.Unlock()
+ st.gap = true
+ for _, b := range st.buffers {
+ close(b.changed)
+ b.changed = make(chan struct{})
+ }
+}
diff --git a/tests/internal/id/id.go b/tests/internal/id/id.go
index 9cb3b21aef..316c9dd327 100644
--- a/tests/internal/id/id.go
+++ b/tests/internal/id/id.go
@@ -14,11 +14,18 @@ import (
// not collide.
func Short() string { return random(4) }
-// Nonce is a credential a stub can be keyed on.
+// binary is shared by every nonce this test binary mints.
+var binary = random(4)
+
+// Binary is the prefix of every nonce from this process, so fakenet can send this
+// binary only its own events while other packages run beside it.
+func Binary() string { return binary }
+
+// Nonce is a credential a fake can be keyed on.
//
// Unguessable is not the point; unique is. It is what tells one tenant's outbound
-// requests from another's in a shared request journal.
-func Nonce() string { return random(16) }
+// requests from another's on a shared fakenet.
+func Nonce() string { return binary + random(16) }
func random(n int) string {
b := make([]byte, n)
diff --git a/tests/suites/secretmanager/syncs/github_test.go b/tests/suites/secretmanager/syncs/github_test.go
index 5947b09106..e097a781a6 100644
--- a/tests/suites/secretmanager/syncs/github_test.go
+++ b/tests/suites/secretmanager/syncs/github_test.go
@@ -10,6 +10,7 @@ import (
"github.com/Infisical/infisical/tests/fixture/project"
"github.com/Infisical/infisical/tests/fixture/secret"
"github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/infra/fakenet"
"github.com/Infisical/infisical/tests/internal/spec"
"github.com/Infisical/infisical/tests/provider"
)
@@ -53,9 +54,14 @@ func TestGitHubSync_SyncSecrets(t *testing.T) {
secret.Create(t, proj, "dev", "DROP", "2")
s.trigger(t)
+ mark := gh.Mark(t)
secret.Delete(t, proj, "dev", "DROP")
s.trigger(t)
+ gh.ExpectEvent[github.SecretDeleted](t, func(e github.SecretDeleted) bool {
+ return e.SecretName == "DROP"
+ }, fakenet.Since(mark))
+
got := gh.Repo(t, "acme/app").Secrets
if got["KEEP"].Value != "1" {
t.Errorf("KEEP holds %q, want 1", got["KEEP"].Value)
@@ -199,9 +205,7 @@ func TestGitHubSync_Create(t *testing.T) {
newSync(t, proj, conn, repoScope("acme", "app"), autoSync(false))
- if store := gh.Repo(t, "acme/app"); store != nil && len(store.Secrets) > 0 {
- t.Errorf("a sync created with auto-sync off wrote to the destination: %v", keys(store.Secrets))
- }
+ gh.ExpectNoEvent[github.SecretCreated](t, nil)
})
}