Skip to content

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

Go

fix(autopilots): match GitLab pipeline and job statuses (#10810)

Bohan Jiang633fc580d266
diff --git a/apps/docs/content/docs/autopilots.fr.mdx b/apps/docs/content/docs/autopilots.fr.mdx
index d93a5c7c74..eb57154166 100644
--- a/apps/docs/content/docs/autopilots.fr.mdx
+++ b/apps/docs/content/docs/autopilots.fr.mdx
@@ -102,7 +102,7 @@ Indiquez des verbes d'action (`open`, `update`, `reopen`, `merge`, `close`) plut
- `Issue Hook` avec `close` accepte les tickets fermés.
- `Note Hook` avec `create` accepte les nouveaux commentaires ; un commentaire modifié envoie `update`.
- Une règle GitLab sans actions accepte tous les événements portant ce nom.
-- Les hooks de pipeline et de job indiquent leur résultat dans `object_attributes.status` et `build_status`, qui ne sont pas lus comme des actions. Laissez les actions vides et ajoutez plutôt une condition sur ce champ, par exemple `object_attributes.status` égal à `failed`.
+- Pour ne lancer une exécution qu’en cas d’échec, définissez **Actions** sur `failed` avec `Pipeline Hook` (`object_kind: "pipeline"`, statut dans `object_attributes.status`) ou `Job Hook` (`object_kind: "build"`, statut dans `build_status`). Les autres statuts, comme `success` et `running`, sont filtrés ; laisser Actions vide accepte tous les statuts de cet événement. Ces champs de statut CI ne s’appliquent qu’à leur type d’objet respectif. Consultez les [charges utiles des événements GitLab](https://docs.gitlab.com/user/project/integrations/webhook_events/#pipeline-events).
Chaque règle peut aussi porter des `conditions` sur les champs de la charge utile : cliquez sur **Ajouter une condition** dans la règle, ou définissez-les via l'API. Toutes les conditions doivent être vraies pour que la règle corresponde ; un événement filtré est ignoré avant le démarrage de toute exécution. `path` parcourt la charge utile avec des points : un nombre indexe un tableau et `*` désigne n'importe quel élément (`pull_request.labels.*.name`). `op` vaut `equals`, `not_equals`, `contains`, `in` ou `exists`, et `ignore_case` s'applique au texte. Avec `*`, `equals`, `contains`, `in` et `exists` sont vraies si un élément correspond, et `not_equals` si aucun ne correspond. Un champ absent ne correspond jamais, et `exists` ignore `null`. Par exemple, cette règle n'accepte que les pull requests prêtes, étiquetées `needs-review`, qui ciblent `main` ou `release` et n'ont pas été ouvertes par un bot :
diff --git a/apps/docs/content/docs/autopilots.ja.mdx b/apps/docs/content/docs/autopilots.ja.mdx
index 466808e52d..f3a535cb94 100644
--- a/apps/docs/content/docs/autopilots.ja.mdx
+++ b/apps/docs/content/docs/autopilots.ja.mdx
@@ -102,7 +102,7 @@ Actions には状態を表す語(`opened`、`merged`、`closed`)ではなく
- `Issue Hook` に `close` を指定すると、クローズされた issue を受け取ります。
- `Note Hook` に `create` を指定すると、新しいコメントを受け取ります。コメントの編集では `update` が送られます。
- Actions が空の GitLab ルールは、そのイベント名のすべてのイベントを受け取ります。
-- Pipeline Hook と Job Hook の結果はそれぞれ `object_attributes.status` と `build_status` にあり、action としては読み取られません。Actions を空にして、そのフィールドに条件を追加してください(例: `object_attributes.status` が `failed` に等しい)。
+- 失敗時だけ実行するには、**Actions** を `failed` にし、イベント名に `Pipeline Hook`(`object_kind: "pipeline"`、状態は `object_attributes.status`)または `Job Hook`(`object_kind: "build"`、状態は `build_status`)を指定します。`success` や `running` などの状態は除外され、Actions を空にするとそのイベントのすべての状態を受け入れます。これらの CI 状態フィールドは、それぞれのオブジェクト種別にのみ適用されます。[GitLab のイベント payload](https://docs.gitlab.com/user/project/integrations/webhook_events/#pipeline-events)も参照してください。
各ルールには payload のフィールドに対する `conditions` も設定できます。ルールの **条件を追加** をクリックするか、API から設定します。すべての条件を満たしたときだけそのルールに一致し、除外されたイベントは実行が始まる前に無視されます。`path` はドット区切りで payload をたどり、数値は配列の添字、`*` は任意の要素を表します(`pull_request.labels.*.name`)。`op` は `equals`、`not_equals`、`contains`、`in`、`exists` のいずれかで、`ignore_case` はテキストに適用されます。`*` を使う場合、`equals`、`contains`、`in`、`exists` はいずれかの要素が一致すれば成立し、`not_equals` はどの要素も一致しないときに成立します。フィールドが存在しない場合は一致せず、`exists` は `null` を無視します。たとえば次のルールは、準備ができていて `needs-review` ラベルが付き、`main` または `release` を対象とし、bot が作成したものではない pull request だけを受け取ります。
diff --git a/apps/docs/content/docs/autopilots.ko.mdx b/apps/docs/content/docs/autopilots.ko.mdx
index b46b7699b1..d8bf97494b 100644
--- a/apps/docs/content/docs/autopilots.ko.mdx
+++ b/apps/docs/content/docs/autopilots.ko.mdx
@@ -102,7 +102,7 @@ Actions에는 상태 단어(`opened`, `merged`, `closed`)가 아니라 동작
- `Issue Hook`에 `close`를 지정하면 닫힌 issue를 받습니다.
- `Note Hook`에 `create`를 지정하면 새 댓글을 받습니다. 댓글을 수정하면 `update`가 전송됩니다.
- Actions가 비어 있는 GitLab 규칙은 해당 이벤트 이름의 모든 이벤트를 받습니다.
-- Pipeline Hook과 Job Hook은 결과를 각각 `object_attributes.status`와 `build_status`에 담으며, 이 값은 action으로 읽히지 않습니다. Actions를 비워 두고 해당 필드에 조건을 추가하세요. 예: `object_attributes.status`가 `failed`와 같음.
+- 실패할 때만 실행하려면 **Actions**를 `failed`로 설정하고 이벤트 이름에 `Pipeline Hook`(`object_kind: "pipeline"`, 상태는 `object_attributes.status`) 또는 `Job Hook`(`object_kind: "build"`, 상태는 `build_status`)을 입력하세요. `success`, `running` 등 다른 상태는 필터링되며, Actions를 비우면 해당 이벤트의 모든 상태를 받습니다. 이 CI 상태 필드는 각각의 객체 유형에만 적용됩니다. [GitLab 이벤트 payload](https://docs.gitlab.com/user/project/integrations/webhook_events/#pipeline-events)를 참고하세요.
각 규칙에는 payload 필드에 대한 `conditions`도 지정할 수 있습니다. 규칙의 **조건 추가**를 클릭하거나 API로 설정하세요. 모든 조건을 만족해야 해당 규칙이 일치하며, 걸러진 이벤트는 실행이 시작되기 전에 무시됩니다. `path`는 점으로 payload를 따라가며, 숫자는 배열 인덱스이고 `*`는 임의의 요소를 뜻합니다(`pull_request.labels.*.name`). `op`는 `equals`, `not_equals`, `contains`, `in`, `exists` 중 하나이며, `ignore_case`는 텍스트에 적용됩니다. `*`를 쓰면 `equals`, `contains`, `in`, `exists`는 요소 하나라도 일치하면 성립하고, `not_equals`는 어떤 요소도 일치하지 않을 때 성립합니다. 필드가 없으면 일치하지 않으며, `exists`는 `null`을 무시합니다. 예를 들어 아래 규칙은 준비된 상태이고 `needs-review` 라벨이 있으며 `main` 또는 `release`를 대상으로 하고 봇이 열지 않은 pull request만 받습니다.
diff --git a/apps/docs/content/docs/autopilots.mdx b/apps/docs/content/docs/autopilots.mdx
index 19e63b6d26..dc7d32fcbf 100644
--- a/apps/docs/content/docs/autopilots.mdx
+++ b/apps/docs/content/docs/autopilots.mdx
@@ -102,7 +102,7 @@ List action words (`open`, `update`, `reopen`, `merge`, `close`) rather than sta
- `Issue Hook` with `close` accepts closed issues.
- `Note Hook` with `create` accepts new comments; edited comments send `update`.
- A GitLab rule with no actions accepts every event with that event name.
-- Pipeline and job hooks report their result in `object_attributes.status` and `build_status`, which aren't read as actions. Leave the actions empty and add a condition on that field instead, for example `object_attributes.status` equals `failed`.
+- To run only on failures, set **Actions** to `failed` with either `Pipeline Hook` (`object_kind: "pipeline"`, status from `object_attributes.status`) or `Job Hook` (`object_kind: "build"`, status from `build_status`). Other statuses, such as `success` and `running`, are filtered out; leaving Actions empty accepts every status for that event. These CI status fields apply only to their respective object kinds. See [GitLab's event payloads](https://docs.gitlab.com/user/project/integrations/webhook_events/#pipeline-events).
Each rule can also carry `conditions` on payload fields: click **Add condition** on the rule, or set them through the API. Every condition must hold for the rule to match; a filtered event is ignored before any run starts. `path` walks the payload with dots, where a number indexes an array and `*` means any element (`pull_request.labels.*.name`). `op` is `equals`, `not_equals`, `contains`, `in` or `exists`, and `ignore_case` applies to text. With `*`, `equals`, `contains`, `in` and `exists` hold if any element matches, and `not_equals` holds if none does. A missing field never matches, and `exists` ignores `null`. For example, this rule only accepts ready pull requests labelled `needs-review` that target `main` or `release` and weren't opened by a bot:
diff --git a/apps/docs/content/docs/autopilots.zh-Hant.mdx b/apps/docs/content/docs/autopilots.zh-Hant.mdx
index 6378929cb5..d6052207e2 100644
--- a/apps/docs/content/docs/autopilots.zh-Hant.mdx
+++ b/apps/docs/content/docs/autopilots.zh-Hant.mdx
@@ -102,7 +102,7 @@ Actions 請填寫動作詞(`open`、`update`、`reopen`、`merge`、`close`)
- `Issue Hook` 加 `close`:接收被關閉的 issue。
- `Note Hook` 加 `create`:接收新留言;編輯留言傳送的是 `update`。
- GitLab 規則的 Actions 留空時,接收該事件名下的所有事件。
-- Pipeline Hook 和 Job Hook 的結果分別在 `object_attributes.status` 和 `build_status` 中,不會被當作 action 讀取。請把 Actions 留空,再對該欄位新增條件,例如 `object_attributes.status` 等於 `failed`。
+- 只在失敗時執行,可以將 **Actions** 設為 `failed`,事件名填寫 `Pipeline Hook`(`object_kind: "pipeline"`,狀態讀取 `object_attributes.status`)或 `Job Hook`(`object_kind: "build"`,狀態讀取 `build_status`)。`success`、`running` 等其他狀態會被過濾;Actions 留空則接收該事件的所有狀態。這兩個 CI 狀態欄位僅用於各自的物件類型,參見 [GitLab 事件 payload](https://docs.gitlab.com/user/project/integrations/webhook_events/#pipeline-events)。
每條規則還可以設定針對本文欄位的 `conditions`:點選該規則的 **新增條件**,或透過 API 設定。同一條規則的全部條件都要符合,多條規則之間符合任意一條即可。`path` 用點號存取事件本文,數字表示陣列索引,`*` 表示任意元素(例如 `pull_request.labels.*.name`)。操作支援 `equals`、`not_equals`、`contains`、`in` 和 `exists`,`ignore_case` 忽略文字大小寫。使用 `*` 時,前四種操作中除 `not_equals` 外,只要有一個元素符合即可;`not_equals` 要求沒有元素等於指定值。`exists` 忽略 `null`。字串與布林值必須使用正確類型,例如 `"false"` 與 `false` 不同。
diff --git a/apps/docs/content/docs/autopilots.zh.mdx b/apps/docs/content/docs/autopilots.zh.mdx
index bc54517675..ad80dab5cd 100644
--- a/apps/docs/content/docs/autopilots.zh.mdx
+++ b/apps/docs/content/docs/autopilots.zh.mdx
@@ -102,7 +102,7 @@ Actions 请填写动作词(`open`、`update`、`reopen`、`merge`、`close`)
- `Issue Hook` 加 `close`:接收被关闭的 issue。
- `Note Hook` 加 `create`:接收新评论;编辑评论发送的是 `update`。
- GitLab 规则的 Actions 留空时,接收该事件名下的所有事件。
-- Pipeline Hook 和 Job Hook 的结果分别在 `object_attributes.status` 和 `build_status` 中,不会被当作 action 读取。请把 Actions 留空,再对该字段添加条件,例如 `object_attributes.status` 等于 `failed`。
+- 只在失败时运行,可以将 **Actions** 设为 `failed`,事件名填写 `Pipeline Hook`(`object_kind: "pipeline"`,状态读取 `object_attributes.status`)或 `Job Hook`(`object_kind: "build"`,状态读取 `build_status`)。`success`、`running` 等其他状态会被过滤;Actions 留空则接收该事件的所有状态。这两个 CI 状态字段仅用于各自的对象类型,参见 [GitLab 事件 payload](https://docs.gitlab.com/user/project/integrations/webhook_events/#pipeline-events)。
每条规则还可以设置针对 payload 字段的 `conditions`:点击该规则的 **添加条件**,或通过 API 设置。所有条件都满足时该规则才命中;被过滤的事件在任何运行开始前就会被忽略。`path` 用点号访问 payload,数字表示数组下标,`*` 表示任意元素(`pull_request.labels.*.name`)。`op` 可选 `equals`、`not_equals`、`contains`、`in` 或 `exists`,`ignore_case` 作用于文本。使用 `*` 时,`equals`、`contains`、`in` 和 `exists` 只要有一个元素匹配即成立,`not_equals` 要求没有任何元素匹配。字段不存在时永远不命中,`exists` 会忽略 `null`。例如,下面这条规则只接收已就绪、带有 `needs-review` 标签、目标分支为 `main` 或 `release`、且不是由机器人创建的 pull request:
diff --git a/server/internal/handler/autopilot_webhook.go b/server/internal/handler/autopilot_webhook.go
index 7e88344aaa..3be4937d28 100644
--- a/server/internal/handler/autopilot_webhook.go
+++ b/server/internal/handler/autopilot_webhook.go
@@ -892,6 +892,17 @@ func webhookActionCandidates(eventAction string, payload json.RawMessage) []stri
add(v)
}
}
+ // Pipeline status is separate from MR/Issue actions and states.
+ if obj["object_kind"] == "pipeline" {
+ if status, ok := attrs["status"].(string); ok {
+ add(status)
+ }
+ }
+ }
+ if obj["object_kind"] == "build" {
+ if status, ok := obj["build_status"].(string); ok {
+ add(status)
+ }
}
}
out := make([]string, 0, len(seen))
diff --git a/server/internal/handler/autopilot_webhook_gitlab_test.go b/server/internal/handler/autopilot_webhook_gitlab_test.go
new file mode 100644
index 0000000000..60fb7af334
--- /dev/null
+++ b/server/internal/handler/autopilot_webhook_gitlab_test.go
@@ -0,0 +1,181 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestWebhookEventAllowedByTriggerScope_GitLabCIStatusFields(t *testing.T) {
+ for _, tc := range []struct {
+ name, event, payload string
+ allowed bool
+ }{
+ {"pipeline failed", "Pipeline Hook", `{"object_kind":"pipeline","object_attributes":{"status":"failed"}}`, true},
+ {"job failed", "Job Hook", `{"object_kind":"build","build_status":"failed"}`, true},
+ {"pipeline missing status", "Pipeline Hook", `{"object_kind":"pipeline","object_attributes":{}}`, false},
+ {"pipeline null status", "Pipeline Hook", `{"object_kind":"pipeline","object_attributes":{"status":null}}`, false},
+ {"pipeline non-string status", "Pipeline Hook", `{"object_kind":"pipeline","object_attributes":{"status":42}}`, false},
+ {"pipeline malformed attributes", "Pipeline Hook", `{"object_kind":"pipeline","object_attributes":[]}`, false},
+ {"job missing status", "Job Hook", `{"object_kind":"build"}`, false},
+ {"job null status", "Job Hook", `{"object_kind":"build","build_status":null}`, false},
+ {"job non-string status", "Job Hook", `{"object_kind":"build","build_status":false}`, false},
+ {"job does not use pipeline status", "Job Hook", `{"object_kind":"build","object_attributes":{"status":"failed"}}`, false},
+ {"pipeline does not use job status", "Pipeline Hook", `{"object_kind":"pipeline","build_status":"failed"}`, false},
+ {"MR ignores CI fields", "Merge Request Hook", `{"object_kind":"merge_request","object_attributes":{"action":"open","state":"opened","status":"failed"},"build_status":"failed"}`, false},
+ {"issue ignores CI fields", "Issue Hook", `{"object_kind":"issue","object_attributes":{"action":"open","state":"opened","status":"failed"},"build_status":"failed"}`, false},
+ {"note ignores CI fields", "Note Hook", `{"object_kind":"note","object_attributes":{"action":"create","status":"failed"},"build_status":"failed"}`, false},
+ {"missing kind ignores CI fields", "Pipeline Hook", `{"object_attributes":{"status":"failed"},"build_status":"failed"}`, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ headers := make(http.Header)
+ headers.Set("X-Gitlab-Event", tc.event)
+ envelope, err := normalizeWebhookPayload([]byte(tc.payload), headers)
+ if err != nil {
+ t.Fatal(err)
+ }
+ filters, err := json.Marshal([]WebhookEventFilter{{Event: tc.event, Actions: []string{"failed"}}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ decision := evaluateWebhookTriggerScope(filters, envelope)
+ if decision.Allowed != tc.allowed || (!tc.allowed && decision.ReasonCode != "event_filtered") {
+ t.Fatalf("decision=%+v, want allowed=%v", decision, tc.allowed)
+ }
+ })
+ }
+}
+
+func gitLabCIWebhookBody(event, status string) []byte {
+ if event == "Pipeline Hook" {
+ return []byte(fmt.Sprintf(`{"object_kind":"pipeline","object_attributes":{"id":31,"ref":"main","status":%q},"project":{"id":1},"builds":[{"id":1977,"status":"failed"}]}`, status))
+ }
+ return []byte(fmt.Sprintf(`{"object_kind":"build","build_id":1977,"build_name":"test","build_stage":"test","build_status":%q,"pipeline_id":31,"project_id":1,"commit":{"id":31,"status":"failed"}}`, status))
+}
+
+func gitLabCIWebhookFixture(t *testing.T, event string, actions []string) (string, AutopilotTriggerResponse) {
+ t.Helper()
+ agentID := dbfx.Agent(t, "GitLab CI webhook agent", testRuntimeID)
+ apID := dbfx.Insert(t, "autopilot", testutil.Cols{
+ "workspace_id": testWorkspaceID, "title": "GitLab CI webhook",
+ "assignee_id": agentID, "status": "active", "execution_mode": "run_only",
+ "created_by_type": "member", "created_by_id": testUserID,
+ })
+ trig := createWebhookTriggerWithFilters(t, apID, []WebhookEventFilter{{Event: event, Actions: actions}})
+ dbfx.Cleanup(t, `DELETE FROM autopilot_trigger WHERE autopilot_id = $1`, apID)
+ dbfx.Cleanup(t, `DELETE FROM webhook_delivery WHERE autopilot_id = $1`, apID)
+ dbfx.Cleanup(t, `DELETE FROM autopilot_run WHERE autopilot_id = $1`, apID)
+ dbfx.Cleanup(t, `DELETE FROM agent_task_queue WHERE agent_id = $1`, agentID)
+ setSigningSecretViaHandler(t, apID, trig.ID, testSigningSecret)
+ return apID, trig
+}
+
+func TestWebhookGitLabCI_IngressAndRecoveredWorker(t *testing.T) {
+ for _, event := range []string{"Pipeline Hook", "Job Hook"} {
+ for _, worker := range []bool{false, true} {
+ for _, tc := range []struct {
+ name, status string
+ actions []string
+ allowed bool
+ }{
+ {"failed matches", "failed", []string{"failed"}, true},
+ {"success filtered", "success", []string{"failed"}, false},
+ {"running filtered", "running", []string{"failed"}, false},
+ {"empty actions", "success", nil, true},
+ } {
+ t.Run(fmt.Sprintf("%s/worker=%v/%s", event, worker, tc.name), func(t *testing.T) {
+ ctx := context.Background()
+ apID, trig := gitLabCIWebhookFixture(t, event, tc.actions)
+ body := gitLabCIWebhookBody(event, tc.status)
+ var deliveryID string
+ if worker {
+ // Recover a verified delivery before ingress admitted a run.
+ headers := make(http.Header)
+ headers.Set("X-Gitlab-Event", event)
+ row, _, err := testHandler.persistInboundDelivery(httptest.NewRequest(http.MethodPost, "/webhook", nil), persistDeliveryInput{
+ WorkspaceID: parseUUID(testWorkspaceID), AutopilotID: parseUUID(apID), TriggerID: parseUUID(trig.ID),
+ Provider: "generic", Event: "gitlab." + event, SignatureStatus: sigStatusValid,
+ RawBody: body, SelectedHeaders: selectedHeadersJSON(headers),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ deliveryID = uuidToString(row.ID)
+ } else {
+ w := postWebhook(t, *trig.WebhookToken, body, map[string]string{
+ "X-Gitlab-Event": event, "X-Hub-Signature-256": signBody(testSigningSecret, body),
+ })
+ if tc.allowed {
+ deliveryID = requireAcceptedWebhookResponse(t, w)
+ } else {
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatal(err)
+ }
+ if w.Code != http.StatusOK || resp["status"] != "ignored" || resp["reason"] != "event_filtered" || resp["run_id"] != nil {
+ t.Fatalf("unexpected ingress response: %d %v", w.Code, resp)
+ }
+ deliveryID, _ = resp["delivery_id"].(string)
+ }
+ }
+ row := processQueuedWebhookDelivery(t, deliveryID)
+ wantStatus, wantRuns := deliveryStatusIgnored, 0
+ if tc.allowed {
+ wantStatus, wantRuns = deliveryStatusDispatched, 1
+ }
+ if row.Status != wantStatus || row.AutopilotRunID.Valid != tc.allowed || row.Event != "gitlab."+event || row.SignatureStatus != sigStatusValid {
+ t.Fatalf("delivery status=%s run=%v event=%q signature=%s", row.Status, row.AutopilotRunID.Valid, row.Event, row.SignatureStatus)
+ }
+ if !tc.allowed && (!row.Error.Valid || row.Error.String != "event_filtered") {
+ t.Fatalf("filtered delivery error=%v", row.Error)
+ }
+ runs, err := testHandler.Queries.ListAutopilotRuns(ctx, db.ListAutopilotRunsParams{AutopilotID: parseUUID(apID), Limit: 10})
+ if err != nil || len(runs) != wantRuns {
+ t.Fatalf("runs=%d, want %d, err=%v", len(runs), wantRuns, err)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestWebhookGitLabCI_SignatureBeforeFiltering(t *testing.T) {
+ for _, event := range []string{"Pipeline Hook", "Job Hook"} {
+ for _, status := range []string{"failed", "success"} {
+ for _, signature := range []string{"", "sha256=deadbeef"} {
+ t.Run(fmt.Sprintf("%s/%s/signature=%q", event, status, signature), func(t *testing.T) {
+ apID, trig := gitLabCIWebhookFixture(t, event, []string{"failed"})
+ w := postWebhook(t, *trig.WebhookToken, gitLabCIWebhookBody(event, status), map[string]string{
+ "X-Gitlab-Event": event, "X-Hub-Signature-256": signature,
+ })
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatal(err)
+ }
+ wantReason := "invalid_signature"
+ if signature == "" {
+ wantReason = "missing_signature"
+ }
+ if w.Code != http.StatusUnauthorized || resp["status"] != "rejected" || resp["reason"] != wantReason || resp["run_id"] != nil {
+ t.Fatalf("unexpected signature response: %d %v", w.Code, resp)
+ }
+ deliveryID, _ := resp["delivery_id"].(string)
+ row := processQueuedWebhookDelivery(t, deliveryID)
+ if row.Status != deliveryStatusRejected || row.AutopilotRunID.Valid {
+ t.Fatalf("rejected delivery status=%s run=%v", row.Status, row.AutopilotRunID.Valid)
+ }
+ runs, err := testHandler.Queries.ListAutopilotRuns(context.Background(), db.ListAutopilotRunsParams{AutopilotID: parseUUID(apID), Limit: 10})
+ if err != nil || len(runs) != 0 {
+ t.Fatalf("rejected signature created %d runs, err=%v", len(runs), err)
+ }
+ })
+ }
+ }
+ }
+}