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
test(e2e): cover project event subscriptions over SSE
varonixa124373376ae
diff --git a/tests/suites/secretmanager/events/access_test.go b/tests/suites/secretmanager/events/access_test.gonew file mode 100644index 0000000000..4b3316fa00--- /dev/null+++ b/tests/suites/secretmanager/events/access_test.go@@ -0,0 +1,111 @@+package events_test++import (+ "net/http"+ "testing"++ "github.com/Infisical/infisical/tests/fakes/license"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestProjectEvents_Access(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ subscribeTo := func(action string, conditions map[string]any) fixture.Permission {+ return fixture.Permission{Subject: "secret-event-subscriptions", Action: []string{action}, Conditions: conditions}+ }++ t.Run("should refuse when the plan does not include event subscriptions", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t, harness.WithPlan(license.Enterprise().Without(license.EventSubscriptions)))+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))++ // Action+ res := trySubscribe(t, tn.Admin, proj, on("secret:create"))++ // Assert+ require.Equalf(t, http.StatusBadRequest, res.StatusCode(), "body: %s", apierr.Body(res.Body))+ require.Equal(t, "Event subscriptions are not available on your current plan. Please upgrade to access this feature.",+ apierr.Message(res.Body))+ })++ t.Run("should refuse the whole subscription when the role does not allow one of its event types", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ proj.NewRole(t, "create-only", subscribeTo("subscribe-to-creation-events", nil))+ subscriber := proj.NewMachineIdentity(t, fixture.WithRoles("create-only"))++ // Action+ res := trySubscribe(t, subscriber, proj, on("secret:create"), on("secret:delete"))++ // Assert+ require.Equalf(t, http.StatusForbidden, res.StatusCode(), "body: %s", apierr.Body(res.Body))+ require.Equal(t, "You are not allowed to subscribe-to-deletion-events on secret-event-subscriptions",+ apierr.Message(res.Body))+ subscribe(t, subscriber, proj, on("secret:create"))+ })++ t.Run("should refuse a subscription to every environment when the role allows only one", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ proj.NewRole(t, "dev-only", subscribeTo("subscribe-to-creation-events",+ map[string]any{"environment": map[string]any{"$eq": "dev"}}))+ subscriber := proj.NewMachineIdentity(t, fixture.WithRoles("dev-only"))++ // Action+ res := trySubscribe(t, subscriber, proj, on("secret:create"))++ // Assert+ require.Equalf(t, http.StatusForbidden, res.StatusCode(), "body: %s", apierr.Body(res.Body))+ subscribe(t, subscriber, proj, on("secret:create").in("dev", "/"))+ })++ t.Run("should not stream a change in a folder the role denies", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateFolder(t, proj, "dev", "/payroll")+ denied := subscribeTo("subscribe-to-creation-events", map[string]any{"secretPath": map[string]any{"$eq": "/payroll"}})+ denied.Inverted = true+ proj.NewRole(t, "no-payroll", subscribeTo("subscribe-to-creation-events", nil), denied)+ s := subscribe(t, proj.NewMachineIdentity(t, fixture.WithRoles("no-payroll")), proj, on("secret:create"))++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "SALARY", "value", secretmanager.WithPath("/payroll"))+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")++ // Assert+ require.Equal(t, []secretRef{{"dev", "/", "API_KEY"}}, s.next(t).secrets(t))+ })++ t.Run("should refuse another organization's project without revealing it", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ outsider := h.NewTenant(t).Admin++ // Action+ res := trySubscribe(t, outsider, proj, on("secret:create"))++ // Assert+ require.GreaterOrEqualf(t, res.StatusCode(), 400, "body: %s", apierr.Body(res.Body))+ require.NotContains(t, string(res.Body), proj.Name)+ })+}diff --git a/tests/suites/secretmanager/events/filter_test.go b/tests/suites/secretmanager/events/filter_test.gonew file mode 100644index 0000000000..6fb62b9780--- /dev/null+++ b/tests/suites/secretmanager/events/filter_test.go@@ -0,0 +1,86 @@+package events_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/stretchr/testify/require"+)++func TestProjectEvents_Filter(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should stream only the registered event types", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ s := watch(t, proj, on("secret:delete"))++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "first")+ secretmanager.UpdateSecret(t, proj, "dev", "DB_URL", "second")+ secretmanager.DeleteSecret(t, proj, "dev", "DB_URL")++ // Assert+ require.Equal(t, "secret:delete", s.next(t).Type)+ })++ t.Run("should stream only the registered environment", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ s := watch(t, proj, on("secret:create").in("dev", "/"))++ // Action+ secretmanager.CreateSecret(t, proj, "staging", "STAGING_KEY", "value")+ secretmanager.CreateSecret(t, proj, "dev", "DEV_KEY", "value")++ // Assert+ require.Equal(t, []secretRef{{"dev", "/", "DEV_KEY"}}, s.next(t).secrets(t))+ })++ t.Run("should stream a subfolder change when the path is /** or unset but not when it is /", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateFolder(t, proj, "dev", "/app")+ root := watch(t, proj, on("secret:create").in("dev", "/"))+ recursive := watch(t, proj, on("secret:create").in("dev", "/**"))+ unscoped := watch(t, proj, on("secret:create"))++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "NESTED_KEY", "value", secretmanager.WithPath("/app"))+ secretmanager.CreateSecret(t, proj, "dev", "ROOT_KEY", "value")++ // Assert+ require.Equal(t, []secretRef{{"dev", "/", "ROOT_KEY"}}, root.next(t).secrets(t))+ require.Equal(t, []secretRef{{"dev", "/app", "NESTED_KEY"}}, recursive.next(t).secrets(t))+ require.Equal(t, []secretRef{{"dev", "/app", "NESTED_KEY"}}, unscoped.next(t).secrets(t))+ })++ t.Run("should not stream another project's changes", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ other := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ s := watch(t, proj, on("secret:create"))++ // Action+ secretmanager.CreateSecret(t, other, "dev", "OTHER_KEY", "value")+ secretmanager.CreateSecret(t, proj, "dev", "OWN_KEY", "value")++ // Assert+ require.Equal(t, []secretRef{{"dev", "/", "OWN_KEY"}}, s.next(t).secrets(t))+ })+}diff --git a/tests/suites/secretmanager/events/helpers_test.go b/tests/suites/secretmanager/events/helpers_test.gonew file mode 100644index 0000000000..5994ae249b--- /dev/null+++ b/tests/suites/secretmanager/events/helpers_test.go@@ -0,0 +1,174 @@+package events_test++import (+ "bufio"+ "bytes"+ "context"+ "encoding/json"+ "io"+ "net/http"+ "strings"+ "testing"+ "time"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++// eventBudget covers the slowest event here: an import mutation for an importing+// folder, which the source folder's sync job publishes after its debounce.+const eventBudget = 30 * time.Second++type registration struct {+ Event string `json:"event"`+ Conditions *conditions `json:"conditions,omitempty"`+}++type conditions struct {+ EnvironmentSlug string `json:"environmentSlug,omitempty"`+ SecretPath string `json:"secretPath,omitempty"`+}++func on(event string) registration { return registration{Event: event} }++// in narrows a registration to one environment and a path, which may be a glob.+func (r registration) in(env, secretPath string) registration {+ r.Conditions = &conditions{EnvironmentSlug: env, SecretPath: secretPath}+ return r+}++// secretRef is one entry in the payload of a create, update or delete.+type secretRef struct {+ Environment string `json:"environment"`+ SecretPath string `json:"secretPath"`+ SecretKey string `json:"secretKey"`+}++// folderRef is the payload of an import mutation.+type folderRef struct {+ Environment string `json:"environment"`+ SecretPath string `json:"secretPath"`+}++type event struct {+ Name string // the frame's event field+ Type string // the body's eventType+ ProjectType string+ payload json.RawMessage+}++func (e event) secrets(t *testing.T) []secretRef {+ t.Helper()+ var refs []secretRef+ require.NoErrorf(t, json.Unmarshal(e.payload, &refs), "decoding the payload of %s: %s", e.Name, e.payload)+ return refs+}++func (e event) folder(t *testing.T) folderRef {+ t.Helper()+ var ref folderRef+ require.NoErrorf(t, json.Unmarshal(e.payload, &ref), "decoding the payload of %s: %s", e.Name, e.payload)+ return ref+}++type frame struct{ name, data string }++type stream struct {+ frames chan frame+ err error+}++// watch subscribes as a viewer machine identity, the access a subscriber such as the+// Kubernetes operator is usually given.+func watch(t *testing.T, proj *fixture.Project, regs ...registration) *stream {+ t.Helper()+ return subscribe(t, proj.NewMachineIdentity(t, fixture.WithRoles("viewer")), proj, regs...)+}++// subscribe opens a stream that stays open until the test ends. The method without+// WithResponse hands back the unread body, so frames are read as they arrive.+func subscribe(t *testing.T, p *harness.Principal, proj *fixture.Project, regs ...registration) *stream {+ t.Helper()+ res, err := p.API.SubscribeToProjectEventsWithBody(t.Context(), "application/json", subscription(t, proj, regs))+ require.NoError(t, err, "subscribing to project events")+ t.Cleanup(func() { _ = res.Body.Close() })+ if res.StatusCode != http.StatusOK {+ body, _ := io.ReadAll(res.Body)+ t.Fatalf("subscribing to project events returned %d: %s", res.StatusCode, apierr.Body(body))+ }+ require.Equal(t, "text/event-stream", res.Header.Get("Content-Type"))++ s := &stream{frames: make(chan frame, 64)}+ go s.read(t.Context(), res.Body)+ return s+}++// trySubscribe is the subscribe call for a test that expects a refusal. An accepted+// stream never ends, so the deadline turns one into a failure instead of a hang.+func trySubscribe(t *testing.T, p *harness.Principal, proj *fixture.Project, regs ...registration) *api.SubscribeToProjectEventsResponse {+ t.Helper()+ ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)+ defer cancel()+ res, err := p.API.SubscribeToProjectEventsWithBodyWithResponse(ctx, "application/json", subscription(t, proj, regs))+ require.NoError(t, err, "subscribing to project events; a timeout means the stream was accepted")+ return res+}++func subscription(t *testing.T, proj *fixture.Project, regs []registration) io.Reader {+ t.Helper()+ body, err := json.Marshal(map[string]any{"projectId": proj.ID, "register": regs})+ require.NoError(t, err)+ return bytes.NewReader(body)+}++func (s *stream) read(ctx context.Context, body io.Reader) {+ defer close(s.frames)+ sc := bufio.NewScanner(body)+ var f frame+ for sc.Scan() {+ field, value, _ := strings.Cut(sc.Text(), ": ")+ switch field {+ case "event":+ f.name = value+ case "data":+ f.data = value+ case "":+ if f.name != "" && f.name != "ping" {+ select {+ case s.frames <- f:+ case <-ctx.Done():+ return+ }+ }+ f = frame{}+ }+ }+ s.err = sc.Err()+}++// next returns the next event. Events arrive in the order they were published, so a+// test shows a change was left out by making it first and receiving the one after.+func (s *stream) next(t *testing.T) event {+ t.Helper()+ select {+ case f, ok := <-s.frames:+ if !ok {+ t.Fatalf("the stream ended before the next event: %v", s.err)+ }+ var body struct {+ ProjectType string `json:"projectType"`+ Data struct {+ EventType string `json:"eventType"`+ Payload json.RawMessage `json:"payload"`+ } `json:"data"`+ }+ require.NoErrorf(t, json.Unmarshal([]byte(f.data), &body), "decoding %s: %s", f.name, f.data)+ return event{Name: f.name, Type: body.Data.EventType, ProjectType: body.ProjectType, payload: body.Data.Payload}+ case <-time.After(eventBudget):+ t.Fatalf("no event arrived within %s", eventBudget)+ }+ return event{}+}diff --git a/tests/suites/secretmanager/events/import_test.go b/tests/suites/secretmanager/events/import_test.gonew file mode 100644index 0000000000..2b60d9e534--- /dev/null+++ b/tests/suites/secretmanager/events/import_test.go@@ -0,0 +1,79 @@+package events_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestProjectEvents_ImportMutation(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should stream an import mutation for the folder an import is added to", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ s := watch(t, proj, on("secret:import-mutation"))++ // Action+ secretmanager.CreateImport(t, proj, "dev", secretmanager.Location{Env: "staging", Path: "/"})++ // Assert+ ev := s.next(t)+ require.Equal(t, "secret:import-mutation", ev.Type)+ require.Equal(t, folderRef{"dev", "/"}, ev.folder(t))+ })++ t.Run("should stream an import mutation for the importing folder when an imported secret changes", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateFolder(t, proj, "dev", "/shared")+ secretmanager.CreateFolder(t, proj, "dev", "/app")+ secretmanager.CreateImport(t, proj, "dev", secretmanager.Location{Env: "dev", Path: "/shared"},+ secretmanager.IntoPath("/app"))+ s := watch(t, proj, on("secret:import-mutation").in("dev", "/app"))++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "SHARED_KEY", "value", secretmanager.WithPath("/shared"))++ // Assert+ require.Equal(t, folderRef{"dev", "/app"}, s.next(t).folder(t))+ })++ t.Run("should stream an import mutation for both folders when a secret is moved", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateFolder(t, proj, "prod", "/app")+ moved := secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")+ s := watch(t, proj, on("secret:import-mutation"))++ // Action+ res, err := tn.Admin.API.MoveSecretsV4WithResponse(t.Context(), api.MoveSecretsV4JSONRequestBody{+ ProjectId: proj.ID,+ SourceEnvironment: "dev",+ DestinationEnvironment: "prod",+ DestinationSecretPath: new("/app"),+ SecretIds: []string{moved.ID},+ })++ // Assert+ require.NoError(t, err)+ require.NotNilf(t, res.JSON200, "moving returned %d: %s", res.StatusCode(), apierr.Body(res.Body))+ require.ElementsMatch(t, []folderRef{{"dev", "/"}, {"prod", "/app"}},+ []folderRef{s.next(t).folder(t), s.next(t).folder(t)})+ })+}diff --git a/tests/suites/secretmanager/events/main_test.go b/tests/suites/secretmanager/events/main_test.gonew file mode 100644index 0000000000..a736422976--- /dev/null+++ b/tests/suites/secretmanager/events/main_test.go@@ -0,0 +1,9 @@+package events_test++import (+ "testing"++ "github.com/Infisical/infisical/tests/harness"+)++func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }diff --git a/tests/suites/secretmanager/events/stream_test.go b/tests/suites/secretmanager/events/stream_test.gonew file mode 100644index 0000000000..9cda659a22--- /dev/null+++ b/tests/suites/secretmanager/events/stream_test.go@@ -0,0 +1,80 @@+package events_test++import (+ "net/http"+ "slices"+ "testing"++ "github.com/Infisical/infisical/tests/clients/api"+ "github.com/Infisical/infisical/tests/fixture"+ "github.com/Infisical/infisical/tests/fixture/secretmanager"+ "github.com/Infisical/infisical/tests/harness"+ "github.com/Infisical/infisical/tests/internal/apierr"+ "github.com/stretchr/testify/require"+)++func TestProjectEvents_Stream(t *testing.T) {+ t.Parallel()+ h := harness.From(t)++ t.Run("should stream a create, an update and a delete with the secret each one changed", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ s := watch(t, proj, on("secret:create"), on("secret:update"), on("secret:delete"))++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "first")+ secretmanager.UpdateSecret(t, proj, "dev", "DB_URL", "second")+ secretmanager.DeleteSecret(t, proj, "dev", "DB_URL")++ // Assert+ for _, want := range []string{"secret:create", "secret:update", "secret:delete"} {+ ev := s.next(t)+ require.Equal(t, want, ev.Name)+ require.Equal(t, want, ev.Type)+ require.Equal(t, "secret-manager", ev.ProjectType)+ require.Equal(t, []secretRef{{"dev", "/", "DB_URL"}}, ev.secrets(t))+ }+ })++ t.Run("should stream one event naming every secret of a batch create", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ s := watch(t, proj, on("secret:create"))+ batch := api.CreateManySecretsV4JSONRequestBody{ProjectId: proj.ID, Environment: "dev"}+ batch.Secrets = slices.Grow(batch.Secrets, 2)[:2]+ batch.Secrets[0].SecretKey, batch.Secrets[0].SecretValue = "DB_URL", "a"+ batch.Secrets[1].SecretKey, batch.Secrets[1].SecretValue = "API_KEY", "b"++ // Action+ res, err := tn.Admin.API.CreateManySecretsV4WithResponse(t.Context(), batch)++ // Assert+ require.NoError(t, err)+ require.Equalf(t, http.StatusOK, res.StatusCode(), "batch create: %s", apierr.Body(res.Body))+ require.ElementsMatch(t, []secretRef{{"dev", "/", "DB_URL"}, {"dev", "/", "API_KEY"}}, s.next(t).secrets(t))+ })++ t.Run("should not stream a personal override", func(t *testing.T) {+ t.Parallel()++ // Setup+ tn := h.NewTenant(t)+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))+ secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "shared")+ s := watch(t, proj, on("secret:create"))++ // Action+ secretmanager.CreateSecret(t, proj, "dev", "DB_URL", "mine", secretmanager.WithPersonal())+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "shared")++ // Assert+ require.Equal(t, []secretRef{{"dev", "/", "API_KEY"}}, s.next(t).secrets(t))+ })+}