Skip to content

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

test(e2e): add a webhook sink fake and cover webhook CRUD, delivery, failures and request and rotation notifications

varonix333d6ba46d28
diff --git a/tests/cmd/fakenet/main.go b/tests/cmd/fakenet/main.go
index ef67727612..e6c12e3a6e 100644
--- a/tests/cmd/fakenet/main.go
+++ b/tests/cmd/fakenet/main.go
@@ -17,6 +17,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/fakes/webhook"
"github.com/Infisical/infisical/tests/infra/fakenet"
)
@@ -34,6 +35,8 @@ func main() {
srv := fakenet.New(
github.Service,
license.Service,
+ webhook.Service,
+ webhook.Slack,
)
mail := smtp.New(func(domain string) fakenet.Emitter { return srv.Emitter(smtp.Host, domain) })
diff --git a/tests/fakes/webhook/controlplane.go b/tests/fakes/webhook/controlplane.go
new file mode 100644
index 0000000000..ce5ccd0f3d
--- /dev/null
+++ b/tests/fakes/webhook/controlplane.go
@@ -0,0 +1,25 @@
+package webhook
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// ControlPlane is a test's view of one receiving URL inside fakenet.
+type ControlPlane struct {
+ *fakenet.Scope[Endpoint]
+}
+
+// Open returns the endpoint a nonce addresses on a sink. The nonce has to be tracked
+// with fakenet.Track before its URL reaches Infisical.
+func Open(tt *testing.T, adminURL string, sink Sink, nonce string) *ControlPlane {
+ tt.Helper()
+ return &ControlPlane{fakenet.Open[Endpoint](tt, adminURL, sink.Host(), nonce)}
+}
+
+// Deliveries is everything the endpoint received so far, oldest first.
+func (cp *ControlPlane) Deliveries(tt *testing.T) []Delivery {
+ tt.Helper()
+ return cp.State(tt).Deliveries
+}
diff --git a/tests/fakes/webhook/events.go b/tests/fakes/webhook/events.go
new file mode 100644
index 0000000000..c05121a3fe
--- /dev/null
+++ b/tests/fakes/webhook/events.go
@@ -0,0 +1,7 @@
+package webhook
+
+// DeliveryReceived is published for every delivery the endpoint answered, whatever
+// the status.
+type DeliveryReceived struct{ Delivery }
+
+func (DeliveryReceived) EventName() string { return "webhook.delivery-received" }
diff --git a/tests/fakes/webhook/fake.go b/tests/fakes/webhook/fake.go
new file mode 100644
index 0000000000..f3aa2f941c
--- /dev/null
+++ b/tests/fakes/webhook/fake.go
@@ -0,0 +1,147 @@
+package webhook
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// Sink is one hostname that accepts deliveries.
+type Sink struct {
+ host string
+
+ // prefix comes before the nonce in the path. Slack's incoming webhooks live
+ // under /services/.
+ prefix string
+ slack bool
+}
+
+// Service is a generic receiver on a hostname of its own. Infisical takes any URL for
+// a general webhook, so the name only has to resolve, which every name does here.
+var Service = Sink{host: "hooks.webhook.test", prefix: "/"}
+
+// Slack answers as hooks.slack.com, the only host Infisical accepts for a Slack
+// webhook.
+var Slack = Sink{host: "hooks.slack.com", prefix: "/services/", slack: true}
+
+func (s Sink) Host() string { return s.host }
+
+// URL is the address a test hands Infisical. The nonce in the path is what keeps
+// parallel tenants' deliveries apart, since a webhook carries no credential.
+func (s Sink) URL(nonce string) string { return "https://" + s.host + s.prefix + nonce }
+
+// Scope is the first path segment after the prefix.
+func (s Sink) Scope(r *http.Request) (string, bool) {
+ rest, ok := strings.CutPrefix(r.URL.Path, s.prefix)
+ if !ok {
+ return "", false
+ }
+ nonce, _, _ := strings.Cut(rest, "/")
+ return nonce, nonce != ""
+}
+
+func (s Sink) New(events fakenet.Emitter) fakenet.Fake {
+ e := &Endpoint{Deliveries: []Delivery{}, sink: s, events: events}
+ e.mux = e.routes()
+ return e
+}
+
+func (e *Endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { e.mux.ServeHTTP(w, r) }
+
+func (e *Endpoint) routes() *http.ServeMux {
+ mux := http.NewServeMux()
+ if e.sink.slack {
+ // Slack's incoming webhooks take a POST and nothing else.
+ mux.HandleFunc("POST /services/{nonce}", e.receive)
+ mux.HandleFunc("POST /services/{nonce}/{rest...}", e.receive)
+ return mux
+ }
+ // A generic receiver records whatever arrives, so a delivery sent with the wrong
+ // method shows up in the event rather than as a 405 nobody reads.
+ mux.HandleFunc("/{nonce}", e.receive)
+ mux.HandleFunc("/{nonce}/{rest...}", e.receive)
+ return mux
+}
+
+func (e *Endpoint) receive(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ http.Error(w, "reading the body: "+err.Error(), http.StatusBadRequest)
+ return
+ }
+
+ e.mu.Lock()
+ status, answer := e.answer(body)
+ d := Delivery{
+ Method: r.Method,
+ Path: r.URL.Path,
+ Header: r.Header.Clone(),
+ Body: string(body),
+ Status: status,
+ ReceivedAt: time.Now().UTC(),
+ }
+ e.Deliveries = append(e.Deliveries, d)
+ e.mu.Unlock()
+
+ e.events.Publish(DeliveryReceived{d})
+
+ w.Header().Set("Content-Type", "text/plain")
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(answer))
+}
+
+// answer is what the endpoint replies. Called with the lock held.
+//
+// Slack refuses a body it cannot render with a 400 and a short code, which is how a
+// payload missing its text fails in production; modelling it is what lets a test
+// about the Slack format fail on a malformed card instead of passing.
+func (e *Endpoint) answer(body []byte) (int, string) {
+ if e.Respond != 0 && e.Respond != http.StatusOK {
+ return e.Respond, http.StatusText(e.Respond)
+ }
+ if !e.sink.slack {
+ return http.StatusOK, ""
+ }
+ var msg struct {
+ Text string `json:"text"`
+ Blocks json.RawMessage `json:"blocks"`
+ }
+ if json.Unmarshal(body, &msg) != nil {
+ return http.StatusBadRequest, "invalid_payload"
+ }
+ if msg.Text == "" && len(msg.Blocks) == 0 {
+ return http.StatusBadRequest, "no_text"
+ }
+ return http.StatusOK, "ok"
+}
+
+// Snapshot marshals under the lock, so a delivery arriving mid-encode cannot race it.
+func (e *Endpoint) Snapshot() ([]byte, error) {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ return json.Marshal(struct {
+ Respond int `json:"respond,omitempty"`
+ Deliveries []Delivery `json:"deliveries"`
+ }{e.Respond, e.Deliveries})
+}
+
+// Seed sets the response status. Deliveries are not seedable: they are only ever
+// what Infisical sent.
+func (e *Endpoint) Seed(raw []byte) error {
+ var in struct {
+ Respond int `json:"respond"`
+ }
+ if err := json.Unmarshal(raw, &in); err != nil {
+ return err
+ }
+ e.mu.Lock()
+ defer e.mu.Unlock()
+ if in.Respond != 0 {
+ e.Respond = in.Respond
+ }
+ return nil
+}
diff --git a/tests/fakes/webhook/fake_test.go b/tests/fakes/webhook/fake_test.go
new file mode 100644
index 0000000000..c92cf2a6ac
--- /dev/null
+++ b/tests/fakes/webhook/fake_test.go
@@ -0,0 +1,179 @@
+package webhook_test
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+ "github.com/stretchr/testify/require"
+)
+
+// stack is fakenet in-process: the fake-serving handler and its control API.
+type stack struct {
+ fakes *httptest.Server
+ admin string
+}
+
+func newStack(t *testing.T) stack {
+ t.Helper()
+ srv := fakenet.New(webhook.Service, webhook.Slack)
+ fakes := httptest.NewServer(srv)
+ t.Cleanup(fakes.Close)
+ admin := httptest.NewServer(srv.Admin(nil))
+ t.Cleanup(admin.Close)
+ require.NoError(t, fakenet.Listen(t.Context(), admin.URL, ""))
+ return stack{fakes: fakes, admin: admin.URL}
+}
+
+// open tracks a nonce on a sink and returns its control plane, the way the fixture
+// does before a URL reaches Infisical.
+func (s stack) open(t *testing.T, sink webhook.Sink, nonce string) *webhook.ControlPlane {
+ t.Helper()
+ fakenet.Track(t, s.admin, sink.Host(), nonce)
+ return webhook.Open(t, s.admin, sink, nonce)
+}
+
+// post sends a delivery to a sink URL through the in-process server, keeping the
+// sink's hostname as the Host header the way DNS interception does.
+func (s stack) post(t *testing.T, sinkURL, body string, header map[string]string) (int, string) {
+ t.Helper()
+ u, err := url.Parse(sinkURL)
+ require.NoError(t, err)
+ req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, s.fakes.URL+u.Path, strings.NewReader(body))
+ require.NoError(t, err)
+ req.Host = u.Host
+ for k, v := range header {
+ req.Header.Set(k, v)
+ }
+ res, err := s.fakes.Client().Do(req)
+ require.NoError(t, err)
+ defer func() { _ = res.Body.Close() }()
+ out, err := io.ReadAll(res.Body)
+ require.NoError(t, err)
+ return res.StatusCode, string(out)
+}
+
+func TestWebhookFake_Deliveries(t *testing.T) {
+ t.Run("should keep a delivery and answer 200 when a generic sink receives one", func(t *testing.T) {
+ // Setup
+ s := newStack(t)
+ sink := s.open(t, webhook.Service, "nonce-a")
+
+ // Action
+ code, _ := s.post(t, webhook.Service.URL("nonce-a"), `{"event":"test"}`,
+ map[string]string{"Content-Type": "application/json", "X-Infisical-Signature": "t=1;abc"})
+
+ // Assert
+ require.Equal(t, http.StatusOK, code)
+ got := sink.Deliveries(t)
+ require.Len(t, got, 1)
+ require.Equal(t, http.MethodPost, got[0].Method)
+ require.Equal(t, "/nonce-a", got[0].Path)
+ require.Equal(t, `{"event":"test"}`, got[0].Body)
+ require.Equal(t, "t=1;abc", got[0].Header.Get("X-Infisical-Signature"))
+ })
+
+ t.Run("should publish a delivery-received event carrying the method, path, headers and body", func(t *testing.T) {
+ // Setup
+ s := newStack(t)
+ sink := s.open(t, webhook.Service, "nonce-a")
+
+ // Action
+ s.post(t, webhook.Service.URL("nonce-a")+"/deep/path", `{"n":1}`, map[string]string{"X-Trace": "abc"})
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, nil)
+ require.Equal(t, http.MethodPost, got.Method)
+ require.Equal(t, "/nonce-a/deep/path", got.Path)
+ require.Equal(t, "abc", got.Header.Get("X-Trace"))
+ require.Equal(t, `{"n":1}`, got.Body)
+ require.Equal(t, http.StatusOK, got.Status)
+ })
+
+ t.Run("should answer the seeded status and still keep the delivery", func(t *testing.T) {
+ // Setup
+ s := newStack(t)
+ sink := s.open(t, webhook.Service, "nonce-a")
+ sink.Seed(t, webhook.Respond(http.StatusInternalServerError))
+
+ // Action
+ code, _ := s.post(t, webhook.Service.URL("nonce-a"), `{}`, nil)
+
+ // Assert
+ require.Equal(t, http.StatusInternalServerError, code)
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, nil)
+ require.Equal(t, http.StatusInternalServerError, got.Status)
+ require.Len(t, sink.Deliveries(t), 1)
+ })
+
+ t.Run("should keep endpoints apart when two nonces share the host", func(t *testing.T) {
+ // Setup
+ s := newStack(t)
+ a := s.open(t, webhook.Service, "nonce-a")
+ b := s.open(t, webhook.Service, "nonce-b")
+
+ // Action
+ s.post(t, webhook.Service.URL("nonce-a"), `{}`, nil)
+
+ // Assert
+ require.Len(t, a.Deliveries(t), 1)
+ require.Empty(t, b.Deliveries(t), "nonce b received nonce a's delivery")
+ })
+
+ t.Run("should refuse a delivery when the path carries no nonce", func(t *testing.T) {
+ // Setup
+ s := newStack(t)
+
+ // Action
+ code, body := s.post(t, "https://"+webhook.Service.Host()+"/", `{}`, nil)
+
+ // Assert
+ require.Equalf(t, http.StatusNotImplemented, code, "%s", body)
+ })
+}
+
+func TestWebhookFake_Slack(t *testing.T) {
+ t.Run("should answer ok when the body has text", func(t *testing.T) {
+ // Setup
+ s := newStack(t)
+ sink := s.open(t, webhook.Slack, "nonce-a")
+
+ // Action
+ code, body := s.post(t, webhook.Slack.URL("nonce-a"), `{"text":"hello"}`, nil)
+
+ // Assert
+ require.Equal(t, http.StatusOK, code)
+ require.Equal(t, "ok", body)
+ require.Len(t, sink.Deliveries(t), 1)
+ })
+
+ t.Run("should refuse with no_text and keep the delivery when the body has no text", func(t *testing.T) {
+ // Setup
+ s := newStack(t)
+ sink := s.open(t, webhook.Slack, "nonce-a")
+
+ // Action
+ code, body := s.post(t, webhook.Slack.URL("nonce-a"), `{"event":"test"}`, nil)
+
+ // Assert
+ require.Equal(t, http.StatusBadRequest, code)
+ require.Equal(t, "no_text", body)
+ require.Equal(t, http.StatusBadRequest, sink.Deliveries(t)[0].Status)
+ })
+
+ t.Run("should refuse a path outside /services when it is sent to hooks.slack.com", func(t *testing.T) {
+ // Setup
+ s := newStack(t)
+
+ // Action
+ code, body := s.post(t, "https://"+webhook.Slack.Host()+"/nonce-a", `{"text":"hello"}`, nil)
+
+ // Assert
+ require.Equalf(t, http.StatusNotImplemented, code, "%s", body)
+ })
+}
diff --git a/tests/fakes/webhook/state.go b/tests/fakes/webhook/state.go
new file mode 100644
index 0000000000..49266d4fec
--- /dev/null
+++ b/tests/fakes/webhook/state.go
@@ -0,0 +1,51 @@
+// Package webhook fakes the receiving end of an outgoing webhook: an HTTPS endpoint
+// that accepts deliveries and keeps what it was sent.
+//
+// One fake for every receiver, Slack included. A Slack incoming webhook is the same
+// thing at a fixed host with one extra rule about the body, so splitting it out would
+// mean two receivers free to disagree about what a delivery is.
+package webhook
+
+import (
+ "encoding/json"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+)
+
+// Endpoint is one receiving URL, addressed by the nonce in its path.
+type Endpoint struct {
+ // Respond is the status the endpoint answers every delivery with. Zero means a
+ // success. Unlike fakenet's Fail, the delivery is still kept and published, so a
+ // test can wait on a failed delivery and then on the absence of a retry.
+ Respond int `json:"respond,omitempty"`
+
+ Deliveries []Delivery `json:"deliveries"`
+
+ mu sync.Mutex
+ mux *http.ServeMux
+ sink Sink
+ events fakenet.Emitter
+}
+
+// Delivery is one request the endpoint received, with the status it answered.
+//
+// Body is the raw text rather than decoded JSON: a signature is computed over the
+// exact bytes, and re-encoding would change them.
+type Delivery struct {
+ Method string `json:"method"`
+ Path string `json:"path"`
+ Header http.Header `json:"header"`
+ Body string `json:"body"`
+ Status int `json:"status"`
+ ReceivedAt time.Time `json:"receivedAt"`
+}
+
+// Decode reads the body as JSON into v.
+func (d Delivery) Decode(v any) error { return json.Unmarshal([]byte(d.Body), v) }
+
+// Respond is a seed fragment that sets the status every later delivery is answered
+// with.
+func Respond(status int) any { return Endpoint{Respond: status} }
diff --git a/tests/fixture/secretmanager/webhook.go b/tests/fixture/secretmanager/webhook.go
new file mode 100644
index 0000000000..ba6b1ba05b
--- /dev/null
+++ b/tests/fixture/secretmanager/webhook.go
@@ -0,0 +1,27 @@
+package secretmanager
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/stretchr/testify/require"
+)
+
+// CreateWebhook subscribes a general webhook at url to every event at env and
+// secretPath, and returns its ID. A test about the webhook's own options calls the
+// route itself.
+func CreateWebhook(tt *testing.T, p *fixture.Project, env, secretPath, url string) string {
+ tt.Helper()
+ res, err := p.Tenant().Admin.API.CreateWebhookWithResponse(tt.Context(), api.CreateWebhookJSONRequestBody{
+ ProjectId: p.ID,
+ Environment: env,
+ SecretPath: &secretPath,
+ WebhookUrl: url,
+ })
+ require.NoErrorf(tt, err, "creating a webhook at %s:%s", env, secretPath)
+ require.NotNilf(tt, res.JSON200, "creating a webhook at %s:%s returned %d: %s",
+ env, secretPath, res.StatusCode(), apierr.Body(res.Body))
+ return res.JSON200.Webhook.Id.String()
+}
diff --git a/tests/fixture/webhooksink.go b/tests/fixture/webhooksink.go
new file mode 100644
index 0000000000..cf63eaf264
--- /dev/null
+++ b/tests/fixture/webhooksink.go
@@ -0,0 +1,29 @@
+package fixture
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+ "github.com/Infisical/infisical/tests/internal/id"
+)
+
+// WebhookSink is a receiving URL of the test's own and the fake behind it.
+type WebhookSink struct {
+ *webhook.ControlPlane
+ URL string
+}
+
+// NewWebhookSink mints a URL on sink. Each one is a separate endpoint, so a test that
+// needs to tell two webhooks apart gives each its own sink.
+func NewWebhookSink(tt *testing.T, tn *harness.Tenant, sink webhook.Sink) *WebhookSink {
+ tt.Helper()
+ nonce := id.Nonce()
+ admin := FakenetAdmin(tt, tn)
+
+ // Before the URL reaches Infisical, so no delivery can arrive before its buffer
+ // exists.
+ fakenet.Track(tt, admin, sink.Host(), nonce)
+ return &WebhookSink{ControlPlane: webhook.Open(tt, admin, sink, nonce), URL: sink.URL(nonce)}
+}
diff --git a/tests/suites/secretmanager/accessapprovals/webhook_test.go b/tests/suites/secretmanager/accessapprovals/webhook_test.go
new file mode 100644
index 0000000000..8f54c55f82
--- /dev/null
+++ b/tests/suites/secretmanager/accessapprovals/webhook_test.go
@@ -0,0 +1,89 @@
+package accessapprovals_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/stretchr/testify/require"
+)
+
+// accessRequestEvent is the general payload of an access-request webhook.
+type accessRequestEvent struct {
+ Event string `json:"event"`
+ Action string `json:"action"`
+ Project struct {
+ ID string `json:"id"`
+ } `json:"project"`
+ Request struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ IsBypassed bool `json:"isBypassed"`
+ Policy struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ HasSequencedApprovers bool `json:"hasSequencedApprovers"`
+ } `json:"policy"`
+ RequestedAccess struct {
+ Target struct {
+ Environment struct {
+ Slug string `json:"slug"`
+ } `json:"environment"`
+ SecretPath string `json:"secretPath"`
+ } `json:"target"`
+ IsTemporary bool `json:"isTemporary"`
+ Permissions []struct {
+ Subject string `json:"subject"`
+ Actions []string `json:"actions"`
+ } `json:"permissions"`
+ } `json:"requestedAccess"`
+ RequestedBy struct {
+ Type string `json:"type"`
+ ID string `json:"id"`
+ } `json:"requestedBy"`
+ ApprovedAt *string `json:"approvedAt"`
+ RevokedAt *string `json:"revokedAt"`
+ } `json:"request"`
+}
+
+func TestAccessApprovalRequest_Webhook(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should notify a webhook with the request details when a request opens", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ g := newGuarded(t)
+ sink := fixture.NewWebhookSink(t, g.tn, webhook.Service)
+ secretmanager.CreateWebhook(t, g.proj, "dev", "/", sink.URL)
+
+ // Action
+ requestID := openRequest(t, g.requester, g.proj, guardedPath, nil)
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, func(d webhook.DeliveryReceived) bool {
+ var p accessRequestEvent
+ return d.Decode(&p) == nil && p.Event == "secrets.access-request.modified" && p.Request.ID == requestID
+ })
+ var p accessRequestEvent
+ require.NoError(t, got.Decode(&p))
+ require.Equal(t, "created", p.Action)
+ require.Equal(t, g.proj.ID, p.Project.ID)
+ require.Equal(t, "pending", p.Request.Status)
+ require.False(t, p.Request.IsBypassed)
+ require.Equal(t, g.policyID, p.Request.Policy.ID)
+ require.Equal(t, mustGetPolicy(t, g.proj, g.policyID).Name, p.Request.Policy.Name)
+ require.False(t, p.Request.Policy.HasSequencedApprovers)
+ require.Equal(t, "dev", p.Request.RequestedAccess.Target.Environment.Slug)
+ require.Equal(t, guardedPath, p.Request.RequestedAccess.Target.SecretPath)
+ require.False(t, p.Request.RequestedAccess.IsTemporary)
+ require.Len(t, p.Request.RequestedAccess.Permissions, 1)
+ require.Equal(t, "secrets", p.Request.RequestedAccess.Permissions[0].Subject)
+ require.Equal(t, []string{"read"}, p.Request.RequestedAccess.Permissions[0].Actions)
+ require.Equal(t, "user", p.Request.RequestedBy.Type)
+ require.Equal(t, g.requester.ID.String(), p.Request.RequestedBy.ID)
+ require.Nil(t, p.Request.ApprovedAt)
+ require.Nil(t, p.Request.RevokedAt)
+ })
+}
diff --git a/tests/suites/secretmanager/approvals/webhook_test.go b/tests/suites/secretmanager/approvals/webhook_test.go
new file mode 100644
index 0000000000..7a08089684
--- /dev/null
+++ b/tests/suites/secretmanager/approvals/webhook_test.go
@@ -0,0 +1,80 @@
+package approvals_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/stretchr/testify/require"
+)
+
+// changeRequestEvent is the general payload of a change-request webhook.
+type changeRequestEvent struct {
+ Event string `json:"event"`
+ Action string `json:"action"`
+ Project struct {
+ ID string `json:"id"`
+ } `json:"project"`
+ Request struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ HasMerged bool `json:"hasMerged"`
+ Policy struct {
+ ID string `json:"id"`
+ } `json:"policy"`
+ RequestedBy struct {
+ ID string `json:"id"`
+ } `json:"requestedBy"`
+ Target struct {
+ Environment struct {
+ Slug string `json:"slug"`
+ } `json:"environment"`
+ SecretPath string `json:"secretPath"`
+ } `json:"target"`
+ } `json:"request"`
+}
+
+// changeRequestAction waits for the delivery of one action on a request.
+func changeRequestAction(t *testing.T, sink *fixture.WebhookSink, requestID, action string) changeRequestEvent {
+ t.Helper()
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, func(e webhook.DeliveryReceived) bool {
+ var p changeRequestEvent
+ return e.Decode(&p) == nil && p.Event == "secrets.change-request.modified" &&
+ p.Request.ID == requestID && p.Action == action
+ })
+ var p changeRequestEvent
+ require.NoError(t, got.Decode(&p))
+ return p
+}
+
+func TestSecretApprovalRequest_Webhook(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should notify a webhook on create, review and merge", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ p := newProtectedProject(t)
+ sink := fixture.NewWebhookSink(t, p.tn, webhook.Service)
+ secretmanager.CreateWebhook(t, p.proj, "dev", "/", sink.URL)
+
+ // Action
+ held := heldRequest(t, p.proj, createSecret(t, p.committer, p.proj, "API_KEY", "value").Body)
+ approve(t, p.reviewer, held.ID)
+ merge(t, p.committer, held.ID)
+
+ // Assert
+ id := held.ID.String()
+ created := changeRequestAction(t, sink, id, "created")
+ require.Equal(t, p.proj.ID, created.Project.ID)
+ require.Equal(t, p.policyID.String(), created.Request.Policy.ID)
+ require.Equal(t, p.committer.ID.String(), created.Request.RequestedBy.ID)
+ require.Equal(t, "dev", created.Request.Target.Environment.Slug)
+ require.Equal(t, "/", created.Request.Target.SecretPath)
+ require.False(t, created.Request.HasMerged)
+ changeRequestAction(t, sink, id, "reviewed")
+ merged := changeRequestAction(t, sink, id, "merged")
+ require.True(t, merged.Request.HasMerged)
+ })
+}
diff --git a/tests/suites/secretmanager/rotations/webhook_test.go b/tests/suites/secretmanager/rotations/webhook_test.go
new file mode 100644
index 0000000000..5e2108a084
--- /dev/null
+++ b/tests/suites/secretmanager/rotations/webhook_test.go
@@ -0,0 +1,58 @@
+package rotations_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/stretchr/testify/require"
+)
+
+// rotationFailed is the general payload of a rotation-failed webhook.
+type rotationFailed struct {
+ Event string `json:"event"`
+ Project struct {
+ ProjectID string `json:"projectId"`
+ Environment string `json:"environment"`
+ SecretPath string `json:"secretPath"`
+ RotationName string `json:"rotationName"`
+ ErrorMessage string `json:"errorMessage"`
+ TriggeredManually bool `json:"triggeredManually"`
+ } `json:"project"`
+}
+
+func TestSecretRotation_Webhook(t *testing.T) {
+ t.Parallel()
+
+ t.Run("should send a rotation-failed webhook when a manual rotation fails", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ e := setup(t)
+ r := e.newRotation(t)
+ sink := fixture.NewWebhookSink(t, e.tn, webhook.Service)
+ secretmanager.CreateWebhook(t, e.proj, "dev", "/", sink.URL)
+ e.target.DropRole(t, e.users[1].name)
+
+ // Action
+ res := r.rotate(t)
+
+ // Assert
+ requireStatus(t, http.StatusInternalServerError, res.StatusCode(), res.Body)
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, func(d webhook.DeliveryReceived) bool {
+ var p rotationFailed
+ return d.Decode(&p) == nil && p.Event == "secrets.rotation-failed"
+ })
+ var p rotationFailed
+ require.NoError(t, got.Decode(&p))
+ require.Equal(t, e.proj.ID, p.Project.ProjectID)
+ require.Equal(t, "dev", p.Project.Environment)
+ require.Equal(t, "/", p.Project.SecretPath)
+ require.Equal(t, r.Name, p.Project.RotationName)
+ require.True(t, p.Project.TriggeredManually)
+ require.Equal(t, "Credential rotation failed. Check the rotation status in the dashboard for more details.",
+ p.Project.ErrorMessage, "the provider's own error stays out of the webhook")
+ })
+}
diff --git a/tests/suites/secretmanager/webhooks/access_test.go b/tests/suites/secretmanager/webhooks/access_test.go
new file mode 100644
index 0000000000..398dd4c7a2
--- /dev/null
+++ b/tests/suites/secretmanager/webhooks/access_test.go
@@ -0,0 +1,93 @@
+package webhooks_test
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/stretchr/testify/require"
+)
+
+func TestWebhook_Access(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should refuse another tenant's hook on get, list, update, delete and test, and change nothing", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `Refusal, not a status: get answers 404 and the other routes 403 today, and
+ making them agree must not break this claim.`)
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ id := newHook(t, proj, sink.URL)
+ outsider := h.NewTenant(t).Admin
+
+ // Action
+ got, err := outsider.API.GetWebhookByIdWithResponse(t.Context(), id)
+ require.NoError(t, err)
+ listed, err := outsider.API.ListWebhooksWithResponse(t.Context(), &api.ListWebhooksParams{ProjectId: proj.ID})
+ require.NoError(t, err)
+ updated := updateHook(t, outsider, id, api.UpdateWebhookJSONRequestBody{IsDisabled: new(true)})
+ deleted, err := outsider.API.DeleteWebhookWithResponse(t.Context(), id)
+ require.NoError(t, err)
+ tested := testHook(t, outsider, id)
+
+ // Assert
+ for name, res := range map[string]struct {
+ status int
+ body []byte
+ }{
+ "get": {got.StatusCode(), got.Body},
+ "list": {listed.StatusCode(), listed.Body},
+ "update": {updated.StatusCode(), updated.Body},
+ "delete": {deleted.StatusCode(), deleted.Body},
+ "test": {tested.StatusCode(), tested.Body},
+ } {
+ require.GreaterOrEqualf(t, res.status, 400, "%s was accepted: %s", name, apierr.Body(res.body))
+ require.NotContainsf(t, string(res.body), sink.URL, "%s revealed the hook's URL", name)
+ }
+ after := getHook(t, proj, id)
+ require.False(t, after.IsDisabled)
+ require.Nil(t, after.LastStatus)
+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, nil)
+ })
+
+ t.Run("should let a viewer list and read hooks but refuse create, update and delete", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ viewer := proj.NewUser(t, fixture.WithPrincipalName("viewer"), fixture.WithRoles("viewer"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ id := newHook(t, proj, sink.URL)
+ other := fixture.NewWebhookSink(t, tn, webhook.Service)
+
+ // Action
+ listed := listHooks(t, viewer, proj)
+ got, err := viewer.API.GetWebhookByIdWithResponse(t.Context(), id)
+ require.NoError(t, err)
+ created := createHook(t, proj, other.URL, createdBy(viewer))
+ updated := updateHook(t, viewer, id, api.UpdateWebhookJSONRequestBody{IsDisabled: new(true)})
+ deleted, err := viewer.API.DeleteWebhookWithResponse(t.Context(), id)
+ require.NoError(t, err)
+
+ // Assert
+ require.Len(t, listed, 1)
+ require.Equal(t, sink.URL, listed[0].URL)
+ require.Equalf(t, http.StatusOK, got.StatusCode(), "%s", apierr.Body(got.Body))
+ require.Equalf(t, http.StatusForbidden, created.StatusCode(), "%s", apierr.Body(created.Body))
+ require.Equalf(t, http.StatusForbidden, updated.StatusCode(), "%s", apierr.Body(updated.Body))
+ require.Equalf(t, http.StatusForbidden, deleted.StatusCode(), "%s", apierr.Body(deleted.Body))
+ after := listHooks(t, tn.Admin, proj)
+ require.Len(t, after, 1)
+ require.False(t, after[0].IsDisabled)
+ })
+}
diff --git a/tests/suites/secretmanager/webhooks/crud_test.go b/tests/suites/secretmanager/webhooks/crud_test.go
new file mode 100644
index 0000000000..17614be62f
--- /dev/null
+++ b/tests/suites/secretmanager/webhooks/crud_test.go
@@ -0,0 +1,192 @@
+package webhooks_test
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "slices"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/stretchr/testify/require"
+)
+
+func TestWebhook_Create(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should store the path, environment and event filter and hide the secret key", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+
+ // Action
+ res := createHook(t, proj, sink.URL, inEnv("staging"), atPath("/app/"), signedWith("signing-key"),
+ onlyEvents(api.CreateWebhookJSONBodyEventsFilterEventNameSecretsModified))
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ require.NotContains(t, string(res.Body), "signing-key")
+ got := getHook(t, proj, res.JSON200.Webhook.Id.String())
+ require.Equal(t, "staging", got.Environment.Slug)
+ require.Equal(t, "/app", got.SecretPath)
+ require.Equal(t, sink.URL, got.URL)
+ require.Equal(t, "general", got.Type)
+ require.False(t, got.IsDisabled)
+ require.Equal(t, []string{secretModified}, got.events())
+ })
+
+ t.Run("should refuse an unknown environment and create nothing", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+
+ // Action
+ res := createHook(t, proj, sink.URL, inEnv("nope"))
+
+ // Assert
+ require.Equalf(t, http.StatusNotFound, res.StatusCode(), "%s", apierr.Body(res.Body))
+ require.Equal(t, fmt.Sprintf("Environment with slug 'nope' in project with ID '%s' not found", proj.ID),
+ errorMessage(t, res.Body))
+ require.Empty(t, listHooks(t, tn.Admin, proj))
+ })
+
+ t.Run("should refuse a Slack hook whose host is not hooks.slack.com and create nothing", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+
+ // Action
+ res := createHook(t, proj, sink.URL, slackType())
+
+ // Assert
+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "%s", apierr.Body(res.Body))
+ require.Contains(t, string(res.Body), "Incoming Webhook URL is invalid.")
+ require.Empty(t, listHooks(t, tn.Admin, proj))
+ })
+
+ t.Run("should accept a Slack hook on hooks.slack.com", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Slack)
+
+ // Action
+ res := createHook(t, proj, sink.URL, slackType())
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ require.Equal(t, "slack", getHook(t, proj, res.JSON200.Webhook.Id.String()).Type)
+ })
+}
+
+func TestWebhook_Update(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should toggle disabled and replace the event filter", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ id := newHook(t, proj, sink.URL)
+ filter := []struct {
+ EventName api.UpdateWebhookJSONBodyEventsFilterEventName `json:"eventName"`
+ }{{EventName: api.UpdateWebhookJSONBodyEventsFilterEventName("secrets.rotation-failed")}}
+
+ // Action
+ off := updateHook(t, tn.Admin, id, api.UpdateWebhookJSONRequestBody{IsDisabled: new(true), EventsFilter: &filter})
+ offRead := getHook(t, proj, id)
+ on := updateHook(t, tn.Admin, id, api.UpdateWebhookJSONRequestBody{IsDisabled: new(false), EventsFilter: new(filter[:0])})
+
+ // Assert
+ require.Equalf(t, http.StatusOK, off.StatusCode(), "%s", apierr.Body(off.Body))
+ require.True(t, offRead.IsDisabled)
+ require.Equal(t, []string{"secrets.rotation-failed"}, offRead.events())
+ require.Equalf(t, http.StatusOK, on.StatusCode(), "%s", apierr.Body(on.Body))
+ onRead := getHook(t, proj, id)
+ require.False(t, onRead.IsDisabled)
+ require.Empty(t, onRead.events())
+ })
+
+ t.Run("should refuse an update with no fields and change nothing", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ id := newHook(t, proj, sink.URL)
+
+ // Action
+ res := updateHook(t, tn.Admin, id, api.UpdateWebhookJSONRequestBody{})
+
+ // Assert
+ require.Equalf(t, http.StatusUnprocessableEntity, res.StatusCode(), "%s", apierr.Body(res.Body))
+ require.Contains(t, string(res.Body), "At least one field is required")
+ require.False(t, getHook(t, proj, id).IsDisabled)
+ })
+}
+
+func TestWebhook_Delete(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should return only the sanitized fields and remove the hook", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ id := newHook(t, proj, sink.URL, signedWith("signing-key"))
+
+ // Action
+ res, err := tn.Admin.API.DeleteWebhookWithResponse(t.Context(), id)
+
+ // Assert
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ var body struct {
+ Webhook map[string]json.RawMessage `json:"webhook"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body, &body))
+ keys := make([]string, 0, len(body.Webhook))
+ for k := range body.Webhook {
+ keys = append(keys, k)
+ }
+ slices.Sort(keys)
+ require.Equal(t, []string{
+ "createdAt", "envId", "environment", "eventsFilter", "id", "isDisabled",
+ "lastRunErrorMessage", "lastStatus", "projectId", "secretPath", "type", "updatedAt",
+ }, keys, "an exact key set, so a new encrypted column cannot leak through this route unnoticed")
+ require.Equal(t, `"`+id+`"`, string(body.Webhook["id"]))
+ require.Empty(t, listHooks(t, tn.Admin, proj))
+ })
+}
+
+func errorMessage(t *testing.T, body []byte) string {
+ t.Helper()
+ var out struct {
+ Message string `json:"message"`
+ }
+ require.NoErrorf(t, json.Unmarshal(body, &out), "reading the error message: %s", apierr.Body(body))
+ return out.Message
+}
diff --git a/tests/suites/secretmanager/webhooks/delivery_test.go b/tests/suites/secretmanager/webhooks/delivery_test.go
new file mode 100644
index 0000000000..745debdb3e
--- /dev/null
+++ b/tests/suites/secretmanager/webhooks/delivery_test.go
@@ -0,0 +1,256 @@
+package webhooks_test
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+ "github.com/stretchr/testify/require"
+)
+
+// importBudget covers two queue hops: the source folder's sync job finds the import
+// and queues one for the importing folder, and each hop has its own debounce and
+// delivery delay.
+var importBudget = fakenet.Within(30 * time.Second)
+
+func TestWebhook_Delivery(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should deliver once per change and record success", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ id := newHook(t, proj, sink.URL)
+ require.Nil(t, getHook(t, proj, id).LastStatus, "a new webhook reports a run")
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ require.Equal(t, http.MethodPost, got.Method)
+ require.Equal(t, proj.ID, decodeGeneral(t, got.Delivery).Project.ProjectID)
+ ran := awaitRun(t, proj, id)
+ require.Equal(t, "success", *ran.LastStatus)
+ require.Nil(t, ran.LastRunErrorMessage)
+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, nil)
+ })
+
+ t.Run("should deliver for /** but not / on a subfolder change, and not for another environment", 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")
+ recursive := fixture.NewWebhookSink(t, tn, webhook.Service)
+ root := fixture.NewWebhookSink(t, tn, webhook.Service)
+ staging := fixture.NewWebhookSink(t, tn, webhook.Service)
+ newHook(t, proj, recursive.URL, atPath("/**"))
+ newHook(t, proj, root.URL, atPath("/"))
+ newHook(t, proj, staging.URL, inEnv("staging"), atPath("/**"))
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value", secretmanager.WithPath("/app"))
+
+ // Assert
+ got := recursive.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ require.Equal(t, "/app", decodeGeneral(t, got.Delivery).Project.SecretPath)
+ root.ExpectNoEvent[webhook.DeliveryReceived](t, nil)
+ staging.ExpectNoEvent[webhook.DeliveryReceived](t, nil)
+ })
+
+ t.Run("should skip a disabled hook and a hook whose filter leaves the event out", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ control := fixture.NewWebhookSink(t, tn, webhook.Service)
+ disabled := fixture.NewWebhookSink(t, tn, webhook.Service)
+ filtered := fixture.NewWebhookSink(t, tn, webhook.Service)
+ newHook(t, proj, control.URL)
+ disable(t, proj, newHook(t, proj, disabled.URL))
+ newHook(t, proj, filtered.URL,
+ onlyEvents(api.CreateWebhookJSONBodyEventsFilterEventNameSecretsChangeRequestModified))
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ control.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ disabled.ExpectNoEvent[webhook.DeliveryReceived](t, nil)
+ filtered.ExpectNoEvent[webhook.DeliveryReceived](t, nil)
+ })
+
+ t.Run("should deliver when the filter names the event", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ newHook(t, proj, sink.URL, onlyEvents(api.CreateWebhookJSONBodyEventsFilterEventNameSecretsModified))
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ })
+
+ t.Run("should send the documented general payload", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ member := proj.NewUser(t, fixture.WithPrincipalName("writer"), fixture.WithRoles("member"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ newHook(t, proj, sink.URL)
+ before := time.Now().Add(-time.Minute).UnixMilli()
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value", secretmanager.As(member))
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ require.Equal(t, "application/json", contentType(got.Delivery))
+ p := decodeGeneral(t, got.Delivery)
+ require.Equal(t, proj.ID, p.Project.WorkspaceID)
+ require.Equal(t, proj.ID, p.Project.ProjectID)
+ require.Equal(t, proj.Name, p.Project.ProjectName)
+ require.Equal(t, "dev", p.Project.Environment)
+ require.Equal(t, "Development", p.Project.EnvironmentName)
+ require.Equal(t, "/", p.Project.SecretPath)
+ require.Equal(t, member.Email, p.Project.ChangedBy)
+ require.Equal(t, "user", p.Project.ChangedByActorType)
+ require.Greater(t, p.Timestamp, before)
+ })
+
+ t.Run("should send a Slack card with the change details", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Slack)
+ id := newHook(t, proj, sink.URL, slackType())
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, nil)
+ require.Equalf(t, http.StatusOK, got.Status, "Slack refused the card: %s", got.Body)
+ var card slackCard
+ require.NoError(t, got.Decode(&card))
+ require.Equal(t, "A secret value has been added or modified.", card.Text)
+ require.Len(t, card.Attachments, 1)
+ require.Equal(t, map[string]string{
+ "Project": proj.Name,
+ "Environment": "dev",
+ "Environment Name": "Development",
+ "Secret Path": "/",
+ "Modified By": tn.Admin.Email,
+ "Modified By Actor Type": "user",
+ }, card.attachment(0))
+ require.Equal(t, "success", *awaitRun(t, proj, id).LastStatus)
+ })
+
+ t.Run("should sign the body with x-infisical-signature as HMAC-SHA256 of the secret key", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ newHook(t, proj, sink.URL, signedWith("signing-key"))
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ mac := hmac.New(sha256.New, []byte("signing-key"))
+ mac.Write([]byte(got.Body))
+ want := fmt.Sprintf("t=%d;%s", decodeGeneral(t, got.Delivery).Timestamp, hex.EncodeToString(mac.Sum(nil)))
+ require.Equal(t, want, got.Header.Get("X-Infisical-Signature"))
+ })
+
+ t.Run("should send no signature when the hook has no secret key", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ newHook(t, proj, sink.URL)
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ require.Empty(t, got.Header.Values("X-Infisical-Signature"))
+ })
+
+ t.Run("should fire on the importing path when an imported folder 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"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ newHook(t, proj, sink.URL, atPath("/app"))
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "SHARED_KEY", "value", secretmanager.WithPath("/shared"))
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified), importBudget)
+ require.Equal(t, "/app", decodeGeneral(t, got.Delivery).Project.SecretPath)
+ })
+}
+
+func contentType(d webhook.Delivery) string {
+ ct, _, _ := strings.Cut(d.Header.Get("Content-Type"), ";")
+ return strings.TrimSpace(ct)
+}
+
+type slackCard struct {
+ Text string `json:"text"`
+ Attachments []struct {
+ Fields []struct {
+ Title string `json:"title"`
+ Value string `json:"value"`
+ } `json:"fields"`
+ } `json:"attachments"`
+}
+
+func (c slackCard) attachment(i int) map[string]string {
+ out := map[string]string{}
+ for _, f := range c.Attachments[i].Fields {
+ out[f.Title] = f.Value
+ }
+ return out
+}
diff --git a/tests/suites/secretmanager/webhooks/failure_test.go b/tests/suites/secretmanager/webhooks/failure_test.go
new file mode 100644
index 0000000000..f1ca9c9731
--- /dev/null
+++ b/tests/suites/secretmanager/webhooks/failure_test.go
@@ -0,0 +1,202 @@
+package webhooks_test
+
+import (
+ "net/http"
+ "net/url"
+ "testing"
+ "time"
+
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/fixture/secretmanager"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/infra/fakenet"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/Infisical/infisical/tests/internal/spec"
+ "github.com/Infisical/infisical/tests/internal/wait"
+ "github.com/stretchr/testify/require"
+)
+
+// noRetryWindow is longer than the queue's first 3 s backoff, so a job that threw and
+// was retried would deliver inside it.
+var noRetryWindow = fakenet.Within(10 * time.Second)
+
+func TestWebhook_Failure(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should record failed with the error message when the sink answers 500", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ sink.Seed(t, webhook.Respond(http.StatusInternalServerError))
+ id := newHook(t, proj, sink.URL)
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ require.Equal(t, http.StatusInternalServerError, got.Status)
+ ran := awaitRun(t, proj, id)
+ require.Equal(t, "failed", *ran.LastStatus)
+ require.NotNil(t, ran.LastRunErrorMessage)
+ require.Equal(t, "Request failed with status code 500", *ran.LastRunErrorMessage)
+ })
+
+ t.Run("should send a delivery four times when the sink answers 500, then record failed and stop", func(t *testing.T) {
+ t.Parallel()
+ spec.Why(t, `The HTTP client retries a 5xx three times. The delivery job then settles every
+ hook and never throws, so the queue's own five attempts never apply. Pinned as today's
+ contract: a receiver that is down for a few seconds misses the event.`)
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ sink.Seed(t, webhook.Respond(http.StatusInternalServerError))
+ id := newHook(t, proj, sink.URL)
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ for range 4 {
+ sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ }
+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, nil, noRetryWindow)
+ require.Equal(t, "failed", *awaitRun(t, proj, id).LastStatus)
+ })
+
+ t.Run("should send a delivery once when the sink refuses it with 400", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ sink.Seed(t, webhook.Respond(http.StatusBadRequest))
+ id := newHook(t, proj, sink.URL)
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ sink.ExpectNoEvent[webhook.DeliveryReceived](t, nil, noRetryWindow)
+ ran := awaitRun(t, proj, id)
+ require.Equal(t, "failed", *ran.LastStatus)
+ require.Equal(t, "Request failed with status code 400", *ran.LastRunErrorMessage)
+ })
+
+ t.Run("should record success and clear the error once the sink recovers", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ sink.Seed(t, webhook.Respond(http.StatusBadRequest))
+ id := newHook(t, proj, sink.URL)
+ failed := testHook(t, tn.Admin, id)
+ require.Equalf(t, http.StatusOK, failed.StatusCode(), "%s", apierr.Body(failed.Body))
+ require.Equal(t, "failed", *decodeHook(t, failed.Body).LastStatus)
+ sink.Seed(t, webhook.Respond(http.StatusOK))
+
+ // Action
+ secretmanager.CreateSecret(t, proj, "dev", "API_KEY", "value")
+
+ // Assert
+ sink.ExpectEvent[webhook.DeliveryReceived](t, event(secretModified))
+ wait.Until(t, "the webhook to record a successful run", func() bool {
+ got := getHook(t, proj, id)
+ return got.LastStatus != nil && *got.LastStatus == "success"
+ })
+ require.Nil(t, getHook(t, proj, id).LastRunErrorMessage)
+ })
+}
+
+func TestWebhook_Test(t *testing.T) {
+ t.Parallel()
+ h := harness.From(t)
+
+ t.Run("should deliver a test event and report success", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ id := newHook(t, proj, sink.URL, atPath("/app"))
+
+ // Action
+ res := testHook(t, tn.Admin, id)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ require.Equal(t, "success", *decodeHook(t, res.Body).LastStatus)
+ require.Equal(t, "success", *getHook(t, proj, id).LastStatus)
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, event("test"))
+ p := decodeGeneral(t, got.Delivery)
+ require.Equal(t, proj.ID, p.Project.ProjectID)
+ require.Equal(t, proj.Name, p.Project.ProjectName)
+ require.Equal(t, "dev", p.Project.Environment)
+ require.Equal(t, "/app", p.Project.SecretPath)
+ })
+
+ t.Run("should send the test event four times and report failed with the error message when the sink answers 503", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Service)
+ sink.Fail(t, "POST", "*", http.StatusServiceUnavailable)
+ id := newHook(t, proj, sink.URL)
+
+ // Action
+ res := testHook(t, tn.Admin, id)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ got := getHook(t, proj, id)
+ require.Equal(t, "failed", *got.LastStatus)
+ require.NotNil(t, got.LastRunErrorMessage)
+ require.Equal(t, "Request failed with status code 503", *got.LastRunErrorMessage)
+ require.Equal(t, 4, sink.Received(t, "POST", sinkPath(t, sink)), "one attempt and the HTTP client's three retries")
+ })
+
+ t.Run("should send a Slack test message that Slack accepts", func(t *testing.T) {
+ t.Parallel()
+
+ // Setup
+ tn := h.NewTenant(t)
+ proj := fixture.NewProject(t, tn, fixture.WithProjectType("secret-manager"))
+ sink := fixture.NewWebhookSink(t, tn, webhook.Slack)
+ id := newHook(t, proj, sink.URL, slackType())
+
+ // Action
+ res := testHook(t, tn.Admin, id)
+
+ // Assert
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "%s", apierr.Body(res.Body))
+ require.Equal(t, "success", *decodeHook(t, res.Body).LastStatus)
+ got := sink.ExpectEvent[webhook.DeliveryReceived](t, nil)
+ var card slackCard
+ require.NoError(t, got.Decode(&card))
+ require.Equal(t, "This is a test message from Infisical webhooks.", card.Text)
+ require.Equal(t, proj.Name, card.attachment(0)["Project"])
+ })
+}
+
+// sinkPath is the path a delivery to the sink arrives on, as fakenet's call log
+// records it.
+func sinkPath(t *testing.T, sink *fixture.WebhookSink) string {
+ t.Helper()
+ u, err := url.Parse(sink.URL)
+ require.NoError(t, err)
+ return u.Path
+}
diff --git a/tests/suites/secretmanager/webhooks/helpers_test.go b/tests/suites/secretmanager/webhooks/helpers_test.go
new file mode 100644
index 0000000000..fcb9867d00
--- /dev/null
+++ b/tests/suites/secretmanager/webhooks/helpers_test.go
@@ -0,0 +1,203 @@
+package webhooks_test
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "testing"
+
+ "github.com/Infisical/infisical/tests/clients/api"
+ "github.com/Infisical/infisical/tests/fakes/webhook"
+ "github.com/Infisical/infisical/tests/fixture"
+ "github.com/Infisical/infisical/tests/harness"
+ "github.com/Infisical/infisical/tests/internal/apierr"
+ "github.com/Infisical/infisical/tests/internal/wait"
+ "github.com/stretchr/testify/require"
+)
+
+const secretModified = "secrets.modified"
+
+type hookConfig struct {
+ env string
+ path string
+ secretKey string
+ kind api.CreateWebhookJSONBodyType
+ events []api.CreateWebhookJSONBodyEventsFilterEventName
+ as *harness.Principal
+}
+
+type hookOption func(*hookConfig)
+
+func inEnv(env string) hookOption { return func(c *hookConfig) { c.env = env } }
+func atPath(p string) hookOption { return func(c *hookConfig) { c.path = p } }
+func signedWith(k string) hookOption { return func(c *hookConfig) { c.secretKey = k } }
+func slackType() hookOption {
+ return func(c *hookConfig) { c.kind = api.CreateWebhookJSONBodyTypeSlack }
+}
+func onlyEvents(events ...api.CreateWebhookJSONBodyEventsFilterEventName) hookOption {
+ return func(c *hookConfig) { c.events = events }
+}
+func createdBy(p *harness.Principal) hookOption { return func(c *hookConfig) { c.as = p } }
+
+// createHook is the create call, for a test about whether it is accepted.
+func createHook(t *testing.T, proj *fixture.Project, url string, opts ...hookOption) *api.CreateWebhookResponse {
+ t.Helper()
+ cfg := hookConfig{env: "dev", path: "/", kind: api.CreateWebhookJSONBodyTypeGeneral, as: proj.Tenant().Admin}
+ for _, o := range opts {
+ o(&cfg)
+ }
+ body := api.CreateWebhookJSONRequestBody{
+ ProjectId: proj.ID,
+ Environment: cfg.env,
+ SecretPath: &cfg.path,
+ WebhookUrl: url,
+ Type: &cfg.kind,
+ }
+ if cfg.secretKey != "" {
+ body.WebhookSecretKey = &cfg.secretKey
+ }
+ if len(cfg.events) > 0 {
+ filter := make([]struct {
+ EventName api.CreateWebhookJSONBodyEventsFilterEventName `json:"eventName"`
+ }, len(cfg.events))
+ for i, e := range cfg.events {
+ filter[i].EventName = e
+ }
+ body.EventsFilter = &filter
+ }
+ res, err := cfg.as.API.CreateWebhookWithResponse(t.Context(), body)
+ require.NoError(t, err, "creating a webhook")
+ return res
+}
+
+func newHook(t *testing.T, proj *fixture.Project, url string, opts ...hookOption) string {
+ t.Helper()
+ res := createHook(t, proj, url, opts...)
+ require.NotNilf(t, res.JSON200, "creating a webhook returned %d: %s", res.StatusCode(), apierr.Body(res.Body))
+ return res.JSON200.Webhook.Id.String()
+}
+
+// hook is a webhook as the routes return it. Decoded from the body because each
+// route's generated response is its own anonymous struct.
+type hook struct {
+ ID string `json:"id"`
+ ProjectID string `json:"projectId"`
+ SecretPath string `json:"secretPath"`
+ URL string `json:"url"`
+ Type string `json:"type"`
+ IsDisabled bool `json:"isDisabled"`
+ LastStatus *string `json:"lastStatus"`
+ LastRunErrorMessage *string `json:"lastRunErrorMessage"`
+ Environment struct {
+ Slug string `json:"slug"`
+ } `json:"environment"`
+ EventsFilter []struct {
+ EventName string `json:"eventName"`
+ } `json:"eventsFilter"`
+}
+
+func (h hook) events() []string {
+ out := []string{}
+ for _, e := range h.EventsFilter {
+ out = append(out, e.EventName)
+ }
+ return out
+}
+
+func decodeHook(t *testing.T, body []byte) hook {
+ t.Helper()
+ var out struct {
+ Webhook hook `json:"webhook"`
+ }
+ require.NoErrorf(t, json.Unmarshal(body, &out), "decoding a webhook: %s", apierr.Body(body))
+ return out.Webhook
+}
+
+func getHook(t *testing.T, proj *fixture.Project, id string) hook {
+ t.Helper()
+ res, err := proj.Tenant().Admin.API.GetWebhookByIdWithResponse(t.Context(), id)
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "reading webhook %s: %s", id, apierr.Body(res.Body))
+ return decodeHook(t, res.Body)
+}
+
+func listHooks(t *testing.T, actor *harness.Principal, proj *fixture.Project) []hook {
+ t.Helper()
+ res, err := actor.API.ListWebhooksWithResponse(t.Context(), &api.ListWebhooksParams{ProjectId: proj.ID})
+ require.NoError(t, err)
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "listing webhooks: %s", apierr.Body(res.Body))
+ var out struct {
+ Webhooks []hook `json:"webhooks"`
+ }
+ require.NoError(t, json.Unmarshal(res.Body, &out))
+ return out.Webhooks
+}
+
+func updateHook(t *testing.T, actor *harness.Principal, id string, body api.UpdateWebhookJSONRequestBody) *api.UpdateWebhookResponse {
+ t.Helper()
+ res, err := actor.API.UpdateWebhookWithResponse(t.Context(), id, body)
+ require.NoError(t, err, "updating a webhook")
+ return res
+}
+
+func disable(t *testing.T, proj *fixture.Project, id string) {
+ t.Helper()
+ res := updateHook(t, proj.Tenant().Admin, id, api.UpdateWebhookJSONRequestBody{IsDisabled: new(true)})
+ require.Equalf(t, http.StatusOK, res.StatusCode(), "disabling webhook %s: %s", id, apierr.Body(res.Body))
+}
+
+func testHook(t *testing.T, actor *harness.Principal, id string) *api.TestWebhookResponse {
+ t.Helper()
+ res, err := actor.API.TestWebhookWithResponse(t.Context(), id)
+ require.NoError(t, err, "testing a webhook")
+ return res
+}
+
+// awaitRun waits for the delivery job to record an outcome. lastStatus is written
+// only after every hook in the job was called.
+func awaitRun(t *testing.T, proj *fixture.Project, id string) hook {
+ t.Helper()
+ got, err := wait.For(t.Context(), func(ctx context.Context) (hook, bool, error) {
+ res, err := proj.Tenant().Admin.API.GetWebhookByIdWithResponse(ctx, id)
+ if err != nil || res.StatusCode() != http.StatusOK {
+ return hook{}, false, err
+ }
+ h := decodeHook(t, res.Body)
+ return h, h.LastStatus != nil, nil
+ })
+ require.NoError(t, err, "waiting for the webhook to record a run")
+ return got
+}
+
+// generalPayload is the body of a general webhook.
+type generalPayload struct {
+ Event string `json:"event"`
+ Timestamp int64 `json:"timestamp"`
+ Project struct {
+ WorkspaceID string `json:"workspaceId"`
+ ProjectID string `json:"projectId"`
+ ProjectName string `json:"projectName"`
+ Environment string `json:"environment"`
+ EnvironmentName string `json:"environmentName"`
+ SecretPath string `json:"secretPath"`
+ ChangedBy string `json:"changedBy"`
+ ChangedByActorType string `json:"changedByActorType"`
+ } `json:"project"`
+}
+
+func decodeGeneral(t *testing.T, d webhook.Delivery) generalPayload {
+ t.Helper()
+ var p generalPayload
+ require.NoErrorf(t, d.Decode(&p), "decoding a delivery: %s", d.Body)
+ return p
+}
+
+// event matches a delivery of one event type.
+func event(name string) func(webhook.DeliveryReceived) bool {
+ return func(e webhook.DeliveryReceived) bool {
+ var p struct {
+ Event string `json:"event"`
+ }
+ return e.Decode(&p) == nil && p.Event == name
+ }
+}
diff --git a/tests/suites/secretmanager/webhooks/main_test.go b/tests/suites/secretmanager/webhooks/main_test.go
new file mode 100644
index 0000000000..d3c419e954
--- /dev/null
+++ b/tests/suites/secretmanager/webhooks/main_test.go
@@ -0,0 +1,9 @@
+package webhooks_test
+
+import (
+ "testing"
+
+ "github.com/Infisical/infisical/tests/harness"
+)
+
+func TestMain(m *testing.M) { harness.Main(m, harness.Shared) }