Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(autopilots): webhook delivery layer + idempotency/signature/replay (MUL-2334) [PR1] (#2774)

Bohan Jiang2323b7271065
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 6158cb54e7..cbd1660036 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -466,11 +466,15 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/trigger", h.TriggerAutopilot)
r.Get("/runs", h.ListAutopilotRuns)
r.Get("/runs/{runId}", h.GetAutopilotRun)
+ r.Get("/deliveries", h.ListAutopilotDeliveries)
+ r.Get("/deliveries/{deliveryId}", h.GetAutopilotDelivery)
+ r.Post("/deliveries/{deliveryId}/replay", h.ReplayAutopilotDelivery)
r.Post("/triggers", h.CreateAutopilotTrigger)
r.Route("/triggers/{triggerId}", func(r chi.Router) {
r.Patch("/", h.UpdateAutopilotTrigger)
r.Delete("/", h.DeleteAutopilotTrigger)
r.Post("/rotate-webhook-token", h.RotateAutopilotTriggerWebhookToken)
+ r.Put("/signing-secret", h.SetAutopilotTriggerSigningSecret)
})
})
})
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index d3e865b0a9..aff4f14ffc 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -7,6 +7,7 @@ import (
"io"
"net/http"
"strconv"
+ "strings"
"time"
"github.com/go-chi/chi/v5"
@@ -56,11 +57,24 @@ type AutopilotTriggerResponse struct {
// MULTICA_PUBLIC_URL setting. Nil when the server has no public URL
// configured; clients then build the URL themselves from webhook_path
// plus their API base / current origin.
- WebhookURL *string `json:"webhook_url"`
- Label *string `json:"label"`
- LastFiredAt *string `json:"last_fired_at"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
+ WebhookURL *string `json:"webhook_url"`
+ // Provider names the per-endpoint signing/dedupe convention. For now:
+ // "generic" (bearer URL only, Idempotency-Key for dedupe) or "github"
+ // (X-Hub-Signature-256 + X-GitHub-Delivery). Omitted for non-webhook
+ // triggers.
+ Provider *string `json:"provider"`
+ // HasSigningSecret indicates whether a signing secret is configured on
+ // the trigger. The secret itself is never returned — it is set via a
+ // dedicated write-only endpoint. Always false for non-webhook triggers.
+ HasSigningSecret bool `json:"has_signing_secret"`
+ // SigningSecretHint is the last 4 characters of the configured secret,
+ // surfaced to help operators tell two secrets apart in the UI. Nil when
+ // no secret is configured.
+ SigningSecretHint *string `json:"signing_secret_hint"`
+ Label *string `json:"label"`
+ LastFiredAt *string `json:"last_fired_at"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
}
type AutopilotRunResponse struct {
@@ -121,10 +135,31 @@ func (h *Handler) triggerToResponse(t db.AutopilotTrigger) AutopilotTriggerRespo
full := h.cfg.PublicURL + path
resp.WebhookURL = &full
}
+ provider := t.Provider
+ if provider == "" {
+ provider = "generic"
+ }
+ resp.Provider = &provider
+ if t.SigningSecret.Valid && t.SigningSecret.String != "" {
+ resp.HasSigningSecret = true
+ hint := signingSecretHint(t.SigningSecret.String)
+ resp.SigningSecretHint = &hint
+ }
}
return resp
}
+// signingSecretHint returns the last 4 characters of the signing secret so a
+// configured-vs-rotated state is visible in the UI without exposing the
+// secret itself. Truncating below 4 chars (which the validator already
+// rejects) just returns an empty string.
+func signingSecretHint(secret string) string {
+ if len(secret) < 4 {
+ return ""
+ }
+ return secret[len(secret)-4:]
+}
+
// webhookPathForToken composes the path used by the public ingress route.
// Kept as a free function (no Handler receiver) so test code that builds
// expected URLs without instantiating a Handler can call it.
@@ -193,6 +228,22 @@ type CreateAutopilotTriggerRequest struct {
CronExpression *string `json:"cron_expression"`
Timezone *string `json:"timezone"`
Label *string `json:"label"`
+ // Provider is currently only meaningful for kind=webhook. Allowed
+ // values: "generic" (default) or "github". Unset → "generic".
+ Provider *string `json:"provider"`
+}
+
+// SetSigningSecretRequest is the body shape for PUT
+// /api/autopilots/{id}/triggers/{triggerId}/signing-secret. Lives in its own
+// type so the secret never appears alongside other fields on the trigger
+// update path — handlers that log request bodies for debugging cannot pick it
+// up by accident.
+type SetSigningSecretRequest struct {
+ // SigningSecret is the new HMAC key. Sending an empty string explicitly
+ // clears the secret (disables signature verification). Pass any
+ // reasonably entropic value — GitHub's docs recommend at least 32 random
+ // characters; we enforce a 16-char minimum on non-empty input.
+ SigningSecret string `json:"signing_secret"`
}
type UpdateAutopilotTriggerRequest struct {
@@ -496,6 +547,22 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusBadRequest, "timezone is not valid for webhook triggers")
return
}
+ // Provider only applies to webhook triggers and the value space is
+ // closed — reject unknowns early so a typo on create doesn't quietly
+ // degrade into a "generic" trigger that bypasses provider-specific
+ // dedupe / signature behaviour.
+ provider := "generic"
+ if req.Provider != nil && *req.Provider != "" {
+ if req.Kind != "webhook" {
+ writeError(w, http.StatusBadRequest, "provider is only valid for webhook triggers")
+ return
+ }
+ if !isAllowedWebhookProvider(*req.Provider) {
+ writeError(w, http.StatusBadRequest, "provider must be generic or github")
+ return
+ }
+ provider = *req.Provider
+ }
if req.Timezone != nil && *req.Timezone != "" {
if err := service.ValidateTimezone(*req.Timezone); err != nil {
@@ -533,7 +600,7 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
// entry (vanishingly unlikely with 256 bits but the retry keeps
// the failure mode obvious if RNG is degraded), we re-generate
// and re-INSERT — never UPDATE.
- trigger, err := h.createWebhookTriggerWithMintedToken(r, ap.ID, ptrToText(req.Label))
+ trigger, err := h.createWebhookTriggerWithMintedToken(r, ap.ID, ptrToText(req.Label), provider)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create trigger")
return
@@ -584,6 +651,7 @@ func (h *Handler) createWebhookTriggerWithMintedToken(
r *http.Request,
autopilotID pgtype.UUID,
label pgtype.Text,
+ provider string,
) (db.AutopilotTrigger, error) {
for attempt := 0; attempt < 3; attempt++ {
token, err := generateWebhookToken()
@@ -596,6 +664,7 @@ func (h *Handler) createWebhookTriggerWithMintedToken(
Enabled: true,
Label: label,
WebhookToken: pgtype.Text{String: token, Valid: true},
+ Provider: pgtype.Text{String: provider, Valid: provider != ""},
})
if err == nil {
return trigger, nil
@@ -607,6 +676,15 @@ func (h *Handler) createWebhookTriggerWithMintedToken(
return db.AutopilotTrigger{}, fmt.Errorf("could not mint unique webhook token")
}
+func isAllowedWebhookProvider(p string) bool {
+ switch p {
+ case "generic", "github":
+ return true
+ default:
+ return false
+ }
+}
+
func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request) {
autopilotID := chi.URLParam(r, "id")
triggerID := chi.URLParam(r, "triggerId")
@@ -821,6 +899,74 @@ func (h *Handler) RotateAutopilotTriggerWebhookToken(w http.ResponseWriter, r *h
writeJSON(w, http.StatusOK, resp)
}
+// SetAutopilotTriggerSigningSecret sets (or clears) the HMAC signing secret
+// for a webhook trigger. Lives on its own endpoint so the secret value never
+// shares a request body with any other field — keeping it out of generic
+// request-body logs and audit captures that may include patch payloads.
+//
+// Empty body / empty `signing_secret` clears the secret and reverts the
+// trigger to bearer-token-only authentication. The response carries
+// `has_signing_secret` + `signing_secret_hint`; the secret itself is never
+// echoed back, matching the GitHub / Stripe industry pattern.
+func (h *Handler) SetAutopilotTriggerSigningSecret(w http.ResponseWriter, r *http.Request) {
+ autopilotID := chi.URLParam(r, "id")
+ triggerID := chi.URLParam(r, "triggerId")
+ workspaceID := h.resolveWorkspaceID(r)
+
+ ap, ok := h.loadAutopilotInWorkspace(w, r, autopilotID, workspaceID)
+ if !ok {
+ return
+ }
+ triggerUUID, ok := parseUUIDOrBadRequest(w, triggerID, "trigger id")
+ if !ok {
+ return
+ }
+ prev, err := h.Queries.GetAutopilotTrigger(r.Context(), triggerUUID)
+ if err != nil || uuidToString(prev.AutopilotID) != uuidToString(ap.ID) {
+ writeError(w, http.StatusNotFound, "trigger not found")
+ return
+ }
+ if prev.Kind != "webhook" {
+ writeError(w, http.StatusBadRequest, "trigger is not a webhook trigger")
+ return
+ }
+
+ var req SetSigningSecretRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ secret := strings.TrimSpace(req.SigningSecret)
+ // 16 chars is the floor: enough to make brute force impractical for the
+ // SHA-256 HMAC but low enough not to reject providers that mint shorter
+ // keys (Slack signing secrets are 32 hex chars; GitHub recommends 32).
+ if secret != "" && len(secret) < 16 {
+ writeError(w, http.StatusBadRequest, "signing_secret must be at least 16 characters")
+ return
+ }
+
+ param := db.SetAutopilotTriggerSigningSecretParams{ID: triggerUUID}
+ if secret != "" {
+ param.SigningSecret = pgtype.Text{String: secret, Valid: true}
+ }
+ updated, err := h.Queries.SetAutopilotTriggerSigningSecret(r.Context(), param)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to update signing secret")
+ return
+ }
+
+ resp := h.triggerToResponse(updated)
+ userID, _ := requireUserID(w, r)
+ // Publish the trigger update so the UI can refresh the has_signing_secret
+ // badge in real time. The event payload only carries the response shape,
+ // which excludes the secret.
+ h.publish(protocol.EventAutopilotUpdated, workspaceID, "member", userID, map[string]any{
+ "autopilot_id": uuidToString(ap.ID),
+ "trigger": resp,
+ })
+ writeJSON(w, http.StatusOK, resp)
+}
+
// ── Runs ────────────────────────────────────────────────────────────────────
func (h *Handler) ListAutopilotRuns(w http.ResponseWriter, r *http.Request) {
diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.go
index 082b8c3350..df9e83c8cd 100644
--- a/server/internal/handler/autopilot_webhook.go
+++ b/server/internal/handler/autopilot_webhook.go
@@ -1,8 +1,11 @@
package handler
import (
+ "crypto/hmac"
"crypto/rand"
+ "crypto/sha256"
"encoding/base64"
+ "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -18,6 +21,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/middleware"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// maxWebhookBodyBytes is the request body size cap for webhook ingress.
@@ -45,6 +49,31 @@ func generateWebhookToken() (string, error) {
return webhookTokenPrefix + base64.RawURLEncoding.EncodeToString(b), nil
}
+// signature_status values mirror the CHECK constraint on webhook_delivery.
+const (
+ sigStatusNotRequired = "not_required"
+ sigStatusValid = "valid"
+ sigStatusInvalid = "invalid"
+ sigStatusMissing = "missing"
+)
+
+// delivery status values mirror the CHECK constraint on webhook_delivery.
+//
+// "Duplicate" is a *response* status, not a delivery status — duplicates
+// don't get their own row; they bump attempt_count on the existing dedupe
+// target. Likewise "skipped" is a *response* status reported when the
+// autopilot service skipped the run (e.g. runtime offline); the delivery
+// row itself records `dispatched` and links the skipped run via
+// autopilot_run_id, because from the ingress's perspective we DID hand
+// the payload to the autopilot machinery.
+const (
+ deliveryStatusQueued = "queued"
+ deliveryStatusDispatched = "dispatched"
+ deliveryStatusRejected = "rejected"
+ deliveryStatusIgnored = "ignored"
+ deliveryStatusFailed = "failed"
+)
+
// ── Payload normalization ───────────────────────────────────────────────────
// WebhookEnvelope is the canonical shape stored in autopilot_run.trigger_payload
@@ -139,7 +168,6 @@ func normalizeWebhookPayload(body []byte, headers http.Header) (WebhookEnvelope,
}
// inferEvent returns a best-effort event identifier from headers and body.
-// The order matches the documented inference rules in PLAN.md.
func inferEvent(headers http.Header, body any) string {
if gh := headers.Get("X-GitHub-Event"); gh != "" {
if obj, ok := body.(map[string]any); ok {
@@ -178,25 +206,139 @@ func stripBOM(b []byte) []byte {
return b
}
+// ── Dedupe + signature helpers ──────────────────────────────────────────────
+
+// extractDedupeKey returns the provider-specific idempotency identifier from
+// request headers, plus a short tag naming the header it came from. Returns
+// ("", "") when no recognised header is present.
+//
+// github -> X-GitHub-Delivery
+// generic -> Idempotency-Key
+//
+// Other providers fall back to the generic header to keep manual replays from
+// Postman / curl behaving the same way regardless of trigger config.
+func extractDedupeKey(provider string, headers http.Header) (string, string) {
+ if v := strings.TrimSpace(headers.Get("X-GitHub-Delivery")); v != "" && provider == "github" {
+ return v, "x-github-delivery"
+ }
+ if v := strings.TrimSpace(headers.Get("Idempotency-Key")); v != "" {
+ return v, "idempotency-key"
+ }
+ if v := strings.TrimSpace(headers.Get("X-GitHub-Delivery")); v != "" {
+ return v, "x-github-delivery"
+ }
+ return "", ""
+}
+
+// verifyWebhookSignatureForProvider returns one of sigStatus* describing the
+// outcome of HMAC verification for the configured trigger.
+//
+// When no signing secret is configured the result is `not_required` — the
+// trigger has opted into bearer-token-only authentication. When a secret IS
+// configured the request must carry the expected header; otherwise the
+// outcome is `missing` (caller still records a rejected delivery).
+//
+// github -> X-Hub-Signature-256: sha256=<hex>
+// generic -> X-Hub-Signature-256 (same shape; lets curl/Postman opt in)
+func verifyWebhookSignatureForProvider(provider, secret string, headers http.Header, rawBody []byte) string {
+ if secret == "" {
+ return sigStatusNotRequired
+ }
+ sig := headers.Get("X-Hub-Signature-256")
+ if sig == "" {
+ return sigStatusMissing
+ }
+ if !verifyHubSignature(secret, sig, rawBody) {
+ return sigStatusInvalid
+ }
+ _ = provider
+ return sigStatusValid
+}
+
+// verifyHubSignature implements the GitHub-compatible HMAC-SHA256 scheme:
+// `X-Hub-Signature-256: sha256=<hex(hmac(body, secret))>`. The hmac.Equal
+// comparison is constant-time so partial-prefix attacks cannot leak timing.
+func verifyHubSignature(secret, header string, body []byte) bool {
+ const prefix = "sha256="
+ if !strings.HasPrefix(header, prefix) {
+ return false
+ }
+ want, err := hex.DecodeString(strings.TrimPrefix(header, prefix))
+ if err != nil {
+ return false
+ }
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write(body)
+ return hmac.Equal(mac.Sum(nil), want)
+}
+
+// selectedHeadersJSON returns the small, debugging-friendly subset of request
+// headers we persist on a delivery row. Signature header is recorded as
+// present/absent only — never the value, so a delivery dump cannot leak the
+// HMAC of a sensitive body.
+func selectedHeadersJSON(headers http.Header) []byte {
+ out := map[string]any{}
+ add := func(name string) {
+ if v := headers.Get(name); v != "" {
+ out[strings.ToLower(name)] = v
+ }
+ }
+ add("User-Agent")
+ add("X-GitHub-Event")
+ add("X-GitHub-Delivery")
+ add("X-Gitlab-Event")
+ add("X-Event-Type")
+ add("Idempotency-Key")
+ if v := headers.Get("X-Hub-Signature-256"); v != "" {
+ out["x-hub-signature-256-present"] = true
+ }
+ b, err := json.Marshal(out)
+ if err != nil {
+ return []byte("{}")
+ }
+ return b
+}
+
// ── Public ingress ──────────────────────────────────────────────────────────
// HandleAutopilotWebhook is the public entry point for webhook-triggered
// autopilots. It runs OUTSIDE the authenticated route group: the bearer
-// token in the URL path IS the credential. Workspace context is derived
-// from the trigger row's joined autopilot.workspace_id, never from request
-// headers — that's why this handler does not call resolveWorkspaceID.
+// token in the URL path IS the credential.
+//
+// Flow (persist-first, sync-dispatch):
+//
+// 1. Per-IP rate limit (gate before any DB I/O).
+// 2. Token lookup. ErrNoRows → 404; other DB errors → 500.
+// 3. Per-token rate limit.
+// 4. Read raw body (capped). Oversized → 413.
+// 5. Normalize JSON envelope. Invalid → 400 (no persistence — there is no
+// dedupe identifier we can trust from an unparsable body).
+// 6. Extract dedupe key from headers per provider.
+// 7. Verify signature (or `not_required` when no secret is configured).
+// 8. INSERT webhook_delivery row (status=queued). On dedupe collision (23505
+// against `(trigger_id, dedupe_key)`) treat as duplicate: bump
+// attempt_count on the existing row and return its delivery_id +
+// autopilot_run_id with 200.
+// 9. If signature invalid/missing: UPDATE delivery → rejected, return 401.
+// 10. If trigger disabled / autopilot paused / archived: UPDATE delivery →
+// ignored, return 200.
+// 11. Dispatch the autopilot synchronously. UPDATE delivery → dispatched
+// (with autopilot_run_id) or failed. Return 200 (skipped runs surface
+// their `reason`).
+// 12. Bump last_fired_at after dispatch — even on the skipped path — so the
+// trigger's "last seen" is accurate.
//
// Response shapes:
-// - 200 {"status":"accepted", "run_id", "autopilot_id", "trigger_id"}
-// - 200 {"status":"skipped", "run_id", "reason"} — runtime offline at dispatch
-// - 200 {"status":"ignored", "reason":"trigger_disabled"} — disabled trigger
-// - 200 {"status":"ignored", "reason":"autopilot_paused"} — paused autopilot
-// - 200 {"status":"ignored", "reason":"autopilot_archived"} — archived autopilot
+// - 200 {"status":"accepted", "delivery_id", "run_id", "autopilot_id", "trigger_id"}
+// - 200 {"status":"skipped", "delivery_id", "run_id", "reason"}
+// - 200 {"status":"ignored", "delivery_id", "reason"}
+// - 200 {"status":"duplicate", "delivery_id", "run_id?"}
// - 400 {"error":"..."} — invalid JSON / scalar / empty
+// - 401 {"status":"rejected", "delivery_id", "reason":"..."} — signature failure
// - 404 {"error":"webhook not found"} — unknown token
// - 413 {"error":"payload too large"} — body exceeded cap
-// - 429 {"error":"rate limit exceeded"} — over per-token budget
-// - 500 {"error":"..."} — dispatch failure
+// - 429 {"error":"rate limit exceeded"} — over per-IP/token budget
+// - 500 {"error":"..."} — internal failure
func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request) {
token := chi.URLParam(r, "token")
if token == "" {
@@ -205,9 +347,8 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
}
// 1. Per-IP rate limit BEFORE we hit Postgres. Bounds the DB-probe blast
- // radius for an attacker spraying random tokens: each token gets a
- // fresh per-token bucket, so without this gate a spray turns the
- // handler into an unauthenticated index probe.
+ // radius for an attacker spraying random tokens. A spray of bad
+ // signatures still counts here — fast-path 429 stops budget burn.
if h.WebhookIPRateLimiter != nil {
if ip := h.clientIPForRateLimit(r); ip != "" {
if !h.WebhookIPRateLimiter.Allow(r.Context(), ip) {
@@ -217,11 +358,10 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
}
}
- // 2. Look up the trigger by token. Distinguish "no row" from "DB error":
- // collapsing both to 404 means a transient DB blip silently drops real
- // deliveries (providers like GitHub don't retry on 404). For the no-row
- // case we still return a generic "webhook not found" so we don't leak
- // which tokens existed at some point.
+ // 2. Token lookup. Distinguish "no row" from "DB error": collapsing both
+ // to 404 means a transient DB blip silently drops real deliveries
+ // (providers like GitHub don't retry on 404). For no-row we still
+ // return a generic message so we don't leak which tokens existed.
trigRow, err := h.Queries.GetWebhookTriggerByToken(r.Context(), pgtype.Text{String: token, Valid: true})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -233,11 +373,6 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- // Stash the resolved trigger ID on the request context so the request
- // logger can include it in the audit line without revealing the bearer
- // token in the URL path. SetWebhookTriggerID mutates *r in place so the
- // wrapping RequestLogger middleware reads the value back after
- // ServeHTTP returns — see its doc comment for why.
middleware.SetWebhookTriggerID(r, uuidToString(trigRow.ID))
// 3. Per-token rate limit.
@@ -248,25 +383,28 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
}
}
- // 4. Disabled trigger → ignored. We deliberately return 200 so the
- // sender's webhook-retry machinery doesn't keep hammering us; the
- // "ignored" status makes the no-op visible if the operator inspects
- // delivery logs.
- if !trigRow.Enabled {
- writeJSON(w, http.StatusOK, map[string]any{"status": "ignored", "reason": "trigger_disabled"})
+ // 4. Body size cap + JSON validation. http.MaxBytesReader stops the read
+ // mid-stream once the cap is exceeded so an oversized payload is
+ // rejected before being fully buffered.
+ r.Body = http.MaxBytesReader(w, r.Body, maxWebhookBodyBytes)
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ var mbe *http.MaxBytesError
+ if errors.As(err, &mbe) {
+ writeError(w, http.StatusRequestEntityTooLarge, "payload too large")
+ return
+ }
+ writeError(w, http.StatusBadRequest, "failed to read request body")
return
}
- // 5. Load Autopilot and cross-check workspace consistency. Same
- // ErrNoRows-vs-DB-error split as the token lookup above: a transient
- // DB hiccup must NOT degrade to 404, otherwise providers like GitHub
- // drop the event silently (no 5xx retry).
+ // 5. Cross-check autopilot/workspace consistency BEFORE we persist the
+ // delivery — webhook_delivery.workspace_id is NOT NULL and a stale FK
+ // row would otherwise fail INSERT after we've already paid the body
+ // read. Same ErrNoRows-vs-DB-error split as token lookup.
autopilot, err := h.Queries.GetAutopilot(r.Context(), trigRow.AutopilotID)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
- // FK invariant violation (trigger references a non-existent
- // autopilot). The FK constraint should prevent this; treat
- // as 404 if it ever happens.
writeError(w, http.StatusNotFound, "webhook not found")
return
}
@@ -278,9 +416,6 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
if uuidToString(autopilot.WorkspaceID) != uuidToString(trigRow.AutopilotWorkspaceID) {
- // This should be impossible — the join is by primary key — but
- // fail closed if it ever happens rather than dispatching against
- // the wrong workspace.
slog.Warn("webhook: trigger workspace mismatch",
"trigger_id", uuidToString(trigRow.ID),
"autopilot_id", uuidToString(autopilot.ID),
@@ -289,46 +424,108 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- if autopilot.Status == "archived" {
- writeJSON(w, http.StatusOK, map[string]any{"status": "ignored", "reason": "autopilot_archived"})
+ // 6. Normalize body. Invalid JSON → 400 without persistence: we have no
+ // dedupe identifier from the body, and replaying an unparsable payload
+ // is not useful.
+ envelope, err := normalizeWebhookPayload(body, r.Header)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
return
}
- if autopilot.Status != "active" {
- writeJSON(w, http.StatusOK, map[string]any{"status": "ignored", "reason": "autopilot_paused"})
+ envelopeBytes, err := json.Marshal(envelope)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to encode envelope")
return
}
- // 6. Body size cap + JSON validation. http.MaxBytesReader stops the
- // read mid-stream once the cap is exceeded so an oversized payload
- // is rejected before being fully buffered.
- r.Body = http.MaxBytesReader(w, r.Body, maxWebhookBodyBytes)
- body, err := io.ReadAll(r.Body)
+ // 7. Provider + dedupe + signature.
+ provider := trigRow.Provider
+ if provider == "" {
+ provider = "generic"
+ }
+ dedupeKey, dedupeSource := extractDedupeKey(provider, r.Header)
+ sigStatus := verifyWebhookSignatureForProvider(provider, trigRow.SigningSecret.String, r.Header, body)
+
+ // 8. Persist (INSERT delivery). Dedupe collision → bump existing row.
+ delivery, dup, err := h.persistInboundDelivery(r, persistDeliveryInput{
+ WorkspaceID: autopilot.WorkspaceID,
+ AutopilotID: autopilot.ID,
+ TriggerID: trigRow.ID,
+ Provider: provider,
+ Event: envelope.Event,
+ DedupeKey: dedupeKey,
+ DedupeSource: dedupeSource,
+ SignatureStatus: sigStatus,
+ ContentType: envelope.Request.ContentType,
+ RawBody: body,
+ SelectedHeaders: selectedHeadersJSON(r.Header),
+ })
if err != nil {
- var mbe *http.MaxBytesError
- if errors.As(err, &mbe) {
- writeError(w, http.StatusRequestEntityTooLarge, "payload too large")
- return
+ slog.Error("webhook: persist delivery failed",
+ "error", err,
+ "trigger_id", uuidToString(trigRow.ID),
+ )
+ writeError(w, http.StatusInternalServerError, "internal error")
+ return
+ }
+ if dup {
+ // A previous delivery already covered this dedupe key. Return the
+ // original delivery_id + (possibly empty) run_id with 200 so the
+ // caller can correlate.
+ resp := map[string]any{
+ "status": "duplicate",
+ "delivery_id": uuidToString(delivery.ID),
}
- writeError(w, http.StatusBadRequest, "failed to read request body")
+ if delivery.AutopilotRunID.Valid {
+ resp["run_id"] = uuidToString(delivery.AutopilotRunID)
+ }
+ writeJSON(w, http.StatusOK, resp)
return
}
- envelope, err := normalizeWebhookPayload(body, r.Header)
- if err != nil {
- writeError(w, http.StatusBadRequest, err.Error())
+ // 9. Signature failure → rejected delivery + 401. No dispatch, no replay.
+ // Providers will look for 4xx feedback when their secret is wrong.
+ if sigStatus == sigStatusInvalid || sigStatus == sigStatusMissing {
+ reason := "invalid_signature"
+ if sigStatus == sigStatusMissing {
+ reason = "missing_signature"
+ }
+ respBody := map[string]any{
+ "status": "rejected",
+ "delivery_id": uuidToString(delivery.ID),
+ "reason": reason,
+ }
+ h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusRejected, http.StatusUnauthorized, respBody, reason)
+ writeJSON(w, http.StatusUnauthorized, respBody)
return
}
- envelopeBytes, err := json.Marshal(envelope)
- if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to encode envelope")
+ // 10. Trigger disabled / autopilot paused / archived → ignored. We return
+ // 200 so the sender's webhook-retry machinery doesn't keep hammering
+ // us; the "ignored" status + delivery row makes the no-op visible if
+ // the operator inspects the delivery log.
+ if !trigRow.Enabled {
+ respBody := map[string]any{"status": "ignored", "delivery_id": uuidToString(delivery.ID), "reason": "trigger_disabled"}
+ h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusIgnored, http.StatusOK, respBody, "trigger_disabled")
+ writeJSON(w, http.StatusOK, respBody)
+ return
+ }
+ if autopilot.Status == "archived" {
+ respBody := map[string]any{"status": "ignored", "delivery_id": uuidToString(delivery.ID), "reason": "autopilot_archived"}
+ h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusIgnored, http.StatusOK, respBody, "autopilot_archived")
+ writeJSON(w, http.StatusOK, respBody)
+ return
+ }
+ if autopilot.Status != "active" {
+ respBody := map[string]any{"status": "ignored", "delivery_id": uuidToString(delivery.ID), "reason": "autopilot_paused"}
+ h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusIgnored, http.StatusOK, respBody, "autopilot_paused")
+ writeJSON(w, http.StatusOK, respBody)
return
}
- // 7. Dispatch. DispatchAutopilot already publishes the workspace-scoped
- // EventAutopilotRunStart, persists the payload, runs the admission
- // check (offline runtime → records a `skipped` run), and bumps
- // last_run_at. We don't add a second WS publish.
+ // 11. Dispatch synchronously. DispatchAutopilot publishes WS events,
+ // persists trigger_payload on autopilot_run, runs the admission
+ // check (offline runtime → skipped), and bumps last_run_at.
run, err := h.AutopilotService.DispatchAutopilot(
r.Context(),
autopilot,
@@ -342,13 +539,22 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
"autopilot_id", uuidToString(autopilot.ID),
"error", err,
)
- writeError(w, http.StatusInternalServerError, "failed to dispatch autopilot")
+ respBody := map[string]any{"error": "failed to dispatch autopilot"}
+ // DispatchAutopilot may return a non-nil run alongside an error
+ // (e.g. when the run row was created but the downstream dispatch
+ // failed). Link the run on the delivery anyway so the Deliveries
+ // UI can show which run row corresponds to the failure.
+ if run != nil {
+ h.finaliseDeliveryWithRun(r, delivery.ID, deliveryStatusFailed, run.ID, http.StatusInternalServerError, respBody)
+ } else {
+ h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusFailed, http.StatusInternalServerError, respBody, err.Error())
+ }
+ writeJSON(w, http.StatusInternalServerError, respBody)
return
}
- // 8. Bump last_fired_at (separate from autopilot.last_run_at). Done
- // after dispatch returns — including the skipped path — so paused
- // early-return arms above don't corrupt the meaning of "last fired".
+ // 12. Bump last_fired_at after dispatch returns — including the skipped
+ // path — so paused early-returns above don't corrupt "last fired".
if err := h.Queries.TouchAutopilotTriggerFiredAt(r.Context(), trigRow.ID); err != nil {
slog.Warn("webhook: failed to touch last_fired_at",
"trigger_id", uuidToString(trigRow.ID),
@@ -356,42 +562,170 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
)
}
- // 9. Response shape: skipped runs surface their reason
- // so providers can log it without parsing free-form text.
+ // 13. Persist the linkage delivery → run.
+ //
+ // The delivery row is always `dispatched` once we reach here: from the
+ // ingress's perspective we handed the payload off to the autopilot
+ // machinery and got a run id back. The autopilot may have skipped the
+ // run (e.g. runtime offline) — that's reflected in the response status
+ // + reason and in the linked run row, not in the delivery status. This
+ // keeps the delivery enum tight and the Deliveries UI unambiguous
+ // (`run.status` is the source of truth for what the run did).
+ respBody := map[string]any{
+ "status": "accepted",
+ "delivery_id": uuidToString(delivery.ID),
+ "run_id": uuidToString(run.ID),
+ "autopilot_id": uuidToString(autopilot.ID),
+ "trigger_id": uuidToString(trigRow.ID),
+ }
if run.Status == "skipped" {
- reason := ""
+ respBody = map[string]any{
+ "status": "skipped",
+ "delivery_id": uuidToString(delivery.ID),
+ "run_id": uuidToString(run.ID),
+ }
if run.FailureReason.Valid {
- reason = run.FailureReason.String
+ respBody["reason"] = run.FailureReason.String
}
- writeJSON(w, http.StatusOK, map[string]any{
- "status": "skipped",
- "run_id": uuidToString(run.ID),
- "reason": reason,
- })
- return
}
+ h.finaliseDeliveryWithRun(r, delivery.ID, deliveryStatusDispatched, run.ID, http.StatusOK, respBody)
- writeJSON(w, http.StatusOK, map[string]any{
- "status": "accepted",
- "run_id": uuidToString(run.ID),
- "autopilot_id": uuidToString(autopilot.ID),
- "trigger_id": uuidToString(trigRow.ID),
+ writeJSON(w, http.StatusOK, respBody)
+}
+
+// ── Persistence helpers ─────────────────────────────────────────────────────
+
+type persistDeliveryInput struct {
+ WorkspaceID pgtype.UUID
+ AutopilotID pgtype.UUID
+ TriggerID pgtype.UUID
+ Provider string
+ Event string
+ DedupeKey string
+ DedupeSource string
+ SignatureStatus string
+ ContentType string
+ RawBody []byte
+ SelectedHeaders []byte
+}
+
+// persistInboundDelivery INSERTs a fresh `queued` delivery, returning (row,
+// false, nil) on the happy path. On dedupe-key unique-violation it returns
+// (existing-row, true, nil) after bumping attempt_count on the prior row.
+// Any other error bubbles up so the handler can 500 cleanly.
+func (h *Handler) persistInboundDelivery(r *http.Request, in persistDeliveryInput) (db.WebhookDelivery, bool, error) {
+ params := db.CreateWebhookDeliveryParams{
+ WorkspaceID: in.WorkspaceID,
+ AutopilotID: in.AutopilotID,
+ TriggerID: in.TriggerID,
+ Provider: in.Provider,
+ Event: in.Event,
+ SignatureStatus: in.SignatureStatus,
+ Status: deliveryStatusQueued,
+ SelectedHeaders: in.SelectedHeaders,
+ RawBody: in.RawBody,
+ }
+ if in.DedupeKey != "" {
+ params.DedupeKey = pgtype.Text{String: in.DedupeKey, Valid: true}
+ params.DedupeSource = pgtype.Text{String: in.DedupeSource, Valid: true}
+ }
+ if in.ContentType != "" {
+ params.ContentType = pgtype.Text{String: in.ContentType, Valid: true}
+ }
+
+ delivery, err := h.Queries.CreateWebhookDelivery(r.Context(), params)
+ if err == nil {
+ return delivery, false, nil
+ }
+ if !isUniqueViolation(err) || in.DedupeKey == "" {
+ return db.WebhookDelivery{}, false, err
+ }
+ // Dedupe collision: fetch the original row, bump attempt count.
+ existing, lookupErr := h.Queries.GetWebhookDeliveryByTriggerAndDedupe(r.Context(), db.GetWebhookDeliveryByTriggerAndDedupeParams{
+ TriggerID: in.TriggerID,
+ DedupeKey: pgtype.Text{String: in.DedupeKey, Valid: true},
})
+ if lookupErr != nil {
+ return db.WebhookDelivery{}, false, fmt.Errorf("lookup duplicate delivery: %w", lookupErr)
+ }
+ bumped, bumpErr := h.Queries.BumpWebhookDeliveryAttempt(r.Context(), existing.ID)
+ if bumpErr != nil {
+ // Still treat as duplicate; just log the bump failure so the
+ // operator can investigate, returning the row we DID read.
+ slog.Warn("webhook: failed to bump attempt_count",
+ "delivery_id", uuidToString(existing.ID),
+ "error", bumpErr,
+ )
+ return existing, true, nil
+ }
+ return bumped, true, nil
+}
+
+// finaliseDeliveryTerminal records a non-dispatched outcome (rejected,
+// ignored, failed). HTTP status and full response body are captured so a
+// future Deliveries UI can show exactly what we returned.
+func (h *Handler) finaliseDeliveryTerminal(
+ r *http.Request,
+ id pgtype.UUID,
+ status string,
+ httpStatus int,
+ responseBody any,
+ errMsg string,
+) {
+ bodyJSON, _ := json.Marshal(responseBody)
+ params := db.UpdateWebhookDeliveryTerminalParams{
+ ID: id,
+ Status: status,
+ ResponseStatus: pgtype.Int4{Int32: int32(httpStatus), Valid: true},
+ ResponseBody: pgtype.Text{String: string(bodyJSON), Valid: true},
+ }
+ if errMsg != "" {
+ params.Error = pgtype.Text{String: errMsg, Valid: true}
+ }
+ if _, err := h.Queries.UpdateWebhookDeliveryTerminal(r.Context(), params); err != nil {
+ slog.Warn("webhook: finalise terminal failed",
+ "delivery_id", uuidToString(id),
+ "status", status,
+ "error", err,
+ )
+ }
}
+// finaliseDeliveryWithRun records a delivery that produced (or was admission-
+// skipped to) an autopilot_run. Same response-capture as the terminal path.
+func (h *Handler) finaliseDeliveryWithRun(
+ r *http.Request,
+ id pgtype.UUID,
+ status string,
+ runID pgtype.UUID,
+ httpStatus int,
+ responseBody any,
+) {
+ bodyJSON, _ := json.Marshal(responseBody)
+ params := db.UpdateWebhookDeliveryDispatchedParams{
+ ID: id,
+ Status: status,
+ AutopilotRunID: runID,
+ ResponseStatus: pgtype.Int4{Int32: int32(httpStatus), Valid: true},
+ ResponseBody: pgtype.Text{String: string(bodyJSON), Valid: true},
+ }
+ if _, err := h.Queries.UpdateWebhookDeliveryDispatched(r.Context(), params); err != nil {
+ slog.Warn("webhook: finalise with run failed",
+ "delivery_id", uuidToString(id),
+ "run_id", uuidToString(runID),
+ "error", err,
+ )
+ }
+}
+
+// ── Rate-limit / IP plumbing ────────────────────────────────────────────────
+
// clientIPForRateLimit returns the IP used as a rate-limit bucket key.
//
// Default behaviour: use the host portion of r.RemoteAddr. Forwarded
// headers (X-Forwarded-For, X-Real-IP) are IGNORED unless the operator
// has explicitly opted in via MULTICA_TRUSTED_PROXIES — and even then
// only when r.RemoteAddr is itself inside one of the listed CIDRs.
-//
-// Why this matters: the job of THIS limiter is to gate unauthenticated
-// token spraying before it hits the autopilot_trigger unique index. If
-// we honored XFF from anyone, an attacker could rotate the header on
-// every request, the per-IP bucket would effectively become per-request,
-// and the limiter would be bypassed. The CIDR gate forces trust to come
-// from where the operator says it does.
func (h *Handler) clientIPForRateLimit(r *http.Request) string {
remoteIP := remoteAddrHost(r.RemoteAddr)
if len(h.cfg.TrustedProxies) == 0 {
@@ -414,23 +748,16 @@ func (h *Handler) clientIPForRateLimit(r *http.Request) string {
return remoteIP
}
-// remoteAddrHost returns the host portion of an "addr" or "host:port" string.
-// IPv6 with port is "[::1]:8080" — we strip the brackets so the result is a
-// parseable IP. If the input has no port, it is returned unchanged.
func remoteAddrHost(remote string) string {
if remote == "" {
return ""
}
- // IPv6 "[::1]:port" → "::1"
if strings.HasPrefix(remote, "[") {
if end := strings.IndexByte(remote, ']'); end > 0 {
return remote[1:end]
}
}
- // IPv4 "host:port" → "host"; bare IPv4 stays.
if i := strings.LastIndexByte(remote, ':'); i >= 0 && !strings.Contains(remote, "]") {
- // Only treat the trailing ":<digits>" as a port. If there are
- // multiple colons (bare IPv6) we leave the string alone.
if strings.Count(remote, ":") == 1 {
return remote[:i]
}
@@ -438,7 +765,6 @@ func remoteAddrHost(remote string) string {
return remote
}
-// parseNetIPAddr parses an IP literal, tolerating IPv6 zone suffixes.
func parseNetIPAddr(s string) (netip.Addr, bool) {
if s == "" {
return netip.Addr{}, false
@@ -450,7 +776,6 @@ func parseNetIPAddr(s string) (netip.Addr, bool) {
return addr.Unmap(), true
}
-// addrInPrefixes reports whether addr falls into any of the CIDRs.
func addrInPrefixes(addr netip.Addr, prefixes []netip.Prefix) bool {
for _, p := range prefixes {
if p.Contains(addr) {
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index dd3dd1cc24..bde2d7fce5 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -59,6 +59,15 @@ func TestMain(m *testing.M) {
bus := events.New()
emailSvc := service.NewEmailService()
testHandler = New(queries, pool, hub, bus, emailSvc, nil, nil, analytics.NoopClient{}, Config{AllowSignup: true})
+ // httptest.NewRequest defaults RemoteAddr to 192.0.2.1, so every webhook
+ // test in the suite shares one IP bucket. With the production default
+ // (30/min) the budget runs out partway through the suite and unrelated
+ // downstream tests see a 429 from the IP gate instead of the response
+ // they're asserting. Tests that exercise rate limiting deliberately
+ // swap in a tight limiter with t.Cleanup; this generous default keeps
+ // the rest of the suite hermetic.
+ testHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 1_000_000, Window: time.Minute})
+ testHandler.WebhookIPRateLimiter = NewMemoryWebhookIPRateLimiter(WebhookRateLimit{Limit: 1_000_000, Window: time.Minute})
testPool = pool
testUserID, testWorkspaceID, err = setupHandlerTestFixture(ctx, pool)
diff --git a/server/internal/handler/webhook_delivery.go b/server/internal/handler/webhook_delivery.go
new file mode 100644
index 0000000000..f6099f370b
--- /dev/null
+++ b/server/internal/handler/webhook_delivery.go
@@ -0,0 +1,412 @@
+package handler
+
+import (
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "strconv"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// ── Response types ──────────────────────────────────────────────────────────
+
+// WebhookDeliveryResponse is the authenticated-API view of webhook_delivery.
+// The list endpoint returns these without `RawBody` / `SelectedHeaders`
+// populated; the detail endpoint includes both for debugging. We never echo
+// the signing secret or token through this surface.
+type WebhookDeliveryResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ AutopilotID string `json:"autopilot_id"`
+ TriggerID string `json:"trigger_id"`
+ Provider string `json:"provider"`
+ Event string `json:"event"`
+ DedupeKey *string `json:"dedupe_key"`
+ DedupeSource *string `json:"dedupe_source"`
+ SignatureStatus string `json:"signature_status"`
+ Status string `json:"status"`
+ AttemptCount int32 `json:"attempt_count"`
+ ContentType *string `json:"content_type"`
+ ResponseStatus *int32 `json:"response_status"`
+ AutopilotRunID *string `json:"autopilot_run_id"`
+ ReplayedFromDeliveryID *string `json:"replayed_from_delivery_id"`
+ Error *string `json:"error"`
+ ReceivedAt string `json:"received_at"`
+ LastAttemptAt string `json:"last_attempt_at"`
+ CreatedAt string `json:"created_at"`
+
+ // Detail-only fields. List responses leave these nil/empty so a page
+ // of N deliveries never serialises ~N × 256 KiB of raw bodies. Detail
+ // requests opt in by hitting GET /deliveries/{deliveryId}.
+ SelectedHeaders json.RawMessage `json:"selected_headers,omitempty"`
+ RawBody *string `json:"raw_body,omitempty"`
+ ResponseBody *string `json:"response_body,omitempty"`
+}
+
+// slimDeliveryToResponse maps the projected list row (no raw_body /
+// selected_headers / response_body) into the wire response shape.
+func slimDeliveryToResponse(d db.ListWebhookDeliveriesByAutopilotRow) WebhookDeliveryResponse {
+ resp := WebhookDeliveryResponse{
+ ID: uuidToString(d.ID),
+ WorkspaceID: uuidToString(d.WorkspaceID),
+ AutopilotID: uuidToString(d.AutopilotID),
+ TriggerID: uuidToString(d.TriggerID),
+ Provider: d.Provider,
+ Event: d.Event,
+ DedupeKey: textToPtr(d.DedupeKey),
+ DedupeSource: textToPtr(d.DedupeSource),
+ SignatureStatus: d.SignatureStatus,
+ Status: d.Status,
+ AttemptCount: d.AttemptCount,
+ ContentType: textToPtr(d.ContentType),
+ ReceivedAt: timestampToString(d.ReceivedAt),
+ LastAttemptAt: timestampToString(d.LastAttemptAt),
+ CreatedAt: timestampToString(d.CreatedAt),
+ }
+ if d.ResponseStatus.Valid {
+ v := d.ResponseStatus.Int32
+ resp.ResponseStatus = &v
+ }
+ if d.AutopilotRunID.Valid {
+ v := uuidToString(d.AutopilotRunID)
+ resp.AutopilotRunID = &v
+ }
+ if d.ReplayedFromDeliveryID.Valid {
+ v := uuidToString(d.ReplayedFromDeliveryID)
+ resp.ReplayedFromDeliveryID = &v
+ }
+ if d.Error.Valid {
+ v := d.Error.String
+ resp.Error = &v
+ }
+ return resp
+}
+
+func deliveryToResponse(d db.WebhookDelivery, detail bool) WebhookDeliveryResponse {
+ resp := WebhookDeliveryResponse{
+ ID: uuidToString(d.ID),
+ WorkspaceID: uuidToString(d.WorkspaceID),
+ AutopilotID: uuidToString(d.AutopilotID),
+ TriggerID: uuidToString(d.TriggerID),
+ Provider: d.Provider,
+ Event: d.Event,
+ DedupeKey: textToPtr(d.DedupeKey),
+ DedupeSource: textToPtr(d.DedupeSource),
+ SignatureStatus: d.SignatureStatus,
+ Status: d.Status,
+ AttemptCount: d.AttemptCount,
+ ContentType: textToPtr(d.ContentType),
+ ReceivedAt: timestampToString(d.ReceivedAt),
+ LastAttemptAt: timestampToString(d.LastAttemptAt),
+ CreatedAt: timestampToString(d.CreatedAt),
+ }
+ if d.ResponseStatus.Valid {
+ v := d.ResponseStatus.Int32
+ resp.ResponseStatus = &v
+ }
+ if d.AutopilotRunID.Valid {
+ v := uuidToString(d.AutopilotRunID)
+ resp.AutopilotRunID = &v
+ }
+ if d.ReplayedFromDeliveryID.Valid {
+ v := uuidToString(d.ReplayedFromDeliveryID)
+ resp.ReplayedFromDeliveryID = &v
+ }
+ if d.Error.Valid {
+ v := d.Error.String
+ resp.Error = &v
+ }
+ if detail {
+ if len(d.SelectedHeaders) > 0 {
+ resp.SelectedHeaders = json.RawMessage(d.SelectedHeaders)
+ }
+ if len(d.RawBody) > 0 {
+ s := string(d.RawBody)
+ resp.RawBody = &s
+ }
+ if d.ResponseBody.Valid {
+ v := d.ResponseBody.String
+ resp.ResponseBody = &v
+ }
+ }
+ return resp
+}
+
+// ── Handlers ────────────────────────────────────────────────────────────────
+
+// ListAutopilotDeliveries returns recent deliveries for an autopilot. Slim
+// projection — selected_headers / raw_body / response_body are omitted to
+// keep list responses small. Use GetAutopilotDelivery for the full payload.
+func (h *Handler) ListAutopilotDeliveries(w http.ResponseWriter, r *http.Request) {
+ autopilotID := chi.URLParam(r, "id")
+ workspaceID := h.resolveWorkspaceID(r)
+
+ autopilot, ok := h.loadAutopilotInWorkspace(w, r, autopilotID, workspaceID)
+ if !ok {
+ return
+ }
+
+ limit := int32(20)
+ offset := int32(0)
+ if l := r.URL.Query().Get("limit"); l != "" {
+ if v, err := strconv.Atoi(l); err == nil && v > 0 {
+ limit = int32(v)
+ }
+ }
+ if limit > 100 {
+ limit = 100
+ }
+ if o := r.URL.Query().Get("offset"); o != "" {
+ if v, err := strconv.Atoi(o); err == nil && v >= 0 {
+ offset = int32(v)
+ }
+ }
+
+ rows, err := h.Queries.ListWebhookDeliveriesByAutopilot(r.Context(), db.ListWebhookDeliveriesByAutopilotParams{
+ AutopilotID: autopilot.ID,
+ WorkspaceID: autopilot.WorkspaceID,
+ Limit: limit,
+ Offset: offset,
+ })
+ if err != nil {
+ slog.Error("list deliveries failed", "error", err, "autopilot_id", autopilotID)
+ writeError(w, http.StatusInternalServerError, "failed to list deliveries")
+ return
+ }
+
+ resp := make([]WebhookDeliveryResponse, len(rows))
+ for i, row := range rows {
+ resp[i] = slimDeliveryToResponse(row)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"deliveries": resp, "total": len(resp)})
+}
+
+// GetAutopilotDelivery returns one delivery in full, including the raw body
+// and headers subset. Workspace-scoped via the autopilot lookup; the
+// delivery is then re-checked to belong to that autopilot so a guessed
+// delivery id from another workspace cannot leak data.
+func (h *Handler) GetAutopilotDelivery(w http.ResponseWriter, r *http.Request) {
+ autopilotID := chi.URLParam(r, "id")
+ deliveryID := chi.URLParam(r, "deliveryId")
+ workspaceID := h.resolveWorkspaceID(r)
+
+ autopilot, ok := h.loadAutopilotInWorkspace(w, r, autopilotID, workspaceID)
+ if !ok {
+ return
+ }
+ delivery, ok := h.loadDeliveryForAutopilot(w, r, autopilot, deliveryID)
+ if !ok {
+ return
+ }
+ writeJSON(w, http.StatusOK, deliveryToResponse(delivery, true))
+}
+
+// ReplayAutopilotDelivery creates a NEW delivery row from a prior one and
+// dispatches the autopilot synchronously. The new row carries
+// `replayed_from_delivery_id` so the operator can correlate. Replay is
+// rejected for deliveries that originally failed signature verification —
+// re-running an attack payload against the autopilot would defeat the
+// rejection in the first place.
+//
+// Replays bypass per-trigger dedupe by inserting with a NULL dedupe_key:
+// reusing the original key would silently collapse the replay onto the prior
+// delivery (the partial unique index would fire). This is the intended
+// behaviour — a replay is explicitly "run this again".
+func (h *Handler) ReplayAutopilotDelivery(w http.ResponseWriter, r *http.Request) {
+ autopilotID := chi.URLParam(r, "id")
+ deliveryID := chi.URLParam(r, "deliveryId")
+ workspaceID := h.resolveWorkspaceID(r)
+
+ autopilot, ok := h.loadAutopilotInWorkspace(w, r, autopilotID, workspaceID)
+ if !ok {
+ return
+ }
+ original, ok := h.loadDeliveryForAutopilot(w, r, autopilot, deliveryID)
+ if !ok {
+ return
+ }
+ if original.Status == deliveryStatusRejected || original.SignatureStatus == sigStatusInvalid {
+ writeError(w, http.StatusBadRequest, "cannot replay a delivery that failed signature verification")
+ return
+ }
+ if len(original.RawBody) == 0 {
+ writeError(w, http.StatusBadRequest, "original delivery has no raw body to replay")
+ return
+ }
+
+ if autopilot.Status != "active" {
+ writeError(w, http.StatusBadRequest, "autopilot is not active")
+ return
+ }
+
+ trigRow, err := h.Queries.GetAutopilotTrigger(r.Context(), original.TriggerID)
+ if err != nil {
+ writeError(w, http.StatusNotFound, "trigger not found")
+ return
+ }
+ if !trigRow.Enabled {
+ writeError(w, http.StatusBadRequest, "trigger is disabled")
+ return
+ }
+
+ // Build the envelope from the stored raw body using the original headers
+ // subset for event inference. SelectedHeaders is small + JSON-shaped, so
+ // we decode it back into a header map to reuse the same normalize path.
+ headers := headersFromSelected(original.SelectedHeaders)
+ envelope, err := normalizeWebhookPayload(original.RawBody, headers)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "stored body no longer parses: "+err.Error())
+ return
+ }
+ envelopeBytes, err := json.Marshal(envelope)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to encode envelope")
+ return
+ }
+
+ contentType := ""
+ if original.ContentType.Valid {
+ contentType = original.ContentType.String
+ }
+ replay, err := h.Queries.CreateWebhookDelivery(r.Context(), db.CreateWebhookDeliveryParams{
+ WorkspaceID: autopilot.WorkspaceID,
+ AutopilotID: autopilot.ID,
+ TriggerID: original.TriggerID,
+ Provider: original.Provider,
+ Event: envelope.Event,
+ SignatureStatus: sigStatusNotRequired,
+ Status: deliveryStatusQueued,
+ SelectedHeaders: original.SelectedHeaders,
+ ContentType: pgtype.Text{String: contentType, Valid: contentType != ""},
+ RawBody: original.RawBody,
+ ReplayedFromDeliveryID: original.ID,
+ })
+ if err != nil {
+ slog.Error("replay: insert delivery failed",
+ "error", err,
+ "original_delivery_id", uuidToString(original.ID),
+ )
+ writeError(w, http.StatusInternalServerError, "failed to create replay delivery")
+ return
+ }
+
+ run, dispatchErr := h.AutopilotService.DispatchAutopilot(
+ r.Context(),
+ autopilot,
+ trigRow.ID,
+ "webhook",
+ envelopeBytes,
+ )
+ if dispatchErr != nil {
+ respBody := map[string]any{"error": "failed to dispatch autopilot"}
+ // DispatchAutopilot may return a non-nil run alongside an error
+ // (see HandleAutopilotWebhook for the same rationale). Link the
+ // run on the failed delivery so Deliveries UI can surface it.
+ if run != nil {
+ h.finaliseDeliveryWithRun(r, replay.ID, deliveryStatusFailed, run.ID, http.StatusInternalServerError, respBody)
+ } else {
+ h.finaliseDeliveryTerminal(r, replay.ID, deliveryStatusFailed, http.StatusInternalServerError, respBody, dispatchErr.Error())
+ }
+ writeError(w, http.StatusInternalServerError, dispatchErr.Error())
+ return
+ }
+
+ if err := h.Queries.TouchAutopilotTriggerFiredAt(r.Context(), trigRow.ID); err != nil {
+ slog.Warn("replay: failed to touch last_fired_at", "trigger_id", uuidToString(trigRow.ID), "error", err)
+ }
+
+ // Delivery is always `dispatched` once a run is produced — even when
+ // the run itself was skipped (e.g. runtime offline). See the comment
+ // in HandleAutopilotWebhook for the rationale.
+ respBody := map[string]any{
+ "status": "accepted",
+ "delivery_id": uuidToString(replay.ID),
+ "run_id": uuidToString(run.ID),
+ "autopilot_id": uuidToString(autopilot.ID),
+ "trigger_id": uuidToString(trigRow.ID),
+ "replayed_from_delivery_id": uuidToString(original.ID),
+ }
+ if run.Status == "skipped" {
+ respBody["status"] = "skipped"
+ if run.FailureReason.Valid {
+ respBody["reason"] = run.FailureReason.String
+ }
+ }
+ h.finaliseDeliveryWithRun(r, replay.ID, deliveryStatusDispatched, run.ID, http.StatusCreated, respBody)
+
+ final, err := h.Queries.GetWebhookDelivery(r.Context(), replay.ID)
+ if err != nil {
+ writeJSON(w, http.StatusCreated, respBody)
+ return
+ }
+ writeJSON(w, http.StatusCreated, deliveryToResponse(final, true))
+}
+
+// loadDeliveryForAutopilot returns the delivery row when it exists in the
+// same workspace AND belongs to the given autopilot. Cross-autopilot or
+// cross-workspace IDs are returned as 404 — defense in depth against ID
+// guessing.
+func (h *Handler) loadDeliveryForAutopilot(w http.ResponseWriter, r *http.Request, autopilot db.Autopilot, deliveryID string) (db.WebhookDelivery, bool) {
+ deliveryUUID, ok := parseUUIDOrBadRequest(w, deliveryID, "delivery id")
+ if !ok {
+ return db.WebhookDelivery{}, false
+ }
+ delivery, err := h.Queries.GetWebhookDeliveryInWorkspace(r.Context(), db.GetWebhookDeliveryInWorkspaceParams{
+ ID: deliveryUUID,
+ WorkspaceID: autopilot.WorkspaceID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "delivery not found")
+ return db.WebhookDelivery{}, false
+ }
+ writeError(w, http.StatusInternalServerError, "failed to load delivery")
+ return db.WebhookDelivery{}, false
+ }
+ if uuidToString(delivery.AutopilotID) != uuidToString(autopilot.ID) {
+ writeError(w, http.StatusNotFound, "delivery not found")
+ return db.WebhookDelivery{}, false
+ }
+ return delivery, true
+}
+
+// headersFromSelected decodes the small headers-subset blob back into an
+// http.Header. Only used by the replay path — fields we did not capture at
+// ingress time are simply absent, which matches what would have happened if
+// the original request had not sent them either.
+func headersFromSelected(raw []byte) http.Header {
+ out := http.Header{}
+ if len(raw) == 0 {
+ return out
+ }
+ var m map[string]any
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return out
+ }
+ canonical := map[string]string{
+ "user-agent": "User-Agent",
+ "x-github-event": "X-GitHub-Event",
+ "x-github-delivery": "X-GitHub-Delivery",
+ "x-gitlab-event": "X-Gitlab-Event",
+ "x-event-type": "X-Event-Type",
+ "idempotency-key": "Idempotency-Key",
+ }
+ for k, v := range m {
+ s, ok := v.(string)
+ if !ok {
+ continue
+ }
+ header := canonical[k]
+ if header == "" {
+ continue
+ }
+ out.Set(header, s)
+ }
+ return out
+}
diff --git a/server/internal/handler/webhook_delivery_test.go b/server/internal/handler/webhook_delivery_test.go
new file mode 100644
index 0000000000..0ce1773b8c
--- /dev/null
+++ b/server/internal/handler/webhook_delivery_test.go
@@ -0,0 +1,701 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// ── Setup helpers ───────────────────────────────────────────────────────────
+
+const testSigningSecret = "this-is-a-test-secret-32-chars-x"
+
+func setSigningSecretViaHandler(t *testing.T, apID, triggerID, secret string) {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("PUT", fmt.Sprintf("/api/autopilots/%s/triggers/%s/signing-secret", apID, triggerID), map[string]any{
+ "signing_secret": secret,
+ })
+ req = withURLParams(req, "id", apID, "triggerId", triggerID)
+ testHandler.SetAutopilotTriggerSigningSecret(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("set signing secret: %d body=%s", w.Code, w.Body.String())
+ }
+}
+
+func setTriggerProvider(t *testing.T, triggerID, provider string) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE autopilot_trigger SET provider = $1 WHERE id = $2`, provider, triggerID); err != nil {
+ t.Fatalf("set provider: %v", err)
+ }
+}
+
+func signBody(secret string, body []byte) string {
+ mac := hmac.New(sha256.New, []byte(secret))
+ mac.Write(body)
+ return "sha256=" + hex.EncodeToString(mac.Sum(nil))
+}
+
+// listDeliveries calls ListAutopilotDeliveries and decodes the body.
+func listDeliveries(t *testing.T, apID string) []map[string]any {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("GET", "/api/autopilots/"+apID+"/deliveries", nil)
+ req = withURLParam(req, "id", apID)
+ testHandler.ListAutopilotDeliveries(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("list deliveries: %d body=%s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Deliveries []map[string]any `json:"deliveries"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ return resp.Deliveries
+}
+
+// ── Tests ───────────────────────────────────────────────────────────────────
+
+func TestWebhookHandler_PersistsDeliveryOnAccept(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "DeliveryPersist Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"hello": "world"}, nil)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status: %d body=%s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp["delivery_id"] == nil {
+ t.Fatal("response should include delivery_id")
+ }
+ if resp["status"] != "accepted" {
+ t.Fatalf("status: %v", resp["status"])
+ }
+
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 1 {
+ t.Fatalf("expected 1 delivery, got %d", len(deliveries))
+ }
+ d := deliveries[0]
+ if d["status"] != "dispatched" {
+ t.Fatalf("delivery status: %v", d["status"])
+ }
+ if d["autopilot_run_id"] == nil {
+ t.Fatal("delivery should link to run")
+ }
+ if d["signature_status"] != "not_required" {
+ t.Fatalf("expected signature_status=not_required, got %v", d["signature_status"])
+ }
+}
+
+func TestWebhookHandler_DedupeViaIdempotencyKey(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "DeliveryIdem Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ body := map[string]any{"event": "demo.x", "eventPayload": map[string]any{"k": "v"}}
+ headers := map[string]string{"Idempotency-Key": "demo-key-1"}
+
+ w1 := postWebhook(t, *trig.WebhookToken, body, headers)
+ if w1.Code != http.StatusOK {
+ t.Fatalf("first: %d body=%s", w1.Code, w1.Body.String())
+ }
+ var r1 map[string]any
+ json.Unmarshal(w1.Body.Bytes(), &r1)
+ if r1["status"] != "accepted" {
+ t.Fatalf("first status: %v", r1["status"])
+ }
+ firstDeliveryID := r1["delivery_id"].(string)
+ firstRunID := r1["run_id"].(string)
+
+ // Second identical delivery should be a duplicate.
+ w2 := postWebhook(t, *trig.WebhookToken, body, headers)
+ if w2.Code != http.StatusOK {
+ t.Fatalf("second: %d body=%s", w2.Code, w2.Body.String())
+ }
+ var r2 map[string]any
+ json.Unmarshal(w2.Body.Bytes(), &r2)
+ if r2["status"] != "duplicate" {
+ t.Fatalf("expected duplicate, got %v body=%s", r2["status"], w2.Body.String())
+ }
+ if r2["delivery_id"] != firstDeliveryID {
+ t.Fatalf("duplicate delivery_id mismatch: %v != %v", r2["delivery_id"], firstDeliveryID)
+ }
+ if r2["run_id"] != firstRunID {
+ t.Fatalf("duplicate run_id mismatch: %v != %v", r2["run_id"], firstRunID)
+ }
+
+ // Only one delivery should exist; attempt_count must be 2.
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 1 {
+ t.Fatalf("expected 1 delivery (dedupe), got %d", len(deliveries))
+ }
+ if int(deliveries[0]["attempt_count"].(float64)) != 2 {
+ t.Fatalf("attempt_count: %v", deliveries[0]["attempt_count"])
+ }
+}
+
+func TestWebhookHandler_DedupeViaGitHubDelivery(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "DeliveryGH Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setTriggerProvider(t, trig.ID, "github")
+
+ body := map[string]any{"action": "opened"}
+ headers := map[string]string{
+ "X-GitHub-Event": "pull_request",
+ "X-GitHub-Delivery": "abc-123",
+ }
+
+ w1 := postWebhook(t, *trig.WebhookToken, body, headers)
+ if w1.Code != http.StatusOK {
+ t.Fatalf("first: %d", w1.Code)
+ }
+ var r1 map[string]any
+ json.Unmarshal(w1.Body.Bytes(), &r1)
+ if r1["status"] != "accepted" {
+ t.Fatalf("first status: %v", r1["status"])
+ }
+
+ w2 := postWebhook(t, *trig.WebhookToken, body, headers)
+ var r2 map[string]any
+ json.Unmarshal(w2.Body.Bytes(), &r2)
+ if r2["status"] != "duplicate" {
+ t.Fatalf("expected duplicate, got %v", r2["status"])
+ }
+
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 1 {
+ t.Fatalf("expected 1 delivery, got %d", len(deliveries))
+ }
+ if deliveries[0]["dedupe_source"] != "x-github-delivery" {
+ t.Fatalf("dedupe_source: %v", deliveries[0]["dedupe_source"])
+ }
+}
+
+func TestWebhookHandler_InvalidSignatureReturns401AndPersistsRejected(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "SigInvalid Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
+
+ body := map[string]any{"hello": "world"}
+ w := postWebhook(t, *trig.WebhookToken, body, map[string]string{
+ "X-Hub-Signature-256": "sha256=deadbeef",
+ })
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp["status"] != "rejected" {
+ t.Fatalf("status: %v", resp["status"])
+ }
+ if resp["delivery_id"] == nil {
+ t.Fatal("delivery_id should be present on rejected response")
+ }
+
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 1 {
+ t.Fatalf("expected 1 delivery, got %d", len(deliveries))
+ }
+ if deliveries[0]["status"] != "rejected" {
+ t.Fatalf("expected rejected, got %v", deliveries[0]["status"])
+ }
+ if deliveries[0]["signature_status"] != "invalid" {
+ t.Fatalf("expected signature_status=invalid, got %v", deliveries[0]["signature_status"])
+ }
+ if deliveries[0]["autopilot_run_id"] != nil {
+ t.Fatal("rejected delivery must not link to a run")
+ }
+}
+
+func TestWebhookHandler_MissingSignatureReturns401WhenSecretSet(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "SigMissing Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"hello": "world"}, nil)
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp["reason"] != "missing_signature" {
+ t.Fatalf("reason: %v", resp["reason"])
+ }
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 1 || deliveries[0]["signature_status"] != "missing" {
+ t.Fatalf("delivery missing-signature state: %#v", deliveries)
+ }
+}
+
+func TestWebhookHandler_ValidSignatureDispatches(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "SigValid Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
+
+ bodyBytes := []byte(`{"hello":"world"}`)
+ sig := signBody(testSigningSecret, bodyBytes)
+
+ w := postWebhook(t, *trig.WebhookToken, bodyBytes, map[string]string{
+ "X-Hub-Signature-256": sig,
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp["status"] != "accepted" {
+ t.Fatalf("status: %v", resp["status"])
+ }
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 1 {
+ t.Fatalf("expected 1 delivery, got %d", len(deliveries))
+ }
+ if deliveries[0]["signature_status"] != "valid" {
+ t.Fatalf("signature_status: %v", deliveries[0]["signature_status"])
+ }
+}
+
+func TestSigningSecretNotEchoedInTriggerResponse(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "SigEcho Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
+
+ // GET the autopilot — trigger response embedded.
+ w := httptest.NewRecorder()
+ req := newRequest("GET", "/api/autopilots/"+apID, nil)
+ req = withURLParam(req, "id", apID)
+ testHandler.GetAutopilot(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("get autopilot: %d", w.Code)
+ }
+ if bytes.Contains(w.Body.Bytes(), []byte(testSigningSecret)) {
+ t.Fatalf("signing secret leaked in trigger response: %s", w.Body.String())
+ }
+ if !bytes.Contains(w.Body.Bytes(), []byte(`"has_signing_secret":true`)) {
+ t.Fatalf("has_signing_secret should be true: %s", w.Body.String())
+ }
+ if !bytes.Contains(w.Body.Bytes(), []byte(`"signing_secret_hint":"`+testSigningSecret[len(testSigningSecret)-4:]+`"`)) {
+ t.Fatalf("hint should be last 4 chars: %s", w.Body.String())
+ }
+}
+
+func TestSigningSecret_MinLengthEnforced(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "SigMinLen Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ w := httptest.NewRecorder()
+ req := newRequest("PUT", "/api/autopilots/"+apID+"/triggers/"+trig.ID+"/signing-secret", map[string]any{
+ "signing_secret": "short",
+ })
+ req = withURLParams(req, "id", apID, "triggerId", trig.ID)
+ testHandler.SetAutopilotTriggerSigningSecret(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for short secret, got %d body=%s", w.Code, w.Body.String())
+ }
+}
+
+func TestSigningSecret_EmptyClearsSecret(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "SigClear Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
+
+ // Now clear with empty string.
+ w := httptest.NewRecorder()
+ req := newRequest("PUT", "/api/autopilots/"+apID+"/triggers/"+trig.ID+"/signing-secret", map[string]any{
+ "signing_secret": "",
+ })
+ req = withURLParams(req, "id", apID, "triggerId", trig.ID)
+ testHandler.SetAutopilotTriggerSigningSecret(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("clear secret: %d body=%s", w.Code, w.Body.String())
+ }
+ // Unsigned request should now go through (back to not_required).
+ post := postWebhook(t, *trig.WebhookToken, map[string]any{"x": 1}, nil)
+ if post.Code != http.StatusOK {
+ t.Fatalf("post after clear: %d body=%s", post.Code, post.Body.String())
+ }
+}
+
+func TestReplay_CreatesNewDeliveryAndDispatchesRun(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "Replay Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ // Original delivery (with dedupe key) → accepted + dispatched.
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"hello": "world"}, map[string]string{
+ "Idempotency-Key": "replay-original",
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("original: %d body=%s", w.Code, w.Body.String())
+ }
+ var orig map[string]any
+ json.Unmarshal(w.Body.Bytes(), &orig)
+ originalID := orig["delivery_id"].(string)
+ originalRunID := orig["run_id"].(string)
+
+ // Replay the original.
+ wr := httptest.NewRecorder()
+ req := newRequest("POST", fmt.Sprintf("/api/autopilots/%s/deliveries/%s/replay", apID, originalID), nil)
+ req = withURLParams(req, "id", apID, "deliveryId", originalID)
+ testHandler.ReplayAutopilotDelivery(wr, req)
+ if wr.Code != http.StatusCreated {
+ t.Fatalf("replay: %d body=%s", wr.Code, wr.Body.String())
+ }
+ var replay map[string]any
+ json.Unmarshal(wr.Body.Bytes(), &replay)
+ if replay["id"] == originalID {
+ t.Fatal("replay should create a NEW delivery, not return the original")
+ }
+ if replay["replayed_from_delivery_id"] != originalID {
+ t.Fatalf("replayed_from_delivery_id: %v", replay["replayed_from_delivery_id"])
+ }
+ if replay["autopilot_run_id"] == nil {
+ t.Fatal("replay should dispatch a run")
+ }
+ if replay["autopilot_run_id"] == originalRunID {
+ t.Fatal("replay should produce a NEW run, not reuse the original")
+ }
+
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 2 {
+ t.Fatalf("expected 2 deliveries (original + replay), got %d", len(deliveries))
+ }
+}
+
+func TestReplay_RejectsInvalidSignatureDelivery(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "ReplayReject Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
+
+ // Send an invalid-signature request → rejected delivery created.
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"x": 1}, map[string]string{
+ "X-Hub-Signature-256": "sha256=baadf00d",
+ })
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("setup: expected 401, got %d", w.Code)
+ }
+ var rej map[string]any
+ json.Unmarshal(w.Body.Bytes(), &rej)
+ rejectedID := rej["delivery_id"].(string)
+
+ // Replay the rejected delivery → 400.
+ wr := httptest.NewRecorder()
+ req := newRequest("POST", fmt.Sprintf("/api/autopilots/%s/deliveries/%s/replay", apID, rejectedID), nil)
+ req = withURLParams(req, "id", apID, "deliveryId", rejectedID)
+ testHandler.ReplayAutopilotDelivery(wr, req)
+ if wr.Code != http.StatusBadRequest {
+ t.Fatalf("replay of rejected: expected 400, got %d body=%s", wr.Code, wr.Body.String())
+ }
+}
+
+func TestGetDelivery_ReturnsFullPayload(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "DeliveryDetail Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"event": "demo", "eventPayload": map[string]any{"answer": 42}}, nil)
+ if w.Code != http.StatusOK {
+ t.Fatalf("seed: %d", w.Code)
+ }
+ var seed map[string]any
+ json.Unmarshal(w.Body.Bytes(), &seed)
+ deliveryID := seed["delivery_id"].(string)
+
+ // List response should NOT include raw_body / selected_headers.
+ wList := httptest.NewRecorder()
+ reqList := newRequest("GET", "/api/autopilots/"+apID+"/deliveries", nil)
+ reqList = withURLParam(reqList, "id", apID)
+ testHandler.ListAutopilotDeliveries(wList, reqList)
+ if bytes.Contains(wList.Body.Bytes(), []byte(`"raw_body"`)) {
+ t.Fatalf("list response should not include raw_body, body=%s", wList.Body.String())
+ }
+
+ // Detail response SHOULD include raw_body and selected_headers.
+ wDetail := httptest.NewRecorder()
+ reqDetail := newRequest("GET", "/api/autopilots/"+apID+"/deliveries/"+deliveryID, nil)
+ reqDetail = withURLParams(reqDetail, "id", apID, "deliveryId", deliveryID)
+ testHandler.GetAutopilotDelivery(wDetail, reqDetail)
+ if wDetail.Code != http.StatusOK {
+ t.Fatalf("detail: %d body=%s", wDetail.Code, wDetail.Body.String())
+ }
+ // raw_body is serialised as a JSON string (escaped); decode the response
+ // and assert against the decoded payload so we don't rely on a brittle
+ // substring search against the escaped form.
+ var detail WebhookDeliveryResponse
+ if err := json.Unmarshal(wDetail.Body.Bytes(), &detail); err != nil {
+ t.Fatalf("decode detail: %v body=%s", err, wDetail.Body.String())
+ }
+ if detail.RawBody == nil {
+ t.Fatalf("detail should include raw_body: %s", wDetail.Body.String())
+ }
+ var raw map[string]any
+ if err := json.Unmarshal([]byte(*detail.RawBody), &raw); err != nil {
+ t.Fatalf("raw_body should be valid JSON: %v body=%q", err, *detail.RawBody)
+ }
+ payload, ok := raw["eventPayload"].(map[string]any)
+ if !ok {
+ t.Fatalf("eventPayload missing or wrong type in raw_body: %#v", raw)
+ }
+ if v, ok := payload["answer"].(float64); !ok || v != 42 {
+ t.Fatalf("raw_body eventPayload.answer should be 42, got %#v", payload["answer"])
+ }
+}
+
+func TestGetDelivery_CrossAutopilotReturns404(t *testing.T) {
+ // A delivery_id from one autopilot must not be readable via another
+ // autopilot's URL — defense in depth even though both rows are in the
+ // same workspace.
+ agentID := createWebhookTestAgent(t, "CrossAP Agent")
+ apA := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ apB := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apA)
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"x": 1}, nil)
+ var seed map[string]any
+ json.Unmarshal(w.Body.Bytes(), &seed)
+ deliveryID := seed["delivery_id"].(string)
+
+ // Try reading via the OTHER autopilot's URL.
+ wDetail := httptest.NewRecorder()
+ reqDetail := newRequest("GET", "/api/autopilots/"+apB+"/deliveries/"+deliveryID, nil)
+ reqDetail = withURLParams(reqDetail, "id", apB, "deliveryId", deliveryID)
+ testHandler.GetAutopilotDelivery(wDetail, reqDetail)
+ if wDetail.Code != http.StatusNotFound {
+ t.Fatalf("cross-autopilot GET: expected 404, got %d", wDetail.Code)
+ }
+}
+
+func TestCreateAutopilotTrigger_RejectsUnknownProvider(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "ProviderInvalid Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", map[string]any{
+ "kind": "webhook",
+ "provider": "stripe",
+ })
+ req = withURLParam(req, "id", apID)
+ testHandler.CreateAutopilotTrigger(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for unknown provider, got %d body=%s", w.Code, w.Body.String())
+ }
+}
+
+func TestCreateAutopilotTrigger_AcceptsGitHubProvider(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "ProviderGH Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", map[string]any{
+ "kind": "webhook",
+ "provider": "github",
+ })
+ req = withURLParam(req, "id", apID)
+ testHandler.CreateAutopilotTrigger(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("expected 201, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp AutopilotTriggerResponse
+ json.Unmarshal(w.Body.Bytes(), &resp)
+ if resp.Provider == nil || *resp.Provider != "github" {
+ t.Fatalf("provider: %v", resp.Provider)
+ }
+}
+
+// run_only autopilots have no issue-title duplicate guard, so dedupe via
+// the delivery layer is the only thing keeping a retried provider event
+// from re-running the agent. This regression test pins that path
+// explicitly — it's the largest concrete win over the v1 ingress flow.
+func TestWebhookHandler_RunOnlyDedupeOnGitHubDelivery(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "RunOnlyDedupe Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setTriggerProvider(t, trig.ID, "github")
+
+ headers := map[string]string{
+ "X-GitHub-Event": "pull_request",
+ "X-GitHub-Delivery": "pin-redelivery",
+ }
+ body := map[string]any{"action": "opened"}
+
+ postWebhook(t, *trig.WebhookToken, body, headers)
+ postWebhook(t, *trig.WebhookToken, body, headers)
+ postWebhook(t, *trig.WebhookToken, body, headers)
+
+ // Count autopilot_run rows linked to this trigger.
+ rows, err := testHandler.Queries.ListAutopilotRuns(context.Background(), db.ListAutopilotRunsParams{
+ AutopilotID: parseUUID(apID),
+ Limit: 50,
+ Offset: 0,
+ })
+ if err != nil {
+ t.Fatalf("list runs: %v", err)
+ }
+ runCount := 0
+ for _, r := range rows {
+ if r.TriggerID.Valid && uuidToString(r.TriggerID) == trig.ID {
+ runCount++
+ }
+ }
+ if runCount != 1 {
+ t.Fatalf("expected exactly 1 run from 3 retried deliveries, got %d", runCount)
+ }
+}
+
+func TestWebhookHandler_InvalidSignatureCountsAgainstRateLimit(t *testing.T) {
+ // A stream of bad-signature attempts must not let an attacker bypass
+ // per-token rate limiting; the limiter increment happens before
+ // signature check.
+ agentID := createWebhookTestAgent(t, "SigRateLimit Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+ setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
+
+ prev := testHandler.WebhookRateLimiter
+ testHandler.WebhookRateLimiter = NewMemoryWebhookRateLimiter(WebhookRateLimit{Limit: 2, Window: 60_000_000_000})
+ t.Cleanup(func() { testHandler.WebhookRateLimiter = prev })
+
+ bad := map[string]string{"X-Hub-Signature-256": "sha256=baad"}
+ for i := 0; i < 2; i++ {
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"i": i}, bad)
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("request %d: expected 401, got %d", i, w.Code)
+ }
+ }
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"i": "third"}, bad)
+ if w.Code != http.StatusTooManyRequests {
+ t.Fatalf("third request expected 429 (rate-limited despite bad sig), got %d", w.Code)
+ }
+}
+
+func TestWebhookHandler_IgnoredPathStillPersistsDelivery(t *testing.T) {
+ // An ignored delivery (paused autopilot) must still leave a row so the
+ // operator can see "yes the request arrived, here's why we did nothing".
+ agentID := createWebhookTestAgent(t, "IgnoredPersist Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "paused", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{"x": 1}, nil)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d", w.Code)
+ }
+ deliveries := listDeliveries(t, apID)
+ if len(deliveries) != 1 {
+ t.Fatalf("expected 1 delivery on paused autopilot, got %d", len(deliveries))
+ }
+ if deliveries[0]["status"] != "ignored" {
+ t.Fatalf("status: %v", deliveries[0]["status"])
+ }
+}
+
+// A `failed` delivery (e.g. transient dispatch error) must NOT permanently
+// dedupe-block the provider's retry of the same event. GitHub keeps
+// `X-GitHub-Delivery` stable across retries; if the unique index trapped
+// the `failed` row, the second attempt would come back as `duplicate` and
+// the event would be lost.
+//
+// The handler-level failure path is hard to force in tests (most reasons
+// route through the admission check and produce a skipped run instead),
+// so we exercise the partial unique index directly: insert a `failed`
+// row, then a fresh `dispatched` row with the same dedupe_key — the
+// index excludes both `rejected` and `failed`, so both INSERTs must
+// succeed.
+func TestWebhookDelivery_FailedRowDoesNotBlockDedupe(t *testing.T) {
+ ctx := context.Background()
+ agentID := createWebhookTestAgent(t, "FailedRetry Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ first, err := testHandler.Queries.CreateWebhookDelivery(ctx, db.CreateWebhookDeliveryParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ AutopilotID: parseUUID(apID),
+ TriggerID: parseUUID(trig.ID),
+ Provider: "github",
+ Event: "github.pull_request",
+ SignatureStatus: "not_required",
+ Status: "failed",
+ SelectedHeaders: []byte("{}"),
+ DedupeKey: pgtype.Text{String: "retry-key", Valid: true},
+ DedupeSource: pgtype.Text{String: "x-github-delivery", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("insert failed row: %v", err)
+ }
+
+ // Same dedupe_key, status=dispatched. Must succeed: the partial unique
+ // index excludes both `rejected` and `failed`, so the prior `failed`
+ // row does not consume the slot.
+ second, err := testHandler.Queries.CreateWebhookDelivery(ctx, db.CreateWebhookDeliveryParams{
+ WorkspaceID: parseUUID(testWorkspaceID),
+ AutopilotID: parseUUID(apID),
+ TriggerID: parseUUID(trig.ID),
+ Provider: "github",
+ Event: "github.pull_request",
+ SignatureStatus: "not_required",
+ Status: "dispatched",
+ SelectedHeaders: []byte("{}"),
+ DedupeKey: pgtype.Text{String: "retry-key", Valid: true},
+ DedupeSource: pgtype.Text{String: "x-github-delivery", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("retry insert blocked by stale failed row: %v", err)
+ }
+ if uuidToString(second.ID) == uuidToString(first.ID) {
+ t.Fatal("retry should produce a fresh row, not reuse the failed one")
+ }
+
+ // And the dedupe lookup MUST prefer the non-terminal (dispatched) row,
+ // not the stale `failed` one, so a third attempt collapses onto the
+ // successful delivery rather than the failure.
+ got, err := testHandler.Queries.GetWebhookDeliveryByTriggerAndDedupe(ctx,
+ db.GetWebhookDeliveryByTriggerAndDedupeParams{
+ TriggerID: parseUUID(trig.ID),
+ DedupeKey: pgtype.Text{String: "retry-key", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("lookup: %v", err)
+ }
+ if got.Status != "dispatched" {
+ t.Fatalf("lookup should prefer non-terminal row, got status=%q (id=%s)",
+ got.Status, uuidToString(got.ID))
+ }
+}
+
+// Confirm a column-level write — sqlc params for narg('signing_secret')
+// must allow nullable NULL to clear the column, not just non-NULL strings.
+func TestSetSigningSecretParams_NullableWrite(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "SigSqlcNull Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ if _, err := testHandler.Queries.SetAutopilotTriggerSigningSecret(context.Background(),
+ db.SetAutopilotTriggerSigningSecretParams{
+ ID: parseUUID(trig.ID),
+ SigningSecret: pgtype.Text{}, // explicit NULL
+ }); err != nil {
+ t.Fatalf("sqlc NULL write: %v", err)
+ }
+}
diff --git a/server/migrations/093_webhook_deliveries.down.sql b/server/migrations/093_webhook_deliveries.down.sql
new file mode 100644
index 0000000000..5ffa5bd8b9
--- /dev/null
+++ b/server/migrations/093_webhook_deliveries.down.sql
@@ -0,0 +1,5 @@
+DROP TABLE IF EXISTS webhook_delivery;
+
+ALTER TABLE autopilot_trigger
+ DROP COLUMN IF EXISTS signing_secret,
+ DROP COLUMN IF EXISTS provider;
diff --git a/server/migrations/093_webhook_deliveries.up.sql b/server/migrations/093_webhook_deliveries.up.sql
new file mode 100644
index 0000000000..fc640f9a28
--- /dev/null
+++ b/server/migrations/093_webhook_deliveries.up.sql
@@ -0,0 +1,97 @@
+-- Webhook delivery layer: separates "we received an inbound HTTP webhook" from
+-- "we created an autopilot run". Splitting the two lets us record duplicate
+-- attempts, signature outcomes, ignored/skipped deliveries, and offers a
+-- replay path — all of which the previous shape (writing straight into
+-- autopilot_run.trigger_payload) could not express.
+--
+-- Scope of this migration:
+-- 1. Add `provider` + `signing_secret` to autopilot_trigger so a webhook
+-- trigger can optionally carry per-provider configuration for signature
+-- verification. signing_secret is plaintext at rest, mirroring how
+-- webhook_token already lives — HMAC verification needs the cleartext
+-- and there is no general secrets-at-rest infrastructure to layer on
+-- yet (see issue MUL-2334 for the design rationale).
+-- 2. Create webhook_delivery, one row per inbound HTTP request the public
+-- ingress endpoint accepted (including rejected / ignored outcomes).
+-- Duplicate requests don't get their own row — they bump attempt_count
+-- on the existing dedupe target. The autopilot_run table is kept intact
+-- and continues to represent the downstream execution — both views are
+-- needed.
+
+ALTER TABLE autopilot_trigger
+ ADD COLUMN provider TEXT NOT NULL DEFAULT 'generic'
+ CHECK (provider IN ('generic', 'github')),
+ ADD COLUMN signing_secret TEXT;
+
+CREATE TABLE IF NOT EXISTS webhook_delivery (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ autopilot_id UUID NOT NULL REFERENCES autopilot(id) ON DELETE CASCADE,
+ trigger_id UUID NOT NULL REFERENCES autopilot_trigger(id) ON DELETE CASCADE,
+ provider TEXT NOT NULL
+ CHECK (provider IN ('generic', 'github')),
+ event TEXT NOT NULL DEFAULT 'webhook.received',
+ -- dedupe_key is extracted from request headers per-provider:
+ -- github -> X-GitHub-Delivery
+ -- generic -> Idempotency-Key
+ -- NULL means "no provider-supplied dedupe identifier"; the partial unique
+ -- index below skips these rows so each NULL-keyed delivery is treated as
+ -- distinct (correct behavior for clients that don't implement idempotency
+ -- headers — the alternative would collapse all of them onto one row).
+ dedupe_key TEXT,
+ dedupe_source TEXT,
+ signature_status TEXT NOT NULL DEFAULT 'not_required'
+ CHECK (signature_status IN ('not_required', 'valid', 'invalid', 'missing')),
+ -- Delivery status tracks the *ingress*, not the autopilot run:
+ -- queued — INSERTed, dispatch not yet attempted
+ -- dispatched — handed off to AutopilotService; autopilot_run_id is set.
+ -- A run that was admission-skipped (e.g. runtime offline)
+ -- still lives here — the skipped-ness is recorded on
+ -- autopilot_run.status, not on the delivery, so the
+ -- Deliveries enum stays unambiguous.
+ -- rejected — signature verification failed (invalid or missing)
+ -- ignored — trigger disabled / autopilot paused / archived
+ -- failed — dispatch attempted and errored
+ status TEXT NOT NULL DEFAULT 'queued'
+ CHECK (status IN ('queued', 'dispatched', 'rejected', 'ignored', 'failed')),
+ attempt_count INTEGER NOT NULL DEFAULT 1,
+ -- Selected headers we want to keep for debugging (user-agent, event,
+ -- delivery id, idempotency key, signature presence). NOT the raw header
+ -- map — never store auth tokens or signature values plaintext.
+ selected_headers JSONB NOT NULL DEFAULT '{}'::jsonb,
+ content_type TEXT,
+ -- raw_body holds the exact bytes we received, capped at the ingress body
+ -- limit (256 KiB). Required for replay and to debug normalization issues.
+ -- No TTL/retention enforced here; if delivery volume becomes a storage
+ -- concern, add a follow-up migration with a retention job rather than
+ -- baking the policy into the schema.
+ raw_body BYTEA,
+ response_status INTEGER,
+ response_body TEXT,
+ autopilot_run_id UUID REFERENCES autopilot_run(id) ON DELETE SET NULL,
+ replayed_from_delivery_id UUID REFERENCES webhook_delivery(id) ON DELETE SET NULL,
+ error TEXT,
+ received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ last_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+-- Listing deliveries per autopilot, newest first.
+CREATE INDEX IF NOT EXISTS idx_webhook_delivery_autopilot
+ ON webhook_delivery(autopilot_id, created_at DESC);
+
+-- Provider-supplied dedupe identifiers must be unique per trigger. Partial so
+-- that NULL keys (no Idempotency-Key / X-GitHub-Delivery header) never
+-- collide. Terminal-but-not-successful outcomes (`rejected`, `failed`) are
+-- excluded so a transient ingress failure or a misconfigured secret does
+-- not strand the operator: providers like GitHub keep X-GitHub-Delivery
+-- stable across retries, and a permanently-blocking row would prevent the
+-- next retry from ever being dispatched.
+CREATE UNIQUE INDEX IF NOT EXISTS idx_webhook_delivery_dedupe
+ ON webhook_delivery(trigger_id, dedupe_key)
+ WHERE dedupe_key IS NOT NULL AND status NOT IN ('rejected', 'failed');
+
+-- Lookup by linked run (sync flows, gc check, run-detail "what triggered me").
+CREATE INDEX IF NOT EXISTS idx_webhook_delivery_run
+ ON webhook_delivery(autopilot_run_id)
+ WHERE autopilot_run_id IS NOT NULL;
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index a2ddc58740..3264cc29a8 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -1,6 +1,6 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
-// sqlc v1.31.1
+// sqlc v1.30.0
// source: autopilot.sql
package db
@@ -40,7 +40,7 @@ WHERE t.autopilot_id = a.id
AND t.next_run_at IS NOT NULL
AND t.next_run_at <= now()
AND a.status = 'active'
-RETURNING t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, a.workspace_id AS autopilot_workspace_id
+RETURNING t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, a.workspace_id AS autopilot_workspace_id
`
type ClaimDueScheduleTriggersRow struct {
@@ -56,6 +56,8 @@ type ClaimDueScheduleTriggersRow struct {
LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Provider string `json:"provider"`
+ SigningSecret pgtype.Text `json:"signing_secret"`
AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
}
@@ -86,6 +88,8 @@ func (q *Queries) ClaimDueScheduleTriggers(ctx context.Context) ([]ClaimDueSched
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
&i.AutopilotWorkspaceID,
); err != nil {
return nil, err
@@ -260,11 +264,12 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa
const createAutopilotTrigger = `-- name: CreateAutopilotTrigger :one
INSERT INTO autopilot_trigger (
autopilot_id, kind, enabled, cron_expression, timezone,
- next_run_at, webhook_token, label
+ next_run_at, webhook_token, label, provider
) VALUES (
$1, $2, $3, $4, $5,
- $6, $7, $8
-) RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at
+ $6, $7, $8,
+ COALESCE($9::text, 'generic')
+) RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret
`
type CreateAutopilotTriggerParams struct {
@@ -276,6 +281,7 @@ type CreateAutopilotTriggerParams struct {
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
WebhookToken pgtype.Text `json:"webhook_token"`
Label pgtype.Text `json:"label"`
+ Provider pgtype.Text `json:"provider"`
}
func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilotTriggerParams) (AutopilotTrigger, error) {
@@ -288,6 +294,7 @@ func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilo
arg.NextRunAt,
arg.WebhookToken,
arg.Label,
+ arg.Provider,
)
var i AutopilotTrigger
err := row.Scan(
@@ -303,6 +310,8 @@ func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilo
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
)
return i, err
}
@@ -454,7 +463,7 @@ func (q *Queries) GetAutopilotRunByIssue(ctx context.Context, issueID pgtype.UUI
}
const getAutopilotTrigger = `-- name: GetAutopilotTrigger :one
-SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at FROM autopilot_trigger
+SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret FROM autopilot_trigger
WHERE id = $1
`
@@ -474,12 +483,14 @@ func (q *Queries) GetAutopilotTrigger(ctx context.Context, id pgtype.UUID) (Auto
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
)
return i, err
}
const getWebhookTriggerByToken = `-- name: GetWebhookTriggerByToken :one
-SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, a.workspace_id AS autopilot_workspace_id
+SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, a.workspace_id AS autopilot_workspace_id
FROM autopilot_trigger t
JOIN autopilot a ON a.id = t.autopilot_id
WHERE t.kind = 'webhook'
@@ -499,6 +510,8 @@ type GetWebhookTriggerByTokenRow struct {
LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Provider string `json:"provider"`
+ SigningSecret pgtype.Text `json:"signing_secret"`
AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
}
@@ -523,6 +536,8 @@ func (q *Queries) GetWebhookTriggerByToken(ctx context.Context, webhookToken pgt
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
&i.AutopilotWorkspaceID,
)
return i, err
@@ -577,7 +592,7 @@ func (q *Queries) ListAutopilotRuns(ctx context.Context, arg ListAutopilotRunsPa
const listAutopilotTriggers = `-- name: ListAutopilotTriggers :many
-SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at FROM autopilot_trigger
+SELECT id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret FROM autopilot_trigger
WHERE autopilot_id = $1
ORDER BY created_at ASC
`
@@ -607,6 +622,8 @@ func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
); err != nil {
return nil, err
}
@@ -670,7 +687,7 @@ func (q *Queries) ListAutopilots(ctx context.Context, arg ListAutopilotsParams)
const recoverLostTriggers = `-- name: RecoverLostTriggers :many
-SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, a.workspace_id AS autopilot_workspace_id
+SELECT t.id, t.autopilot_id, t.kind, t.enabled, t.cron_expression, t.timezone, t.next_run_at, t.webhook_token, t.label, t.last_fired_at, t.created_at, t.updated_at, t.provider, t.signing_secret, a.workspace_id AS autopilot_workspace_id
FROM autopilot_trigger t
JOIN autopilot a ON t.autopilot_id = a.id
WHERE t.kind = 'schedule'
@@ -693,6 +710,8 @@ type RecoverLostTriggersRow struct {
LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Provider string `json:"provider"`
+ SigningSecret pgtype.Text `json:"signing_secret"`
AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
}
@@ -724,6 +743,8 @@ func (q *Queries) RecoverLostTriggers(ctx context.Context) ([]RecoverLostTrigger
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
&i.AutopilotWorkspaceID,
); err != nil {
return nil, err
@@ -742,7 +763,7 @@ SET webhook_token = $2,
updated_at = now()
WHERE id = $1
AND kind = 'webhook'
-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at
+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret
`
type RotateAutopilotTriggerWebhookTokenParams struct {
@@ -769,6 +790,8 @@ func (q *Queries) RotateAutopilotTriggerWebhookToken(ctx context.Context, arg Ro
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
)
return i, err
}
@@ -855,12 +878,53 @@ func (q *Queries) SelectAutopilotsExceedingFailureThreshold(ctx context.Context,
return items, nil
}
+const setAutopilotTriggerSigningSecret = `-- name: SetAutopilotTriggerSigningSecret :one
+UPDATE autopilot_trigger
+SET signing_secret = $2,
+ updated_at = now()
+WHERE id = $1
+ AND kind = 'webhook'
+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret
+`
+
+type SetAutopilotTriggerSigningSecretParams struct {
+ ID pgtype.UUID `json:"id"`
+ SigningSecret pgtype.Text `json:"signing_secret"`
+}
+
+// Writes the signing secret for a webhook trigger. Kept as a dedicated query
+// (not a field on UpdateAutopilotTrigger) so the request body for the
+// write-only endpoint only ever carries the secret value, with no risk of an
+// accidental log line leaking it alongside other fields. Restricted to
+// webhook triggers to avoid corrupting unrelated state.
+func (q *Queries) SetAutopilotTriggerSigningSecret(ctx context.Context, arg SetAutopilotTriggerSigningSecretParams) (AutopilotTrigger, error) {
+ row := q.db.QueryRow(ctx, setAutopilotTriggerSigningSecret, arg.ID, arg.SigningSecret)
+ var i AutopilotTrigger
+ err := row.Scan(
+ &i.ID,
+ &i.AutopilotID,
+ &i.Kind,
+ &i.Enabled,
+ &i.CronExpression,
+ &i.Timezone,
+ &i.NextRunAt,
+ &i.WebhookToken,
+ &i.Label,
+ &i.LastFiredAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
+ )
+ return i, err
+}
+
const setAutopilotTriggerWebhookToken = `-- name: SetAutopilotTriggerWebhookToken :one
UPDATE autopilot_trigger
SET webhook_token = $2,
updated_at = now()
WHERE id = $1
-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at
+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret
`
type SetAutopilotTriggerWebhookTokenParams struct {
@@ -889,6 +953,8 @@ func (q *Queries) SetAutopilotTriggerWebhookToken(ctx context.Context, arg SetAu
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
)
return i, err
}
@@ -1220,7 +1286,7 @@ UPDATE autopilot_trigger SET
label = COALESCE($6, label),
updated_at = now()
WHERE id = $1
-RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at
+RETURNING id, autopilot_id, kind, enabled, cron_expression, timezone, next_run_at, webhook_token, label, last_fired_at, created_at, updated_at, provider, signing_secret
`
type UpdateAutopilotTriggerParams struct {
@@ -1255,6 +1321,8 @@ func (q *Queries) UpdateAutopilotTrigger(ctx context.Context, arg UpdateAutopilo
&i.LastFiredAt,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.Provider,
+ &i.SigningSecret,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 62dbc8e938..2a7f7e2004 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -158,6 +158,8 @@ type AutopilotTrigger struct {
LastFiredAt pgtype.Timestamptz `json:"last_fired_at"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Provider string `json:"provider"`
+ SigningSecret pgtype.Text `json:"signing_secret"`
}
type ChatMessage struct {
@@ -604,6 +606,31 @@ type VerificationCode struct {
Attempts int32 `json:"attempts"`
}
+type WebhookDelivery struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ Provider string `json:"provider"`
+ Event string `json:"event"`
+ DedupeKey pgtype.Text `json:"dedupe_key"`
+ DedupeSource pgtype.Text `json:"dedupe_source"`
+ SignatureStatus string `json:"signature_status"`
+ Status string `json:"status"`
+ AttemptCount int32 `json:"attempt_count"`
+ SelectedHeaders []byte `json:"selected_headers"`
+ ContentType pgtype.Text `json:"content_type"`
+ RawBody []byte `json:"raw_body"`
+ ResponseStatus pgtype.Int4 `json:"response_status"`
+ ResponseBody pgtype.Text `json:"response_body"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ ReplayedFromDeliveryID pgtype.UUID `json:"replayed_from_delivery_id"`
+ Error pgtype.Text `json:"error"`
+ ReceivedAt pgtype.Timestamptz `json:"received_at"`
+ LastAttemptAt pgtype.Timestamptz `json:"last_attempt_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type Workspace struct {
ID pgtype.UUID `json:"id"`
Name string `json:"name"`
diff --git a/server/pkg/db/generated/webhook_delivery.sql.go b/server/pkg/db/generated/webhook_delivery.sql.go
new file mode 100644
index 0000000000..adac4348b5
--- /dev/null
+++ b/server/pkg/db/generated/webhook_delivery.sql.go
@@ -0,0 +1,473 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.30.0
+// source: webhook_delivery.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const bumpWebhookDeliveryAttempt = `-- name: BumpWebhookDeliveryAttempt :one
+UPDATE webhook_delivery
+SET attempt_count = attempt_count + 1,
+ last_attempt_at = now()
+WHERE id = $1
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at
+`
+
+// On duplicate detection, bump attempt_count and refresh last_attempt_at on
+// the existing delivery so the UI / operator can see retry pressure without
+// creating a new row per attempt.
+func (q *Queries) BumpWebhookDeliveryAttempt(ctx context.Context, id pgtype.UUID) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, bumpWebhookDeliveryAttempt, id)
+ var i WebhookDelivery
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.SelectedHeaders,
+ &i.ContentType,
+ &i.RawBody,
+ &i.ResponseStatus,
+ &i.ResponseBody,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const createWebhookDelivery = `-- name: CreateWebhookDelivery :one
+
+INSERT INTO webhook_delivery (
+ workspace_id, autopilot_id, trigger_id, provider, event,
+ dedupe_key, dedupe_source, signature_status, status,
+ selected_headers, content_type, raw_body,
+ replayed_from_delivery_id
+) VALUES (
+ $1, $2, $3, $4, $5,
+ $9, $10, $6, $7,
+ $8, $11, $12,
+ $13
+) RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at
+`
+
+type CreateWebhookDeliveryParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ Provider string `json:"provider"`
+ Event string `json:"event"`
+ SignatureStatus string `json:"signature_status"`
+ Status string `json:"status"`
+ SelectedHeaders []byte `json:"selected_headers"`
+ DedupeKey pgtype.Text `json:"dedupe_key"`
+ DedupeSource pgtype.Text `json:"dedupe_source"`
+ ContentType pgtype.Text `json:"content_type"`
+ RawBody []byte `json:"raw_body"`
+ ReplayedFromDeliveryID pgtype.UUID `json:"replayed_from_delivery_id"`
+}
+
+// =====================
+// Webhook Delivery
+// =====================
+// Inserts a delivery row. On dedupe-key collision the unique partial index
+// (trigger_id, dedupe_key) raises 23505 and the handler treats it as
+// "duplicate" rather than an error.
+func (q *Queries) CreateWebhookDelivery(ctx context.Context, arg CreateWebhookDeliveryParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, createWebhookDelivery,
+ arg.WorkspaceID,
+ arg.AutopilotID,
+ arg.TriggerID,
+ arg.Provider,
+ arg.Event,
+ arg.SignatureStatus,
+ arg.Status,
+ arg.SelectedHeaders,
+ arg.DedupeKey,
+ arg.DedupeSource,
+ arg.ContentType,
+ arg.RawBody,
+ arg.ReplayedFromDeliveryID,
+ )
+ var i WebhookDelivery
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.SelectedHeaders,
+ &i.ContentType,
+ &i.RawBody,
+ &i.ResponseStatus,
+ &i.ResponseBody,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const getWebhookDelivery = `-- name: GetWebhookDelivery :one
+SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at FROM webhook_delivery
+WHERE id = $1
+`
+
+func (q *Queries) GetWebhookDelivery(ctx context.Context, id pgtype.UUID) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, getWebhookDelivery, id)
+ var i WebhookDelivery
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.SelectedHeaders,
+ &i.ContentType,
+ &i.RawBody,
+ &i.ResponseStatus,
+ &i.ResponseBody,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const getWebhookDeliveryByTriggerAndDedupe = `-- name: GetWebhookDeliveryByTriggerAndDedupe :one
+SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at FROM webhook_delivery
+WHERE trigger_id = $1
+ AND dedupe_key = $2
+ORDER BY (status IN ('rejected', 'failed')), created_at DESC
+LIMIT 1
+`
+
+type GetWebhookDeliveryByTriggerAndDedupeParams struct {
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ DedupeKey pgtype.Text `json:"dedupe_key"`
+}
+
+// Looks up the existing delivery for a (trigger, dedupe_key) pair so that
+// duplicate requests return the original delivery_id / autopilot_run_id.
+// The partial unique index excludes terminal-but-not-successful statuses
+// (`rejected`, `failed`), so multiple such rows can coexist for the same
+// key. Prefer non-terminal rows in the lookup: without the ORDER BY we
+// could return a stale rejection / failure even after the operator fixed
+// the cause and a fresh dispatch succeeded.
+func (q *Queries) GetWebhookDeliveryByTriggerAndDedupe(ctx context.Context, arg GetWebhookDeliveryByTriggerAndDedupeParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, getWebhookDeliveryByTriggerAndDedupe, arg.TriggerID, arg.DedupeKey)
+ var i WebhookDelivery
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.SelectedHeaders,
+ &i.ContentType,
+ &i.RawBody,
+ &i.ResponseStatus,
+ &i.ResponseBody,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const getWebhookDeliveryInWorkspace = `-- name: GetWebhookDeliveryInWorkspace :one
+SELECT id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at FROM webhook_delivery
+WHERE id = $1 AND workspace_id = $2
+`
+
+type GetWebhookDeliveryInWorkspaceParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Workspace-scoped read for authenticated detail / replay endpoints.
+func (q *Queries) GetWebhookDeliveryInWorkspace(ctx context.Context, arg GetWebhookDeliveryInWorkspaceParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, getWebhookDeliveryInWorkspace, arg.ID, arg.WorkspaceID)
+ var i WebhookDelivery
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.SelectedHeaders,
+ &i.ContentType,
+ &i.RawBody,
+ &i.ResponseStatus,
+ &i.ResponseBody,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const listWebhookDeliveriesByAutopilot = `-- name: ListWebhookDeliveriesByAutopilot :many
+SELECT
+ d.id, d.workspace_id, d.autopilot_id, d.trigger_id, d.provider, d.event,
+ d.dedupe_key, d.dedupe_source, d.signature_status, d.status,
+ d.attempt_count, d.content_type, d.response_status,
+ d.autopilot_run_id, d.replayed_from_delivery_id, d.error,
+ d.received_at, d.last_attempt_at, d.created_at
+FROM webhook_delivery d
+JOIN autopilot a ON a.id = d.autopilot_id
+WHERE d.autopilot_id = $1
+ AND a.workspace_id = $2
+ORDER BY d.created_at DESC
+LIMIT $3 OFFSET $4
+`
+
+type ListWebhookDeliveriesByAutopilotParams struct {
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Limit int32 `json:"limit"`
+ Offset int32 `json:"offset"`
+}
+
+type ListWebhookDeliveriesByAutopilotRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AutopilotID pgtype.UUID `json:"autopilot_id"`
+ TriggerID pgtype.UUID `json:"trigger_id"`
+ Provider string `json:"provider"`
+ Event string `json:"event"`
+ DedupeKey pgtype.Text `json:"dedupe_key"`
+ DedupeSource pgtype.Text `json:"dedupe_source"`
+ SignatureStatus string `json:"signature_status"`
+ Status string `json:"status"`
+ AttemptCount int32 `json:"attempt_count"`
+ ContentType pgtype.Text `json:"content_type"`
+ ResponseStatus pgtype.Int4 `json:"response_status"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ ReplayedFromDeliveryID pgtype.UUID `json:"replayed_from_delivery_id"`
+ Error pgtype.Text `json:"error"`
+ ReceivedAt pgtype.Timestamptz `json:"received_at"`
+ LastAttemptAt pgtype.Timestamptz `json:"last_attempt_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+// Workspace-scoped via the join so a runId from another workspace cannot
+// leak. Newest first, paged by limit/offset.
+//
+// Projection: large columns (`raw_body`, `selected_headers`, `response_body`)
+// are deliberately excluded. A 100-row page × 256 KiB raw_body would be
+// 25 MiB of bytes pulled from Postgres just to be dropped in the JSON
+// encoder — Deliveries tab would hit that on every reload. Detail views
+// fetch the full row via GetWebhookDelivery / GetWebhookDeliveryInWorkspace.
+func (q *Queries) ListWebhookDeliveriesByAutopilot(ctx context.Context, arg ListWebhookDeliveriesByAutopilotParams) ([]ListWebhookDeliveriesByAutopilotRow, error) {
+ rows, err := q.db.Query(ctx, listWebhookDeliveriesByAutopilot,
+ arg.AutopilotID,
+ arg.WorkspaceID,
+ arg.Limit,
+ arg.Offset,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListWebhookDeliveriesByAutopilotRow{}
+ for rows.Next() {
+ var i ListWebhookDeliveriesByAutopilotRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.ContentType,
+ &i.ResponseStatus,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const updateWebhookDeliveryDispatched = `-- name: UpdateWebhookDeliveryDispatched :one
+UPDATE webhook_delivery
+SET status = $2,
+ autopilot_run_id = $3,
+ response_status = $4,
+ response_body = $5,
+ last_attempt_at = now()
+WHERE id = $1
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at
+`
+
+type UpdateWebhookDeliveryDispatchedParams struct {
+ ID pgtype.UUID `json:"id"`
+ Status string `json:"status"`
+ AutopilotRunID pgtype.UUID `json:"autopilot_run_id"`
+ ResponseStatus pgtype.Int4 `json:"response_status"`
+ ResponseBody pgtype.Text `json:"response_body"`
+}
+
+// Finalises a delivery that successfully created (or skipped to) an
+// autopilot_run. response_status is the HTTP status we returned, recorded
+// alongside so the operator can correlate logs.
+func (q *Queries) UpdateWebhookDeliveryDispatched(ctx context.Context, arg UpdateWebhookDeliveryDispatchedParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, updateWebhookDeliveryDispatched,
+ arg.ID,
+ arg.Status,
+ arg.AutopilotRunID,
+ arg.ResponseStatus,
+ arg.ResponseBody,
+ )
+ var i WebhookDelivery
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.SelectedHeaders,
+ &i.ContentType,
+ &i.RawBody,
+ &i.ResponseStatus,
+ &i.ResponseBody,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
+
+const updateWebhookDeliveryTerminal = `-- name: UpdateWebhookDeliveryTerminal :one
+UPDATE webhook_delivery
+SET status = $2,
+ error = $3,
+ response_status = $4,
+ response_body = $5,
+ last_attempt_at = now()
+WHERE id = $1
+RETURNING id, workspace_id, autopilot_id, trigger_id, provider, event, dedupe_key, dedupe_source, signature_status, status, attempt_count, selected_headers, content_type, raw_body, response_status, response_body, autopilot_run_id, replayed_from_delivery_id, error, received_at, last_attempt_at, created_at
+`
+
+type UpdateWebhookDeliveryTerminalParams struct {
+ ID pgtype.UUID `json:"id"`
+ Status string `json:"status"`
+ Error pgtype.Text `json:"error"`
+ ResponseStatus pgtype.Int4 `json:"response_status"`
+ ResponseBody pgtype.Text `json:"response_body"`
+}
+
+// Finalises a delivery without an autopilot_run link — rejected, ignored,
+// failed. Separate query so callers can't accidentally drop the run_id when
+// they only meant to set status/error.
+func (q *Queries) UpdateWebhookDeliveryTerminal(ctx context.Context, arg UpdateWebhookDeliveryTerminalParams) (WebhookDelivery, error) {
+ row := q.db.QueryRow(ctx, updateWebhookDeliveryTerminal,
+ arg.ID,
+ arg.Status,
+ arg.Error,
+ arg.ResponseStatus,
+ arg.ResponseBody,
+ )
+ var i WebhookDelivery
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.AutopilotID,
+ &i.TriggerID,
+ &i.Provider,
+ &i.Event,
+ &i.DedupeKey,
+ &i.DedupeSource,
+ &i.SignatureStatus,
+ &i.Status,
+ &i.AttemptCount,
+ &i.SelectedHeaders,
+ &i.ContentType,
+ &i.RawBody,
+ &i.ResponseStatus,
+ &i.ResponseBody,
+ &i.AutopilotRunID,
+ &i.ReplayedFromDeliveryID,
+ &i.Error,
+ &i.ReceivedAt,
+ &i.LastAttemptAt,
+ &i.CreatedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 83e6355af6..40b4fa8699 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -62,10 +62,11 @@ WHERE id = $1;
-- name: CreateAutopilotTrigger :one
INSERT INTO autopilot_trigger (
autopilot_id, kind, enabled, cron_expression, timezone,
- next_run_at, webhook_token, label
+ next_run_at, webhook_token, label, provider
) VALUES (
$1, $2, $3, sqlc.narg('cron_expression'), sqlc.narg('timezone'),
- sqlc.narg('next_run_at'), sqlc.narg('webhook_token'), sqlc.narg('label')
+ sqlc.narg('next_run_at'), sqlc.narg('webhook_token'), sqlc.narg('label'),
+ COALESCE(sqlc.narg('provider')::text, 'generic')
) RETURNING *;
-- name: UpdateAutopilotTrigger :one
@@ -134,6 +135,19 @@ SET webhook_token = $2,
WHERE id = $1
RETURNING *;
+-- name: SetAutopilotTriggerSigningSecret :one
+-- Writes the signing secret for a webhook trigger. Kept as a dedicated query
+-- (not a field on UpdateAutopilotTrigger) so the request body for the
+-- write-only endpoint only ever carries the secret value, with no risk of an
+-- accidental log line leaking it alongside other fields. Restricted to
+-- webhook triggers to avoid corrupting unrelated state.
+UPDATE autopilot_trigger
+SET signing_secret = sqlc.narg('signing_secret'),
+ updated_at = now()
+WHERE id = $1
+ AND kind = 'webhook'
+RETURNING *;
+
-- =====================
-- Autopilot Run Management
-- =====================
diff --git a/server/pkg/db/queries/webhook_delivery.sql b/server/pkg/db/queries/webhook_delivery.sql
new file mode 100644
index 0000000000..1d96ddf3b1
--- /dev/null
+++ b/server/pkg/db/queries/webhook_delivery.sql
@@ -0,0 +1,100 @@
+-- =====================
+-- Webhook Delivery
+-- =====================
+
+-- name: CreateWebhookDelivery :one
+-- Inserts a delivery row. On dedupe-key collision the unique partial index
+-- (trigger_id, dedupe_key) raises 23505 and the handler treats it as
+-- "duplicate" rather than an error.
+INSERT INTO webhook_delivery (
+ workspace_id, autopilot_id, trigger_id, provider, event,
+ dedupe_key, dedupe_source, signature_status, status,
+ selected_headers, content_type, raw_body,
+ replayed_from_delivery_id
+) VALUES (
+ $1, $2, $3, $4, $5,
+ sqlc.narg('dedupe_key'), sqlc.narg('dedupe_source'), $6, $7,
+ $8, sqlc.narg('content_type'), sqlc.narg('raw_body'),
+ sqlc.narg('replayed_from_delivery_id')
+) RETURNING *;
+
+-- name: GetWebhookDelivery :one
+SELECT * FROM webhook_delivery
+WHERE id = $1;
+
+-- name: GetWebhookDeliveryInWorkspace :one
+-- Workspace-scoped read for authenticated detail / replay endpoints.
+SELECT * FROM webhook_delivery
+WHERE id = $1 AND workspace_id = $2;
+
+-- name: GetWebhookDeliveryByTriggerAndDedupe :one
+-- Looks up the existing delivery for a (trigger, dedupe_key) pair so that
+-- duplicate requests return the original delivery_id / autopilot_run_id.
+-- The partial unique index excludes terminal-but-not-successful statuses
+-- (`rejected`, `failed`), so multiple such rows can coexist for the same
+-- key. Prefer non-terminal rows in the lookup: without the ORDER BY we
+-- could return a stale rejection / failure even after the operator fixed
+-- the cause and a fresh dispatch succeeded.
+SELECT * FROM webhook_delivery
+WHERE trigger_id = $1
+ AND dedupe_key = $2
+ORDER BY (status IN ('rejected', 'failed')), created_at DESC
+LIMIT 1;
+
+-- name: BumpWebhookDeliveryAttempt :one
+-- On duplicate detection, bump attempt_count and refresh last_attempt_at on
+-- the existing delivery so the UI / operator can see retry pressure without
+-- creating a new row per attempt.
+UPDATE webhook_delivery
+SET attempt_count = attempt_count + 1,
+ last_attempt_at = now()
+WHERE id = $1
+RETURNING *;
+
+-- name: UpdateWebhookDeliveryDispatched :one
+-- Finalises a delivery that successfully created (or skipped to) an
+-- autopilot_run. response_status is the HTTP status we returned, recorded
+-- alongside so the operator can correlate logs.
+UPDATE webhook_delivery
+SET status = $2,
+ autopilot_run_id = sqlc.narg('autopilot_run_id'),
+ response_status = sqlc.narg('response_status'),
+ response_body = sqlc.narg('response_body'),
+ last_attempt_at = now()
+WHERE id = $1
+RETURNING *;
+
+-- name: UpdateWebhookDeliveryTerminal :one
+-- Finalises a delivery without an autopilot_run link — rejected, ignored,
+-- failed. Separate query so callers can't accidentally drop the run_id when
+-- they only meant to set status/error.
+UPDATE webhook_delivery
+SET status = $2,
+ error = sqlc.narg('error'),
+ response_status = sqlc.narg('response_status'),
+ response_body = sqlc.narg('response_body'),
+ last_attempt_at = now()
+WHERE id = $1
+RETURNING *;
+
+-- name: ListWebhookDeliveriesByAutopilot :many
+-- Workspace-scoped via the join so a runId from another workspace cannot
+-- leak. Newest first, paged by limit/offset.
+--
+-- Projection: large columns (`raw_body`, `selected_headers`, `response_body`)
+-- are deliberately excluded. A 100-row page × 256 KiB raw_body would be
+-- 25 MiB of bytes pulled from Postgres just to be dropped in the JSON
+-- encoder — Deliveries tab would hit that on every reload. Detail views
+-- fetch the full row via GetWebhookDelivery / GetWebhookDeliveryInWorkspace.
+SELECT
+ d.id, d.workspace_id, d.autopilot_id, d.trigger_id, d.provider, d.event,
+ d.dedupe_key, d.dedupe_source, d.signature_status, d.status,
+ d.attempt_count, d.content_type, d.response_status,
+ d.autopilot_run_id, d.replayed_from_delivery_id, d.error,
+ d.received_at, d.last_attempt_at, d.created_at
+FROM webhook_delivery d
+JOIN autopilot a ON a.id = d.autopilot_id
+WHERE d.autopilot_id = $1
+ AND a.workspace_id = $2
+ORDER BY d.created_at DESC
+LIMIT $3 OFFSET $4;