Skip to content

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

Go

MUL-2703: feat(autopilots): webhook event filters per trigger (MUL-2334 follow-up) (#3231)

Raúl Anatol2b5696703f1f
diff --git a/packages/core/types/autopilot.ts b/packages/core/types/autopilot.ts
index c18e7041d6..23a8949ede 100644
--- a/packages/core/types/autopilot.ts
+++ b/packages/core/types/autopilot.ts
@@ -41,6 +41,11 @@ export interface Autopilot {
updated_at: string;
}
+export interface WebhookEventFilter {
+ event: string;
+ actions?: string[];
+}
+
export interface AutopilotTrigger {
id: string;
autopilot_id: string;
@@ -59,6 +64,9 @@ export interface AutopilotTrigger {
// webhook_path when this is missing.
webhook_url?: string | null;
label: string | null;
+ // event_filters is only present for webhook triggers. Null/empty means
+ // "accept all events".
+ event_filters?: WebhookEventFilter[] | null;
last_fired_at: string | null;
created_at: string;
updated_at: string;
@@ -110,6 +118,8 @@ export interface CreateAutopilotTriggerRequest {
cron_expression?: string;
timezone?: string;
label?: string;
+ // event_filters is only meaningful for webhook triggers.
+ event_filters?: WebhookEventFilter[];
}
export interface UpdateAutopilotTriggerRequest {
@@ -117,6 +127,8 @@ export interface UpdateAutopilotTriggerRequest {
cron_expression?: string;
timezone?: string;
label?: string;
+ // event_filters is only meaningful for webhook triggers.
+ event_filters?: WebhookEventFilter[] | null;
}
export interface ListAutopilotsResponse {
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 84e6d2afd8..9ad5c24c1b 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -103,6 +103,7 @@ export type {
AutopilotRun,
AutopilotRunStatus,
AutopilotRunSource,
+ WebhookEventFilter,
CreateAutopilotRequest,
UpdateAutopilotRequest,
CreateAutopilotTriggerRequest,
diff --git a/packages/views/autopilots/components/autopilot-dialog.tsx b/packages/views/autopilots/components/autopilot-dialog.tsx
index f749665287..85eb8a9d81 100644
--- a/packages/views/autopilots/components/autopilot-dialog.tsx
+++ b/packages/views/autopilots/components/autopilot-dialog.tsx
@@ -66,8 +66,10 @@ import {
type TriggerConfig,
type TriggerFrequency,
} from "./trigger-config";
+import { WebhookEventFilterSection } from "./webhook-event-filter-section";
import { useT } from "../../i18n";
import { formatSchedulePartialFailureToast } from "./autopilot-dialog-toast";
+import type { WebhookEventFilter } from "@multica/core/types";
// ---------------------------------------------------------------------------
// Types
@@ -226,6 +228,20 @@ function formatNextRunAbsolute(date: Date, timezone: string): string {
}
}
+// ---------------------------------------------------------------------------
+// Webhook event-filter dirty detection
+// ---------------------------------------------------------------------------
+
+// serializeEventFilters returns a stable JSON string so the edit-mode dirty
+// check can compare the current filters against the snapshot taken on open
+// without depending on reference equality. Normalizes empty Actions to []
+// so omitted-vs-explicit-empty doesn't show as a phantom change.
+function serializeEventFilters(filters: WebhookEventFilter[]): string {
+ return JSON.stringify(
+ filters.map((f) => ({ event: f.event, actions: f.actions ?? [] })),
+ );
+}
+
// ---------------------------------------------------------------------------
// Live "now" ticker for countdown
// ---------------------------------------------------------------------------
@@ -296,11 +312,18 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
})();
const [triggerKind, setTriggerKind] = useState<"schedule" | "webhook">(initialKind);
+ const initialEventFilters: WebhookEventFilter[] =
+ !isCreate && props.triggers[0]?.event_filters ? props.triggers[0].event_filters : [];
+ const [eventFilters, setEventFilters] = useState<WebhookEventFilter[]>(initialEventFilters);
+
const initialCronRef = useRef(toCronExpression(initialCfg));
const initialTimezoneRef = useRef(initialCfg.timezone);
+ const initialEventFiltersRef = useRef(serializeEventFilters(initialEventFilters));
const scheduleDirty =
toCronExpression(triggerConfig) !== initialCronRef.current ||
triggerConfig.timezone !== initialTimezoneRef.current;
+ const eventFiltersDirty =
+ serializeEventFilters(eventFilters) !== initialEventFiltersRef.current;
const firstTriggerIdRef = useRef(
!isCreate && props.triggers[0] ? props.triggers[0].id : null,
@@ -364,6 +387,7 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
webhookTrigger = await createTrigger.mutateAsync({
autopilotId: autopilot.id,
kind: "webhook",
+ event_filters: eventFilters.length > 0 ? eventFilters : undefined,
});
} else {
await createTrigger.mutateAsync({
@@ -404,8 +428,8 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
assignee_id: assigneeId,
execution_mode: executionMode,
});
- let scheduleOk = true;
- let scheduleErrMessage: string | null = null;
+ let triggerOk = true;
+ let triggerErrMessage: string | null = null;
// Skip the schedule sync when the autopilot's first trigger is a
// webhook — there's no cron to update there, and the schedule
// panel isn't even rendered for webhook autopilots.
@@ -428,16 +452,38 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
});
}
} catch (err) {
- scheduleOk = false;
- scheduleErrMessage =
+ triggerOk = false;
+ triggerErrMessage =
+ err instanceof Error && err.message ? err.message : null;
+ }
+ }
+ // Webhook autopilots have no schedule, but the user can still edit
+ // event_filters from the same dialog. PATCH only when the snapshot
+ // taken on open differs from the live state. Sending an explicit
+ // empty array clears filters server-side (tri-state semantics — see
+ // UpdateAutopilotTriggerRequest in autopilot.go).
+ if (
+ triggerKind === "webhook" &&
+ eventFiltersDirty &&
+ firstTriggerIdRef.current
+ ) {
+ try {
+ await updateTrigger.mutateAsync({
+ autopilotId: props.autopilotId,
+ triggerId: firstTriggerIdRef.current,
+ event_filters: eventFilters,
+ });
+ } catch (err) {
+ triggerOk = false;
+ triggerErrMessage =
err instanceof Error && err.message ? err.message : null;
}
}
onOpenChange(false);
- if (scheduleOk) {
+ if (triggerOk) {
toast.success(t(($) => $.dialog.toast_updated));
} else {
- toast.error(formatSchedulePartialFailureToast(t, "update", scheduleErrMessage));
+ toast.error(formatSchedulePartialFailureToast(t, "update", triggerErrMessage));
}
}
} catch (err) {
@@ -614,7 +660,11 @@ export function AutopilotDialog(props: AutopilotDialogProps) {
}
/>
) : (
- <WebhookHelpSection isCreate={isCreate} />
+ <WebhookSection
+ isCreate={isCreate}
+ eventFilters={eventFilters}
+ onEventFiltersChange={setEventFilters}
+ />
)}
</aside>
</div>
@@ -1010,16 +1060,30 @@ function TriggerKindButton({
);
}
-function WebhookHelpSection({ isCreate }: { isCreate: boolean }) {
+function WebhookSection({
+ isCreate,
+ eventFilters,
+ onEventFiltersChange,
+}: {
+ isCreate: boolean;
+ eventFilters: WebhookEventFilter[];
+ onEventFiltersChange: (filters: WebhookEventFilter[]) => void;
+}) {
const { t } = useT("autopilots");
return (
- <div>
- <SectionLabel>{t(($) => $.dialog.section_webhook)}</SectionLabel>
- <p className="rounded-md border bg-background px-3 py-2 text-xs text-muted-foreground leading-relaxed">
- {isCreate
- ? t(($) => $.dialog.webhook_help_create)
- : t(($) => $.dialog.webhook_help_edit)}
- </p>
+ <div className="space-y-3">
+ <div>
+ <SectionLabel>{t(($) => $.dialog.section_webhook)}</SectionLabel>
+ <p className="rounded-md border bg-background px-3 py-2 text-xs text-muted-foreground leading-relaxed">
+ {isCreate
+ ? t(($) => $.dialog.webhook_help_create)
+ : t(($) => $.dialog.webhook_help_edit)}
+ </p>
+ </div>
+ <WebhookEventFilterSection
+ filters={eventFilters}
+ onChange={onEventFiltersChange}
+ />
</div>
);
}
diff --git a/packages/views/autopilots/components/webhook-event-filter-section.tsx b/packages/views/autopilots/components/webhook-event-filter-section.tsx
new file mode 100644
index 0000000000..dd2bc4e4a4
--- /dev/null
+++ b/packages/views/autopilots/components/webhook-event-filter-section.tsx
@@ -0,0 +1,120 @@
+"use client";
+
+import { useState } from "react";
+import { X, Plus, Filter } from "lucide-react";
+import { cn } from "@multica/ui/lib/utils";
+import type { WebhookEventFilter } from "@multica/core/types";
+import { useT } from "../../i18n";
+
+interface WebhookEventFilterSectionProps {
+ filters: WebhookEventFilter[];
+ onChange: (filters: WebhookEventFilter[]) => void;
+}
+
+export function WebhookEventFilterSection({
+ filters,
+ onChange,
+}: WebhookEventFilterSectionProps) {
+ const { t } = useT("autopilots");
+ const [newEvent, setNewEvent] = useState("");
+ const [newActions, setNewActions] = useState("");
+
+ const addFilter = () => {
+ const event = newEvent.trim();
+ if (!event) return;
+ const actions = newActions
+ .split(",")
+ .map((a) => a.trim())
+ .filter((a) => a.length > 0);
+ const next: WebhookEventFilter = { event };
+ if (actions.length > 0) next.actions = actions;
+ onChange([...filters, next]);
+ setNewEvent("");
+ setNewActions("");
+ };
+
+ const removeFilter = (idx: number) => {
+ onChange(filters.filter((_, i) => i !== idx));
+ };
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-1.5 text-[11px] font-semibold tracking-[0.08em] text-muted-foreground uppercase">
+ <Filter className="size-3" />
+ {t(($) => $.dialog.event_filter_label)}
+ </div>
+
+ {filters.length > 0 && (
+ <div className="space-y-1">
+ {filters.map((f, idx) => (
+ <div
+ key={idx}
+ className="flex items-center gap-2 rounded-md border bg-background px-2.5 py-1.5 text-xs"
+ >
+ <span className="font-mono font-medium text-foreground">
+ {f.event}
+ </span>
+ {f.actions && f.actions.length > 0 && (
+ <span className="text-muted-foreground">
+ : {f.actions.join(", ")}
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={() => removeFilter(idx)}
+ className="ml-auto rounded p-0.5 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
+ >
+ <X className="size-3" />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div className="flex gap-2">
+ <input
+ type="text"
+ value={newEvent}
+ onChange={(e) => setNewEvent(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ addFilter();
+ }
+ }}
+ placeholder={t(($) => $.dialog.event_filter_event_placeholder)}
+ className="flex-1 min-w-0 rounded-md border bg-background px-2.5 py-1.5 text-xs font-mono outline-none focus:ring-1 focus:ring-ring"
+ />
+ <input
+ type="text"
+ value={newActions}
+ onChange={(e) => setNewActions(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ addFilter();
+ }
+ }}
+ placeholder={t(($) => $.dialog.event_filter_actions_placeholder)}
+ className="w-28 rounded-md border bg-background px-2.5 py-1.5 text-xs outline-none focus:ring-1 focus:ring-ring"
+ />
+ <button
+ type="button"
+ onClick={addFilter}
+ disabled={!newEvent.trim()}
+ className={cn(
+ "inline-flex items-center justify-center rounded-md border px-2.5 py-1.5 text-xs font-medium transition-colors",
+ newEvent.trim()
+ ? "bg-background text-foreground hover:bg-accent/40 cursor-pointer"
+ : "bg-muted text-muted-foreground cursor-not-allowed",
+ )}
+ >
+ <Plus className="size-3.5" />
+ </button>
+ </div>
+ <p className="text-[10px] text-muted-foreground">
+ {t(($) => $.dialog.event_filter_hint)}
+ </p>
+ </div>
+ );
+}
diff --git a/packages/views/locales/en/autopilots.json b/packages/views/locales/en/autopilots.json
index 24e3ab63e9..4ea2c5f3fc 100644
--- a/packages/views/locales/en/autopilots.json
+++ b/packages/views/locales/en/autopilots.json
@@ -258,6 +258,10 @@
"webhook_created_description": "POST any JSON to the URL below and the autopilot will fire. Copy it now — you can also find and rotate it on the autopilot's detail page.",
"webhook_created_warning": "Treat this URL like a password. Anyone who has it can trigger the autopilot.",
"webhook_created_done": "Done",
+ "event_filter_label": "Event filters",
+ "event_filter_event_placeholder": "e.g. workflow_run",
+ "event_filter_actions_placeholder": "completed, failed",
+ "event_filter_hint": "Only process webhooks matching these events. Leave empty to accept all.",
"schedule_disabled_reason": "This autopilot has multiple schedules — edit them in the detail page.",
"next_run_label": "Next run:",
"output_modes": {
diff --git a/packages/views/locales/zh-Hans/autopilots.json b/packages/views/locales/zh-Hans/autopilots.json
index dbde107518..56ce9e2648 100644
--- a/packages/views/locales/zh-Hans/autopilots.json
+++ b/packages/views/locales/zh-Hans/autopilots.json
@@ -258,6 +258,10 @@
"webhook_created_description": "向下方的 URL POST 任意 JSON 即可触发该 Autopilot。请立即复制——之后也能在 Autopilot 详情页查看或重新生成。",
"webhook_created_warning": "请把该 URL 当作密码对待,任何拿到它的人都能触发该 Autopilot。",
"webhook_created_done": "完成",
+ "event_filter_label": "事件过滤",
+ "event_filter_event_placeholder": "例如 workflow_run",
+ "event_filter_actions_placeholder": "completed, failed",
+ "event_filter_hint": "只处理匹配这些事件的 webhook。留空则接受所有事件。",
"schedule_disabled_reason": "该自动化有多个时间表——请到详情页编辑。",
"next_run_label": "下次运行:",
"output_modes": {
diff --git a/server/internal/handler/autopilot.go b/server/internal/handler/autopilot.go
index bd16e053fc..908d072200 100644
--- a/server/internal/handler/autopilot.go
+++ b/server/internal/handler/autopilot.go
@@ -78,6 +78,11 @@ type AutopilotTriggerResponse struct {
LastFiredAt *string `json:"last_fired_at"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
+ // EventFilters is the declared event scope. Only present for webhook
+ // triggers; omitted when the trigger accepts all events. Serializes as
+ // a JSON array of {event, actions?} objects — never as a base64 string
+ // (which is what []byte would produce through encoding/json).
+ EventFilters []WebhookEventFilter `json:"event_filters,omitempty"`
}
type AutopilotRunResponse struct {
@@ -157,6 +162,16 @@ func (h *Handler) triggerToResponse(t db.AutopilotTrigger) AutopilotTriggerRespo
hint := signingSecretHint(t.SigningSecret.String)
resp.SigningSecretHint = &hint
}
+ if len(t.EventFilters) > 0 {
+ var filters []WebhookEventFilter
+ if err := json.Unmarshal(t.EventFilters, &filters); err == nil {
+ resp.EventFilters = filters
+ }
+ // On unmarshal error we deliberately drop the field instead of
+ // surfacing raw bytes or 500ing — strict write-time validation
+ // is supposed to make this branch unreachable, and the matcher
+ // fails closed if a corrupt row ever slips through.
+ }
}
return resp
}
@@ -249,6 +264,9 @@ type CreateAutopilotTriggerRequest struct {
// Provider is currently only meaningful for kind=webhook. Allowed
// values: "generic" (default) or "github". Unset → "generic".
Provider *string `json:"provider"`
+ // EventFilters is an optional list of {event, actions?} scopes. Only
+ // meaningful for webhook triggers. nil/empty means "accept all events".
+ EventFilters []WebhookEventFilter `json:"event_filters,omitempty"`
}
// SetSigningSecretRequest is the body shape for PUT
@@ -269,6 +287,20 @@ type UpdateAutopilotTriggerRequest struct {
CronExpression *string `json:"cron_expression"`
Timezone *string `json:"timezone"`
Label *string `json:"label"`
+ // EventFilters is the desired event-filter set with tri-state PATCH
+ // semantics:
+ //
+ // - omitted / explicit null (nil pointer) → leave the existing value
+ // untouched.
+ // - explicit [] (non-nil, length 0) → clear filters (the trigger
+ // reverts to "accept all events").
+ // - explicit [...] → replace with the supplied
+ // list.
+ //
+ // This is why the pointer matters: with a plain []WebhookEventFilter
+ // there is no way to tell "field absent from the PATCH body" from "field
+ // present but empty", and the user can never clear filters once set.
+ EventFilters *[]WebhookEventFilter `json:"event_filters,omitempty"`
}
// ── Handlers ────────────────────────────────────────────────────────────────
@@ -645,6 +677,16 @@ func (h *Handler) CreateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusBadRequest, "timezone is not valid for webhook triggers")
return
}
+ if req.Kind != "webhook" && len(req.EventFilters) > 0 {
+ // event_filters narrows webhook ingress — it has no meaning for a
+ // schedule trigger and would otherwise be silently dropped.
+ writeError(w, http.StatusBadRequest, "event_filters is only valid for webhook triggers")
+ return
+ }
+ if err := validateWebhookEventFilters(req.EventFilters); err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ 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
@@ -698,7 +740,12 @@ 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), provider)
+ eventFiltersBytes, err := encodeWebhookEventFilters(req.EventFilters)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to encode event_filters")
+ return
+ }
+ trigger, err := h.createWebhookTriggerWithMintedToken(r, ap.ID, ptrToText(req.Label), provider, eventFiltersBytes)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to create trigger")
return
@@ -750,6 +797,7 @@ func (h *Handler) createWebhookTriggerWithMintedToken(
autopilotID pgtype.UUID,
label pgtype.Text,
provider string,
+ eventFilters []byte,
) (db.AutopilotTrigger, error) {
for attempt := 0; attempt < 3; attempt++ {
token, err := generateWebhookToken()
@@ -763,6 +811,7 @@ func (h *Handler) createWebhookTriggerWithMintedToken(
Label: label,
WebhookToken: pgtype.Text{String: token, Valid: true},
Provider: pgtype.Text{String: provider, Valid: provider != ""},
+ EventFilters: eventFilters,
})
if err == nil {
return trigger, nil
@@ -915,6 +964,28 @@ func (h *Handler) UpdateAutopilotTrigger(w http.ResponseWriter, r *http.Request)
if req.Label != nil {
params.Label = pgtype.Text{String: *req.Label, Valid: true}
}
+ // Tri-state PATCH for event_filters. A nil pointer (field omitted or
+ // JSON null) leaves the existing row untouched — params.EventFilters
+ // stays unset and the COALESCE in the UPDATE preserves the previous
+ // value. A non-nil pointer is authoritative: an empty slice clears
+ // filters (encoded as the JSONB literal `[]` so COALESCE replaces
+ // rather than preserves), a populated slice replaces.
+ if req.EventFilters != nil {
+ if prev.Kind != "webhook" {
+ writeError(w, http.StatusBadRequest, "event_filters is only valid for webhook triggers")
+ return
+ }
+ if err := validateWebhookEventFilters(*req.EventFilters); err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ encoded, err := encodeWebhookEventFiltersAlways(*req.EventFilters)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to encode event_filters")
+ return
+ }
+ params.EventFilters = encoded
+ }
// Recompute next_run_at if cron or timezone changed.
cronExpr := prev.CronExpression.String
diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.go
index df9e83c8cd..57db8230df 100644
--- a/server/internal/handler/autopilot_webhook.go
+++ b/server/internal/handler/autopilot_webhook.go
@@ -523,7 +523,22 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- // 11. Dispatch synchronously. DispatchAutopilot publishes WS events,
+ // 11. Event filter scope → ignored. If the trigger declares a concrete
+ // event_filters list and the incoming event is outside that scope,
+ // record an ignored delivery without creating an expensive run/task.
+ if !webhookEventAllowedByTriggerScope(trigRow.EventFilters, envelope) {
+ respBody := map[string]any{
+ "status": "ignored",
+ "delivery_id": uuidToString(delivery.ID),
+ "reason": "event_filtered",
+ "event": envelope.Event,
+ }
+ h.finaliseDeliveryTerminal(r, delivery.ID, deliveryStatusIgnored, http.StatusOK, respBody, "event_filtered")
+ writeJSON(w, http.StatusOK, respBody)
+ return
+ }
+
+ // 12. 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(
@@ -553,7 +568,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
return
}
- // 12. Bump last_fired_at after dispatch returns — including the skipped
+ // 13. 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",
@@ -562,7 +577,7 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
)
}
- // 13. Persist the linkage delivery → run.
+ // 14. 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
@@ -593,6 +608,154 @@ func (h *Handler) HandleAutopilotWebhook(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, respBody)
}
+// ── Event filter helpers ────────────────────────────────────────────────────
+
+// WebhookEventFilter declares one event and an optional list of actions.
+// A nil/empty Actions means "any action" for this event.
+type WebhookEventFilter struct {
+ Event string `json:"event"`
+ Actions []string `json:"actions,omitempty"`
+}
+
+// validateWebhookEventFilters enforces the contract at the HTTP boundary so
+// that malformed shapes never reach the database. The matcher (read path)
+// trusts whatever is stored — see webhookEventAllowedByTriggerScope.
+func validateWebhookEventFilters(filters []WebhookEventFilter) error {
+ for i, f := range filters {
+ if strings.TrimSpace(f.Event) == "" {
+ return fmt.Errorf("event_filters[%d].event must not be empty", i)
+ }
+ for j, a := range f.Actions {
+ if strings.TrimSpace(a) == "" {
+ return fmt.Errorf("event_filters[%d].actions[%d] must not be empty", i, j)
+ }
+ }
+ }
+ return nil
+}
+
+// encodeWebhookEventFilters returns the JSONB bytes to persist for a CREATE.
+// nil/empty input maps to nil bytes (column stays NULL → matcher allows
+// every event), so we never write an explicit `[]` on create.
+func encodeWebhookEventFilters(filters []WebhookEventFilter) ([]byte, error) {
+ if len(filters) == 0 {
+ return nil, nil
+ }
+ return json.Marshal(filters)
+}
+
+// encodeWebhookEventFiltersAlways always returns non-nil bytes, even for an
+// empty slice (`[]byte("[]")`). The UPDATE handler uses this so an explicit
+// empty array in the PATCH body can overwrite (via COALESCE) the existing
+// row to a cleared state — passing nil would be indistinguishable from
+// "field omitted, leave alone".
+func encodeWebhookEventFiltersAlways(filters []WebhookEventFilter) ([]byte, error) {
+ if filters == nil {
+ filters = []WebhookEventFilter{}
+ }
+ return json.Marshal(filters)
+}
+
+// webhookEventAllowedByTriggerScope returns true when the trigger has no
+// filters (NULL / empty) or when the incoming envelope matches at least one
+// declared filter.
+func webhookEventAllowedByTriggerScope(eventFilters []byte, envelope WebhookEnvelope) bool {
+ if len(eventFilters) == 0 {
+ return true
+ }
+ var filters []WebhookEventFilter
+ if err := json.Unmarshal(eventFilters, &filters); err != nil {
+ // Strict write-time validation should prevent malformed bytes
+ // from ever reaching this branch. If a corrupt row somehow
+ // exists, fail closed — silently widening the allowlist on a
+ // "only allow X" policy is worse than dropping events until an
+ // operator notices.
+ slog.Warn("webhook: malformed event_filters, denying", "error", err)
+ return false
+ }
+ if len(filters) == 0 {
+ return true
+ }
+ _, eventName, eventAction := splitWebhookEvent(envelope.Event)
+ actionCandidates := webhookActionCandidates(eventAction, envelope.EventPayload)
+ for _, f := range filters {
+ if f.Event != eventName {
+ continue
+ }
+ if len(f.Actions) == 0 {
+ return true
+ }
+ for _, action := range actionCandidates {
+ for _, allowed := range f.Actions {
+ if action == allowed {
+ return true
+ }
+ }
+ }
+ // Intentionally do NOT return false here: the UI allows several
+ // filters that share the same event name (e.g. two workflow_run
+ // rows covering disjoint actions). Earlier code short-circuited
+ // on the first event-name hit, which made one row silently shadow
+ // the others depending on iteration order — see PR #3231 review.
+ // Keep scanning so any later filter still gets its chance.
+ }
+ return false
+}
+
+// splitWebhookEvent splits a normalized event like "github.workflow_run.completed"
+// into (provider, eventName, action). For unqualified events it returns ("", event, "").
+func splitWebhookEvent(event string) (provider, name, action string) {
+ parts := strings.Split(event, ".")
+ if isKnownProvider(parts[0]) {
+ if len(parts) >= 3 {
+ return parts[0], parts[1], strings.Join(parts[2:], ".")
+ }
+ if len(parts) == 2 {
+ return parts[0], parts[1], ""
+ }
+ return parts[0], "", ""
+ }
+ if len(parts) >= 2 {
+ return "", parts[0], strings.Join(parts[1:], ".")
+ }
+ return "", event, ""
+}
+
+func isKnownProvider(prefix string) bool {
+ switch prefix {
+ case "github", "gitlab", "bitbucket", "gitea":
+ return true
+ }
+ return false
+}
+
+// webhookActionCandidates extracts possible action values from the event
+// action suffix and from well-known payload fields.
+func webhookActionCandidates(eventAction string, payload json.RawMessage) []string {
+ seen := map[string]struct{}{}
+ add := func(v string) {
+ v = strings.TrimSpace(v)
+ if v == "" {
+ return
+ }
+ seen[v] = struct{}{}
+ }
+ add(eventAction)
+ var obj map[string]any
+ if err := json.Unmarshal(payload, &obj); err == nil {
+ for _, key := range []string{"action", "state", "conclusion", "status"} {
+ if v, ok := obj[key].(string); ok {
+ add(v)
+ }
+ }
+ }
+ out := make([]string, 0, len(seen))
+ for v := range seen {
+ out = append(out, v)
+ }
+ return out
+}
+
// ── Persistence helpers ─────────────────────────────────────────────────────
type persistDeliveryInput struct {
diff --git a/server/internal/handler/autopilot_webhook_handler_test.go b/server/internal/handler/autopilot_webhook_handler_test.go
index 893725036c..32d790f8d0 100644
--- a/server/internal/handler/autopilot_webhook_handler_test.go
+++ b/server/internal/handler/autopilot_webhook_handler_test.go
@@ -76,6 +76,315 @@ func createWebhookTriggerViaHandler(t *testing.T, autopilotID string) AutopilotT
return resp
}
+// createWebhookTriggerWithFilters builds the request body with a real JSON
+// array — the same shape the frontend sends. Earlier revisions of this
+// helper marshaled the filters separately and assigned the resulting
+// []byte to the "event_filters" map key, which encoding/json then encoded
+// as a base64 string (since []byte → JSON-string). The base64 path
+// happened to work against an []byte server-side field but masked the
+// actual contract bug fixed in PR #3231 review.
+func createWebhookTriggerWithFilters(t *testing.T, autopilotID string, filters []WebhookEventFilter) AutopilotTriggerResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots/"+autopilotID+"/triggers", map[string]any{
+ "kind": "webhook",
+ "event_filters": filters,
+ })
+ req = withURLParam(req, "id", autopilotID)
+ testHandler.CreateAutopilotTrigger(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateAutopilotTrigger: expected 201, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp AutopilotTriggerResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ return resp
+}
+
+func TestWebhookHandler_FiltersUndeclaredEvent(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "WebhookFilter Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerWithFilters(t, apID, []WebhookEventFilter{
+ {Event: "workflow_run", Actions: []string{"completed"}},
+ {Event: "check_suite", Actions: []string{"completed"}},
+ })
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{
+ "action": "in_progress",
+ "workflow_run": map[string]any{"id": 123},
+ }, map[string]string{"X-GitHub-Event": "workflow_run"})
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if resp["status"] != "ignored" || resp["reason"] != "event_filtered" {
+ t.Fatalf("expected ignored/event_filtered, got %#v body=%s", resp, w.Body.String())
+ }
+ if _, ok := resp["run_id"]; ok {
+ t.Fatalf("filtered response must not include run_id: %#v", resp)
+ }
+
+ runs, err := testHandler.Queries.ListAutopilotRuns(context.Background(), db.ListAutopilotRunsParams{
+ AutopilotID: parseUUID(apID),
+ Limit: 10,
+ Offset: 0,
+ })
+ if err != nil {
+ t.Fatalf("list runs: %v", err)
+ }
+ if len(runs) != 0 {
+ t.Fatalf("filtered webhook should not create runs, got %d", len(runs))
+ }
+}
+
+func TestWebhookHandler_AllowsDeclaredEvent(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "WebhookAllow Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerWithFilters(t, apID, []WebhookEventFilter{
+ {Event: "workflow_run", Actions: []string{"completed"}},
+ })
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{
+ "action": "completed",
+ "workflow_run": map[string]any{"id": 123},
+ }, map[string]string{"X-GitHub-Event": "workflow_run"})
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if resp["status"] != "accepted" && resp["status"] != "skipped" {
+ t.Fatalf("expected accepted or skipped, got %#v", resp)
+ }
+}
+
+func TestWebhookHandler_EmptyFiltersAllowsAll(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "WebhookEmptyFilter Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+ trig := createWebhookTriggerViaHandler(t, apID)
+
+ w := postWebhook(t, *trig.WebhookToken, map[string]any{
+ "action": "in_progress",
+ "workflow_run": map[string]any{"id": 123},
+ }, map[string]string{"X-GitHub-Event": "workflow_run"})
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if resp["status"] != "accepted" && resp["status"] != "skipped" {
+ t.Fatalf("expected accepted or skipped, got %#v", resp)
+ }
+}
+
+// ── HTTP contract: event_filters JSON shape & PATCH semantics ──────────────
+//
+// These tests pin the wire contract the frontend depends on: a real JSON
+// array of {event, actions} objects flows in on create, comes back as the
+// same array on read, and update accepts tri-state semantics (omitted =
+// preserve, explicit [] = clear, explicit [...] = replace). Earlier
+// revisions used []byte at the HTTP boundary and the round-trip silently
+// passed via base64 — which the frontend cannot parse. See PR #3231 review.
+
+func TestCreateWebhookTrigger_EventFiltersRoundTripAsJSONArray(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "EventFilterRT Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ body := map[string]any{
+ "kind": "webhook",
+ "event_filters": []map[string]any{
+ {"event": "workflow_run", "actions": []string{"completed"}},
+ {"event": "pull_request", "actions": []string{"opened", "synchronize"}},
+ },
+ }
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", body)
+ 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())
+ }
+
+ // Decode against the strongly-typed response to verify shape.
+ var typed AutopilotTriggerResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &typed); err != nil {
+ t.Fatalf("decode typed: %v", err)
+ }
+ if len(typed.EventFilters) != 2 {
+ t.Fatalf("expected 2 filters, got %d body=%s", len(typed.EventFilters), w.Body.String())
+ }
+ if typed.EventFilters[0].Event != "workflow_run" ||
+ len(typed.EventFilters[0].Actions) != 1 ||
+ typed.EventFilters[0].Actions[0] != "completed" {
+ t.Fatalf("first filter mismatch: %#v", typed.EventFilters[0])
+ }
+ if typed.EventFilters[1].Event != "pull_request" || len(typed.EventFilters[1].Actions) != 2 {
+ t.Fatalf("second filter mismatch: %#v", typed.EventFilters[1])
+ }
+
+ // Decode against json.RawMessage to confirm we serialize as an array,
+ // not a base64-encoded string. A regression here is exactly the bug
+ // PR #3231 review flagged: []byte through encoding/json produced
+ // `"event_filters": "W3si..."` which the UI can't .map() over.
+ var raw struct {
+ EventFilters json.RawMessage `json:"event_filters"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {
+ t.Fatalf("decode raw: %v", err)
+ }
+ trimmed := bytes.TrimSpace(raw.EventFilters)
+ if len(trimmed) == 0 || trimmed[0] != '[' {
+ t.Fatalf("event_filters must serialize as a JSON array, got %s", raw.EventFilters)
+ }
+}
+
+func TestUpdateWebhookTrigger_ExplicitEmptyArrayClearsFilters(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "EventFilterClear Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ created := createWebhookTriggerWithFilters(t, apID, []WebhookEventFilter{
+ {Event: "workflow_run", Actions: []string{"completed"}},
+ })
+ if len(created.EventFilters) != 1 {
+ t.Fatalf("seed should have 1 filter, got %d", len(created.EventFilters))
+ }
+
+ w := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/autopilots/"+apID+"/triggers/"+created.ID, map[string]any{
+ "event_filters": []any{},
+ })
+ req = withURLParams(req, "id", apID, "triggerId", created.ID)
+ testHandler.UpdateAutopilotTrigger(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ var updated AutopilotTriggerResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &updated); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(updated.EventFilters) != 0 {
+ t.Fatalf("expected cleared filters in response, got %#v", updated.EventFilters)
+ }
+
+ // Stored row should now accept any event (matcher sees length 0).
+ row, err := testHandler.Queries.GetAutopilotTrigger(context.Background(), parseUUID(created.ID))
+ if err != nil {
+ t.Fatalf("load: %v", err)
+ }
+ env := WebhookEnvelope{
+ Event: "github.something_else.opened",
+ EventPayload: json.RawMessage(`{"action":"opened"}`),
+ }
+ if !webhookEventAllowedByTriggerScope(row.EventFilters, env) {
+ t.Fatal("after clear, matcher should allow all events")
+ }
+}
+
+func TestUpdateWebhookTrigger_OmittedFiltersPreserveExisting(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "EventFilterPreserve Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ created := createWebhookTriggerWithFilters(t, apID, []WebhookEventFilter{
+ {Event: "workflow_run", Actions: []string{"completed"}},
+ })
+
+ // PATCH that does NOT include event_filters at all. Must leave the
+ // existing filter set untouched (omitted ≠ clear).
+ w := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/autopilots/"+apID+"/triggers/"+created.ID, map[string]any{
+ "label": "renamed-but-keep-filters",
+ })
+ req = withURLParams(req, "id", apID, "triggerId", created.ID)
+ testHandler.UpdateAutopilotTrigger(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ var updated AutopilotTriggerResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &updated); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(updated.EventFilters) != 1 || updated.EventFilters[0].Event != "workflow_run" {
+ t.Fatalf("filters must be preserved when field omitted, got %#v", updated.EventFilters)
+ }
+}
+
+func TestUpdateWebhookTrigger_ReplacesFilters(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "EventFilterReplace Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ created := createWebhookTriggerWithFilters(t, apID, []WebhookEventFilter{
+ {Event: "workflow_run", Actions: []string{"completed"}},
+ })
+
+ w := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/autopilots/"+apID+"/triggers/"+created.ID, map[string]any{
+ "event_filters": []map[string]any{
+ {"event": "pull_request", "actions": []string{"opened"}},
+ {"event": "issues"},
+ },
+ })
+ req = withURLParams(req, "id", apID, "triggerId", created.ID)
+ testHandler.UpdateAutopilotTrigger(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
+ }
+ var updated AutopilotTriggerResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &updated); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(updated.EventFilters) != 2 {
+ t.Fatalf("expected 2 replaced filters, got %d", len(updated.EventFilters))
+ }
+ if updated.EventFilters[0].Event != "pull_request" || updated.EventFilters[1].Event != "issues" {
+ t.Fatalf("replaced filter list wrong: %#v", updated.EventFilters)
+ }
+}
+
+func TestCreateAutopilotTrigger_RejectsInvalidEventFilter(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "EventFilterInvalid Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", map[string]any{
+ "kind": "webhook",
+ "event_filters": []map[string]any{
+ {"event": "", "actions": []string{"completed"}},
+ },
+ })
+ req = withURLParam(req, "id", apID)
+ testHandler.CreateAutopilotTrigger(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 on empty event name, got %d body=%s", w.Code, w.Body.String())
+ }
+}
+
+func TestCreateAutopilotTrigger_RejectsEventFiltersOnSchedule(t *testing.T) {
+ agentID := createWebhookTestAgent(t, "EventFilterSched Agent")
+ apID := createWebhookTestAutopilot(t, agentID, "active", "run_only")
+
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/autopilots/"+apID+"/triggers", map[string]any{
+ "kind": "schedule",
+ "cron_expression": "0 9 * * *",
+ "event_filters": []map[string]any{
+ {"event": "workflow_run"},
+ },
+ })
+ req = withURLParam(req, "id", apID)
+ testHandler.CreateAutopilotTrigger(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 on event_filters for schedule trigger, got %d body=%s", w.Code, w.Body.String())
+ }
+}
+
func postWebhook(t *testing.T, token string, body any, headers map[string]string) *httptest.ResponseRecorder {
t.Helper()
var buf bytes.Buffer
diff --git a/server/internal/handler/autopilot_webhook_test.go b/server/internal/handler/autopilot_webhook_test.go
index 99a2e4c031..308400c3f6 100644
--- a/server/internal/handler/autopilot_webhook_test.go
+++ b/server/internal/handler/autopilot_webhook_test.go
@@ -214,3 +214,142 @@ func TestNormalizeWebhookPayload_XEventTypeHeader(t *testing.T) {
t.Fatalf("event: %q", env.Event)
}
}
+
+// ── Event filter helpers ────────────────────────────────────────────────────
+
+func TestWebhookEventAllowedByTriggerScope_NoFiltersAllowsAll(t *testing.T) {
+ if !webhookEventAllowedByTriggerScope(nil, WebhookEnvelope{Event: "github.push"}) {
+ t.Fatal("nil filters should allow all")
+ }
+ if !webhookEventAllowedByTriggerScope([]byte{}, WebhookEnvelope{Event: "github.push"}) {
+ t.Fatal("empty filters should allow all")
+ }
+ if !webhookEventAllowedByTriggerScope([]byte("[]"), WebhookEnvelope{Event: "github.push"}) {
+ t.Fatal("empty JSON array should allow all")
+ }
+}
+
+func TestWebhookEventAllowedByTriggerScope_FiltersUndeclaredEvent(t *testing.T) {
+ filters := []byte(`[{"event":"workflow_run","actions":["completed"]}]`)
+ env := WebhookEnvelope{Event: "github.push", EventPayload: json.RawMessage(`{"action":"pushed"}`)}
+ if webhookEventAllowedByTriggerScope(filters, env) {
+ t.Fatal("undeclared event should be filtered")
+ }
+}
+
+func TestWebhookEventAllowedByTriggerScope_FiltersUndeclaredAction(t *testing.T) {
+ filters := []byte(`[{"event":"workflow_run","actions":["completed"]}]`)
+ env := WebhookEnvelope{Event: "github.workflow_run.in_progress", EventPayload: json.RawMessage(`{"action":"in_progress"}`)}
+ if webhookEventAllowedByTriggerScope(filters, env) {
+ t.Fatal("undeclared action should be filtered")
+ }
+}
+
+func TestWebhookEventAllowedByTriggerScope_AllowsDeclaredAction(t *testing.T) {
+ filters := []byte(`[{"event":"workflow_run","actions":["completed"]}]`)
+ env := WebhookEnvelope{Event: "github.workflow_run.completed", EventPayload: json.RawMessage(`{"action":"completed"}`)}
+ if !webhookEventAllowedByTriggerScope(filters, env) {
+ t.Fatal("declared action should be allowed")
+ }
+}
+
+func TestWebhookEventAllowedByTriggerScope_AnyActionWhenEmpty(t *testing.T) {
+ filters := []byte(`[{"event":"workflow_run"}]`)
+ env := WebhookEnvelope{Event: "github.workflow_run.in_progress", EventPayload: json.RawMessage(`{"action":"in_progress"}`)}
+ if !webhookEventAllowedByTriggerScope(filters, env) {
+ t.Fatal("empty actions should allow any action for the event")
+ }
+}
+
+// TestWebhookEventAllowedByTriggerScope_MultipleFiltersSameEvent pins the
+// fix for PR #3231 review: the matcher used to return false as soon as it
+// hit the first event-name match whose actions didn't line up, which made
+// later filters covering the same event but different actions unreachable
+// (order-dependent silent drops). The fix is to keep scanning and only
+// short-circuit on a positive match.
+func TestWebhookEventAllowedByTriggerScope_MultipleFiltersSameEvent(t *testing.T) {
+ filters := []byte(`[
+ {"event":"workflow_run","actions":["completed"]},
+ {"event":"workflow_run","actions":["requested"]}
+ ]`)
+
+ completed := WebhookEnvelope{
+ Event: "github.workflow_run.completed",
+ EventPayload: json.RawMessage(`{"action":"completed"}`),
+ }
+ if !webhookEventAllowedByTriggerScope(filters, completed) {
+ t.Fatal("workflow_run.completed should match the first filter")
+ }
+
+ requested := WebhookEnvelope{
+ Event: "github.workflow_run.requested",
+ EventPayload: json.RawMessage(`{"action":"requested"}`),
+ }
+ if !webhookEventAllowedByTriggerScope(filters, requested) {
+ t.Fatal("workflow_run.requested should match the second filter — pre-fix this silently dropped")
+ }
+
+ inProgress := WebhookEnvelope{
+ Event: "github.workflow_run.in_progress",
+ EventPayload: json.RawMessage(`{"action":"in_progress"}`),
+ }
+ if webhookEventAllowedByTriggerScope(filters, inProgress) {
+ t.Fatal("workflow_run.in_progress is in neither filter and should be filtered out")
+ }
+}
+
+// TestWebhookEventAllowedByTriggerScope_MalformedDenies pins the
+// fail-closed behavior for corrupted rows. Strict write-time validation
+// (validateWebhookEventFilters) is the primary defense; this is the
+// defense-in-depth check for "what if a malformed row somehow exists".
+func TestWebhookEventAllowedByTriggerScope_MalformedDenies(t *testing.T) {
+ corrupt := []byte(`{not a json array}`)
+ env := WebhookEnvelope{
+ Event: "github.workflow_run.completed",
+ EventPayload: json.RawMessage(`{"action":"completed"}`),
+ }
+ if webhookEventAllowedByTriggerScope(corrupt, env) {
+ t.Fatal("malformed event_filters must fail closed (deny), never widen the allowlist")
+ }
+}
+
+func TestWebhookEventAllowedByTriggerScope_MultipleFilters(t *testing.T) {
+ filters := []byte(`[{"event":"workflow_run","actions":["completed"]},{"event":"check_suite","actions":["completed","failure"]}]`)
+
+ allowed1 := WebhookEnvelope{Event: "github.check_suite.completed", EventPayload: json.RawMessage(`{"action":"completed"}`)}
+ if !webhookEventAllowedByTriggerScope(filters, allowed1) {
+ t.Fatal("check_suite.completed should be allowed")
+ }
+
+ allowed2 := WebhookEnvelope{Event: "github.check_suite.failure", EventPayload: json.RawMessage(`{"action":"failure"}`)}
+ if !webhookEventAllowedByTriggerScope(filters, allowed2) {
+ t.Fatal("check_suite.failure should be allowed")
+ }
+
+ filtered := WebhookEnvelope{Event: "github.check_suite.requested", EventPayload: json.RawMessage(`{"action":"requested"}`)}
+ if webhookEventAllowedByTriggerScope(filters, filtered) {
+ t.Fatal("check_suite.requested should be filtered")
+ }
+}
+
+func TestSplitWebhookEvent(t *testing.T) {
+ tests := []struct {
+ input string
+ wantProvider string
+ wantName string
+ wantAction string
+ }{
+ {"github.workflow_run.completed", "github", "workflow_run", "completed"},
+ {"github.push", "github", "push", ""},
+ {"gitlab.Merge Request Hook", "gitlab", "Merge Request Hook", ""},
+ {"webhook.received", "", "webhook", "received"},
+ {"custom", "", "custom", ""},
+ }
+ for _, tc := range tests {
+ p, n, a := splitWebhookEvent(tc.input)
+ if p != tc.wantProvider || n != tc.wantName || a != tc.wantAction {
+ t.Fatalf("splitWebhookEvent(%q) = (%q, %q, %q), want (%q, %q, %q)",
+ tc.input, p, n, a, tc.wantProvider, tc.wantName, tc.wantAction)
+ }
+ }
+}
diff --git a/server/migrations/110_autopilot_trigger_event_filters.down.sql b/server/migrations/110_autopilot_trigger_event_filters.down.sql
new file mode 100644
index 0000000000..d6c3812b0c
--- /dev/null
+++ b/server/migrations/110_autopilot_trigger_event_filters.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE autopilot_trigger
+ DROP COLUMN IF EXISTS event_filters;
diff --git a/server/migrations/110_autopilot_trigger_event_filters.up.sql b/server/migrations/110_autopilot_trigger_event_filters.up.sql
new file mode 100644
index 0000000000..94c93b1e82
--- /dev/null
+++ b/server/migrations/110_autopilot_trigger_event_filters.up.sql
@@ -0,0 +1,5 @@
+-- Add event_filters to autopilot_trigger so webhook triggers can declare
+-- which events/actions they care about. NULL means "accept all" (backward
+-- compatible). JSONB shape: [{"event": "workflow_run", "actions": ["completed"]}, …]
+ALTER TABLE autopilot_trigger
+ ADD COLUMN event_filters JSONB;
diff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.go
index ca301b00e8..3d5fd747aa 100644
--- a/server/pkg/db/generated/autopilot.sql.go
+++ b/server/pkg/db/generated/autopilot.sql.go
@@ -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, t.provider, t.signing_secret, 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, t.event_filters, a.workspace_id AS autopilot_workspace_id
`
type ClaimDueScheduleTriggersRow struct {
@@ -58,6 +58,7 @@ type ClaimDueScheduleTriggersRow struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Provider string `json:"provider"`
SigningSecret pgtype.Text `json:"signing_secret"`
+ EventFilters []byte `json:"event_filters"`
AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
}
@@ -90,6 +91,7 @@ func (q *Queries) ClaimDueScheduleTriggers(ctx context.Context) ([]ClaimDueSched
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
&i.AutopilotWorkspaceID,
); err != nil {
return nil, err
@@ -279,12 +281,13 @@ 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, provider
+ next_run_at, webhook_token, label, provider, event_filters
) VALUES (
$1, $2, $3, $4, $5,
$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
+ COALESCE($9::text, 'generic'),
+ $10
+) 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, event_filters
`
type CreateAutopilotTriggerParams struct {
@@ -297,6 +300,7 @@ type CreateAutopilotTriggerParams struct {
WebhookToken pgtype.Text `json:"webhook_token"`
Label pgtype.Text `json:"label"`
Provider pgtype.Text `json:"provider"`
+ EventFilters []byte `json:"event_filters"`
}
func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilotTriggerParams) (AutopilotTrigger, error) {
@@ -310,6 +314,7 @@ func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilo
arg.WebhookToken,
arg.Label,
arg.Provider,
+ arg.EventFilters,
)
var i AutopilotTrigger
err := row.Scan(
@@ -327,6 +332,7 @@ func (q *Queries) CreateAutopilotTrigger(ctx context.Context, arg CreateAutopilo
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
)
return i, err
}
@@ -484,7 +490,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, provider, signing_secret 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, event_filters FROM autopilot_trigger
WHERE id = $1
`
@@ -506,12 +512,13 @@ func (q *Queries) GetAutopilotTrigger(ctx context.Context, id pgtype.UUID) (Auto
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
)
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, t.provider, t.signing_secret, 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, t.event_filters, a.workspace_id AS autopilot_workspace_id
FROM autopilot_trigger t
JOIN autopilot a ON a.id = t.autopilot_id
WHERE t.kind = 'webhook'
@@ -533,6 +540,7 @@ type GetWebhookTriggerByTokenRow struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Provider string `json:"provider"`
SigningSecret pgtype.Text `json:"signing_secret"`
+ EventFilters []byte `json:"event_filters"`
AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
}
@@ -559,6 +567,7 @@ func (q *Queries) GetWebhookTriggerByToken(ctx context.Context, webhookToken pgt
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
&i.AutopilotWorkspaceID,
)
return i, err
@@ -614,7 +623,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, provider, signing_secret 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, event_filters FROM autopilot_trigger
WHERE autopilot_id = $1
ORDER BY created_at ASC
`
@@ -646,6 +655,7 @@ func (q *Queries) ListAutopilotTriggers(ctx context.Context, autopilotID pgtype.
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
); err != nil {
return nil, err
}
@@ -711,7 +721,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, t.provider, t.signing_secret, 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, t.event_filters, a.workspace_id AS autopilot_workspace_id
FROM autopilot_trigger t
JOIN autopilot a ON t.autopilot_id = a.id
WHERE t.kind = 'schedule'
@@ -736,6 +746,7 @@ type RecoverLostTriggersRow struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Provider string `json:"provider"`
SigningSecret pgtype.Text `json:"signing_secret"`
+ EventFilters []byte `json:"event_filters"`
AutopilotWorkspaceID pgtype.UUID `json:"autopilot_workspace_id"`
}
@@ -769,6 +780,7 @@ func (q *Queries) RecoverLostTriggers(ctx context.Context) ([]RecoverLostTrigger
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
&i.AutopilotWorkspaceID,
); err != nil {
return nil, err
@@ -787,7 +799,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, provider, signing_secret
+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, event_filters
`
type RotateAutopilotTriggerWebhookTokenParams struct {
@@ -816,6 +828,7 @@ func (q *Queries) RotateAutopilotTriggerWebhookToken(ctx context.Context, arg Ro
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
)
return i, err
}
@@ -908,7 +921,7 @@ 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
+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, event_filters
`
type SetAutopilotTriggerSigningSecretParams struct {
@@ -939,6 +952,7 @@ func (q *Queries) SetAutopilotTriggerSigningSecret(ctx context.Context, arg SetA
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
)
return i, err
}
@@ -948,7 +962,7 @@ 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, provider, signing_secret
+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, event_filters
`
type SetAutopilotTriggerWebhookTokenParams struct {
@@ -979,6 +993,7 @@ func (q *Queries) SetAutopilotTriggerWebhookToken(ctx context.Context, arg SetAu
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
)
return i, err
}
@@ -1324,9 +1339,10 @@ UPDATE autopilot_trigger SET
timezone = COALESCE($4, timezone),
next_run_at = $5,
label = COALESCE($6, label),
+ event_filters = COALESCE($7, event_filters),
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, provider, signing_secret
+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, event_filters
`
type UpdateAutopilotTriggerParams struct {
@@ -1336,6 +1352,7 @@ type UpdateAutopilotTriggerParams struct {
Timezone pgtype.Text `json:"timezone"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
Label pgtype.Text `json:"label"`
+ EventFilters []byte `json:"event_filters"`
}
func (q *Queries) UpdateAutopilotTrigger(ctx context.Context, arg UpdateAutopilotTriggerParams) (AutopilotTrigger, error) {
@@ -1346,6 +1363,7 @@ func (q *Queries) UpdateAutopilotTrigger(ctx context.Context, arg UpdateAutopilo
arg.Timezone,
arg.NextRunAt,
arg.Label,
+ arg.EventFilters,
)
var i AutopilotTrigger
err := row.Scan(
@@ -1363,6 +1381,7 @@ func (q *Queries) UpdateAutopilotTrigger(ctx context.Context, arg UpdateAutopilo
&i.UpdatedAt,
&i.Provider,
&i.SigningSecret,
+ &i.EventFilters,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index a37b26ae75..4b6da03c02 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -165,6 +165,7 @@ type AutopilotTrigger struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
Provider string `json:"provider"`
SigningSecret pgtype.Text `json:"signing_secret"`
+ EventFilters []byte `json:"event_filters"`
}
type ChatMessage struct {
diff --git a/server/pkg/db/queries/autopilot.sql b/server/pkg/db/queries/autopilot.sql
index 1c307208b2..d35101aa80 100644
--- a/server/pkg/db/queries/autopilot.sql
+++ b/server/pkg/db/queries/autopilot.sql
@@ -64,11 +64,12 @@ WHERE id = $1;
-- name: CreateAutopilotTrigger :one
INSERT INTO autopilot_trigger (
autopilot_id, kind, enabled, cron_expression, timezone,
- next_run_at, webhook_token, label, provider
+ next_run_at, webhook_token, label, provider, event_filters
) VALUES (
$1, $2, $3, sqlc.narg('cron_expression'), sqlc.narg('timezone'),
sqlc.narg('next_run_at'), sqlc.narg('webhook_token'), sqlc.narg('label'),
- COALESCE(sqlc.narg('provider')::text, 'generic')
+ COALESCE(sqlc.narg('provider')::text, 'generic'),
+ sqlc.narg('event_filters')
) RETURNING *;
-- name: UpdateAutopilotTrigger :one
@@ -78,6 +79,7 @@ UPDATE autopilot_trigger SET
timezone = COALESCE(sqlc.narg('timezone'), timezone),
next_run_at = sqlc.narg('next_run_at'),
label = COALESCE(sqlc.narg('label'), label),
+ event_filters = COALESCE(sqlc.narg('event_filters'), event_filters),
updated_at = now()
WHERE id = $1
RETURNING *;