Skip to content

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

Go

feat(github): fan out PR/check_suite webhooks to all bound workspaces (MUL-4343) (#5218)

Bohan Jiang53f05cca5efd
diff --git a/apps/docs/content/docs/github-integration.mdx b/apps/docs/content/docs/github-integration.mdx
index 43e3392bc6..5d5b1095fc 100644
--- a/apps/docs/content/docs/github-integration.mdx
+++ b/apps/docs/content/docs/github-integration.mdx
@@ -20,6 +20,19 @@ There is no per-issue setup. The whole flow is identifier-driven.
Only the PR itself is mirrored. Commits, branch refs without an open PR, and CI check states are **not** modeled. The integration is intentionally narrow.
+## Multiple workspaces
+
+One GitHub App installation can be connected in **several** workspaces at once — for example when different teams in the same organization run separate workspaces. When it is, every connected workspace receives each repository's `pull_request` events **independently**:
+
+- Each workspace mirrors the PR and auto-links it against **its own** [issue prefix](/workspaces) and GitHub feature switches. A PR that references `MUL-1` and `ENG-2` links `MUL-1` in the workspace whose prefix is `MUL` and `ENG-2` in the one whose prefix is `ENG` — neither sees the other's issues.
+- Disconnecting the installation from one workspace only stops **that** workspace from receiving events; the others keep working.
+
+Repository scope is whatever you granted the GitHub App (all repositories, or a chosen subset). Connecting the installation in a workspace is itself the subscription — there is no separate per-repository selection inside Multica.
+
+<Callout type="warning">
+**Upgrading a self-host deployment:** event delivery is keyed on the GitHub connection, not on a workspace's code-repository list. If a workspace previously received a repo's PRs *without* connecting GitHub in that workspace (by listing the repo in its code-repositories entry alone), it will stop receiving events after this upgrade. To restore delivery, **connect the same GitHub installation** in that workspace under **Settings → GitHub**.
+</Callout>
+
## How identifiers are matched
The webhook extracts identifiers from three fields, in this order: **PR head branch**, **PR title**, **PR body**. The matcher is:
diff --git a/apps/docs/content/docs/github-integration.zh.mdx b/apps/docs/content/docs/github-integration.zh.mdx
index 5d563cdf4b..3d35ace5ff 100644
--- a/apps/docs/content/docs/github-integration.zh.mdx
+++ b/apps/docs/content/docs/github-integration.zh.mdx
@@ -20,6 +20,19 @@ import { Callout } from "fumadocs-ui/components/callout";
只镜像 PR 本身。Commit、没开 PR 的分支、CI 检查状态都**不**入库——集成有意保持窄边界。
+## 多个工作区
+
+同一个 GitHub App installation 可以同时连接到**多个**工作区——比如同一组织下不同团队各自用独立工作区。此时每个已连接的工作区都会**各自独立**收到每个仓库的 `pull_request` 事件:
+
+- 每个工作区各自镜像 PR,并按**自己的** [issue 前缀](/workspaces) 和 GitHub 功能开关做自动关联。一个同时引用 `MUL-1` 和 `ENG-2` 的 PR,会在前缀为 `MUL` 的工作区关联 `MUL-1`、在前缀为 `ENG` 的工作区关联 `ENG-2`,两边互不可见对方的 issue。
+- 从某个工作区断开连接,只会让**该**工作区停止接收事件,其它工作区照常工作。
+
+仓库范围由你授予 GitHub App 的权限决定(全部仓库或指定子集)。在工作区连接这个 installation 本身就是一次订阅——Multica 里不需要再单独逐仓库勾选。
+
+<Callout type="warning">
+**升级 self-host 部署时注意:** 事件投递以 GitHub 连接为准,而不是工作区的代码仓库列表。如果某个工作区之前是在**没有**连接 GitHub 的情况下、仅靠代码仓库列表里登记该仓库来接收 PR 事件,升级后它将不再收到事件。要恢复投递,需在该工作区的 **Settings → GitHub** 里**连接同一个 GitHub installation**。
+</Callout>
+
## 编号是怎么匹配的
Webhook 从三个字段抽取编号,顺序是:**PR head 分支** → **PR 标题** → **PR 正文**。匹配规则:
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.go
index 828d0b50b9..1f45430af7 100644
--- a/server/internal/handler/github.go
+++ b/server/internal/handler/github.go
@@ -818,20 +818,30 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {
// can attribute to a workspace, so drop it silently.
return
}
- // One installation can be bound to several workspaces; delivery is routed
- // per-repo, so the binding only supplies the delivering account and the
- // fallback workspace. The oldest binding is a deterministic fallback.
- inst := insts[0]
-
- // Route to the workspace that owns this repo, not the installation's single
- // workspace — one installation can serve repos across several workspaces.
- wsID := h.resolveWorkspaceForRepo(ctx, inst.WorkspaceID, inst.AccountLogin, p.Repository.Owner.Login, p.Repository.Name)
+ // #4855 lets one GitHub App installation bind to several workspaces. A
+ // repo's events belong to every bound workspace, so fan the delivery out:
+ // each workspace independently mirrors the PR and auto-links it against its
+ // own issues (its own prefix + github toggle). Repo scope is whatever GitHub
+ // authorized the installation for; we deliberately don't gate on the
+ // workspace.repos registry — that list is "code the agent clones", not a
+ // webhook subscription (MUL-4343).
+ for _, inst := range insts {
+ h.mirrorPullRequestForWorkspace(ctx, inst.WorkspaceID, inst.InstallationID, &p)
+ }
+}
+// mirrorPullRequestForWorkspace mirrors a pull_request webhook into a single
+// workspace: it upserts the PR row, replays any check_suite events that
+// arrived before the PR was mirrored, auto-links referenced issues (gated by
+// the workspace's github toggles), advances issues on terminal events, and
+// broadcasts the change. Invoked once per workspace bound to the delivering
+// installation.
+func (h *Handler) mirrorPullRequestForWorkspace(ctx context.Context, wsID pgtype.UUID, installationID int64, p *ghPullRequestPayload) {
state := derivePRState(p.PullRequest.State, p.PullRequest.Draft, p.PullRequest.Merged)
mergeable, clearMergeable := derivePRMergeableState(p.Action, p.PullRequest.MergeableState, baseRefChanged(p.Changes))
pr, err := h.Queries.UpsertGitHubPullRequest(ctx, db.UpsertGitHubPullRequestParams{
WorkspaceID: wsID,
- InstallationID: inst.InstallationID,
+ InstallationID: installationID,
RepoOwner: p.Repository.Owner.Login,
RepoName: p.Repository.Name,
PrNumber: p.PullRequest.Number,
@@ -1043,9 +1053,6 @@ func (h *Handler) handleCheckSuiteEvent(ctx context.Context, body []byte) {
if len(insts) == 0 {
return
}
- // Oldest binding is the deterministic routing fallback; see
- // handlePullRequestEvent.
- inst := insts[0]
if len(p.CheckSuite.PullRequests) == 0 {
// Forks emit suites whose `pull_requests` array is empty for
// the upstream repo. We have no way to attribute the result
@@ -1055,13 +1062,22 @@ func (h *Handler) handleCheckSuiteEvent(ctx context.Context, body []byte) {
}
updatedAt := parseGHTimeRequired(p.CheckSuite.UpdatedAt)
- // Route to the workspace that owns this repository (see
- // handlePullRequestEvent) so the suite lands on the same PR row the
- // pull_request webhook mirrored, rather than the installation's workspace.
- wsID := h.resolveWorkspaceForRepo(ctx, inst.WorkspaceID, inst.AccountLogin, p.Repository.Owner.Login, p.Repository.Name)
+ // Fan out to every workspace bound to this installation: each records the
+ // suite against its own mirror of the PR (see handlePullRequestEvent /
+ // MUL-4343).
+ for _, inst := range insts {
+ h.recordCheckSuiteForWorkspace(ctx, inst.WorkspaceID, &p, updatedAt)
+ }
+}
- affectedWorkspaces := map[string]struct{}{}
+// recordCheckSuiteForWorkspace records a check_suite webhook against one
+// workspace's mirror of each referenced PR. A reference whose PR hasn't been
+// mirrored in this workspace yet is stashed and replayed when the matching
+// pull_request event upserts the row. Invoked once per workspace bound to the
+// delivering installation.
+func (h *Handler) recordCheckSuiteForWorkspace(ctx context.Context, wsID pgtype.UUID, p *ghCheckSuitePayload, updatedAt pgtype.Timestamptz) {
affectedIssues := map[string]struct{}{}
+ recorded := false
for _, prRef := range p.CheckSuite.PullRequests {
// Scope the lookup to the repo's workspace. The (workspace_id,
// repo_owner, repo_name, pr_number) tuple is the real uniqueness key:
@@ -1113,7 +1129,7 @@ func (h *Handler) handleCheckSuiteEvent(ctx context.Context, body []byte) {
slog.Warn("github: upsert check_suite failed", "err", err, "suite_id", p.CheckSuite.ID)
continue
}
- affectedWorkspaces[uuidToString(pr.WorkspaceID)] = struct{}{}
+ recorded = true
issues, err := h.Queries.ListIssueIDsForPullRequest(ctx, pr.ID)
if err == nil {
for _, id := range issues {
@@ -1122,19 +1138,19 @@ func (h *Handler) handleCheckSuiteEvent(ctx context.Context, body []byte) {
}
}
- // Broadcast on the existing event so the issue page just re-queries
- // the PR list. We don't pass a single pull_request payload here
- // because a suite can touch several and the listener already
- // invalidates by issue.
- for ws := range affectedWorkspaces {
- linked := make([]string, 0, len(affectedIssues))
- for id := range affectedIssues {
- linked = append(linked, id)
- }
- h.publish(protocol.EventPullRequestUpdated, ws, "system", "", map[string]any{
- "linked_issue_ids": linked,
- })
+ if !recorded {
+ return
}
+ // Broadcast on the existing event so the issue page just re-queries the PR
+ // list. We don't pass a single pull_request payload here because a suite can
+ // touch several and the listener already invalidates by issue.
+ linked := make([]string, 0, len(affectedIssues))
+ for id := range affectedIssues {
+ linked = append(linked, id)
+ }
+ h.publish(protocol.EventPullRequestUpdated, uuidToString(wsID), "system", "", map[string]any{
+ "linked_issue_ids": linked,
+ })
}
// replayPendingCheckSuitesForPR drains the stash table for one PR (any
@@ -1251,94 +1267,6 @@ func parseGHTimeRequired(s string) pgtype.Timestamptz {
return t
}
-const githubWebhookHost = "github.com"
-
-// resolveWorkspaceForRepo routes a delivery to the workspace whose repos
-// registry owns github.com/owner/name, so one installation can serve repos in
-// several workspaces; falls back to the caller-supplied workspace when
-// unmatched (callers pass the installation's oldest binding, since an
-// installation may now be bound to several workspaces). The registry is
-// admin-editable, so it overrides the verified installation binding only when
-// owner == the delivering account (accountLogin) and the host matches — no
-// cross-account capture. On ties the fallback workspace wins if it is among the
-// matches, else the lowest id (query is ORDER BY id).
-func (h *Handler) resolveWorkspaceForRepo(ctx context.Context, fallback pgtype.UUID, accountLogin, owner, name string) pgtype.UUID {
- owner = strings.TrimSpace(owner)
- name = strings.TrimSpace(name)
- if owner == "" || name == "" {
- return fallback
- }
- // Only the delivering account's repos may be re-routed by the registry.
- if !strings.EqualFold(strings.TrimSpace(accountLogin), owner) {
- return fallback
- }
- target := githubWebhookHost + "/" + strings.ToLower(owner) + "/" + strings.ToLower(name)
- rows, err := h.Queries.ListWorkspacesWithRepos(ctx)
- if err != nil {
- slog.Warn("github: list workspaces with repos failed", "err", err)
- return fallback
- }
- matches := make([]pgtype.UUID, 0, 1)
- for _, row := range rows {
- var repos []struct {
- URL string `json:"url"`
- }
- if err := json.Unmarshal(row.Repos, &repos); err != nil {
- continue
- }
- for _, rp := range repos {
- if repoIdentityFromURL(rp.URL) == target {
- matches = append(matches, row.ID)
- break
- }
- }
- }
- switch len(matches) {
- case 0:
- return fallback
- case 1:
- return matches[0]
- default:
- for _, m := range matches {
- if m == fallback {
- return m
- }
- }
- return matches[0]
- }
-}
-
-// repoIdentityFromURL returns lowercased "host/owner/name" from an https, scp
-// ssh (git@host:owner/name) or ssh:// git URL, or "" if it can't.
-func repoIdentityFromURL(raw string) string {
- s := strings.ToLower(strings.TrimSpace(raw))
- if s == "" {
- return ""
- }
- // Trim trailing slashes before ".git" so "…/foo.git/" resolves.
- s = strings.TrimRight(s, "/")
- s = strings.TrimSuffix(s, ".git")
- s = strings.TrimRight(s, "/")
- if i := strings.Index(s, "://"); i >= 0 {
- s = s[i+3:]
- }
- if i := strings.Index(s, "@"); i >= 0 {
- s = s[i+1:]
- }
- // Fold scp-like "host:owner/name" into a path so one split handles all forms.
- s = strings.ReplaceAll(s, ":", "/")
- segments := make([]string, 0, 4)
- for _, seg := range strings.Split(s, "/") {
- if seg != "" {
- segments = append(segments, seg)
- }
- }
- if len(segments) < 3 {
- return ""
- }
- return segments[0] + "/" + segments[len(segments)-2] + "/" + segments[len(segments)-1]
-}
-
// extractIdentifiers pulls every "PREFIX-NUMBER" match across the supplied
// fields, deduplicating in input order.
func extractIdentifiers(parts ...string) []string {
diff --git a/server/internal/handler/github_test.go b/server/internal/handler/github_test.go
index 4135a9e0bd..071ce4e7fd 100644
--- a/server/internal/handler/github_test.go
+++ b/server/internal/handler/github_test.go
@@ -2845,251 +2845,294 @@ func TestSetupCallback_ConsumesPendingInstallationCreated(t *testing.T) {
}
}
-func TestRepoIdentityFromURL(t *testing.T) {
- cases := []struct {
- in string
- want string
- }{
- {"https://github.com/octocat/hello-world", "github.com/octocat/hello-world"},
- {"https://github.com/octocat/hello-world.git", "github.com/octocat/hello-world"},
- {"https://github.com/octocat/hello-world/", "github.com/octocat/hello-world"},
- {"https://github.com/octocat/hello-world.git/", "github.com/octocat/hello-world"}, // .git + trailing slash
- {"[email protected]:octocat/hello-world.git", "github.com/octocat/hello-world"},
- {"[email protected]:octocat/hello-world", "github.com/octocat/hello-world"},
- {"ssh://[email protected]/octocat/hello-world.git", "github.com/octocat/hello-world"},
- {"https://github.com/Octocat/Hello-World", "github.com/octocat/hello-world"}, // case-folded
- {" https://github.com/octocat/hello-world ", "github.com/octocat/hello-world"},
- {"[email protected]:octocat/hello-world.git", "gitlab.com/octocat/hello-world"}, // host kept
- {"https://bitbucket.org/octocat/hello-world", "bitbucket.org/octocat/hello-world"},
- {"", ""},
- {"single-segment", ""},
- {"github.com/onlyowner", ""}, // needs host + 2 path segments
- }
- for _, c := range cases {
- if got := repoIdentityFromURL(c.in); got != c.want {
- t.Errorf("repoIdentityFromURL(%q) = %q, want %q", c.in, got, c.want)
- }
- }
-}
-
-// TestWebhook_RoutesToRepoOwningWorkspace is the regression test for the bug
-// where one GitHub App installation serving repos in several workspaces filed
-// every PR under the installation's single workspace — so a PR's identifier
-// was scanned against the wrong prefix and never linked. The fix routes by the
-// repository's owning workspace (workspace.repos registry).
-func TestWebhook_RoutesToRepoOwningWorkspace(t *testing.T) {
- if testHandler == nil {
+// TestWebhook_PullRequest_FansOutToBoundWorkspaces is the MUL-4343 change: one
+// GitHub App installation bound to several workspaces must deliver a repo's PR
+// events to EVERY bound workspace. Each workspace mirrors the PR and auto-links
+// it against its own issues (its own prefix), replacing the old single-workspace
+// routing that dropped the event for every workspace but one.
+func TestWebhook_PullRequest_FansOutToBoundWorkspaces(t *testing.T) {
+ if testHandler == nil || testPool == nil {
t.Skip("handler test fixture not initialized (no DB?)")
}
ctx := context.Background()
- secret := "route-by-repo-secret"
+ secret := "fanout-pr-secret"
t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
- // The issue lives in the repo-OWNING workspace B (the shared test workspace).
+ // Workspace B is the shared test workspace (prefix HAN) and owns the issue.
w := httptest.NewRecorder()
- req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
- "title": "route-by-repo test",
+ testHandler.CreateIssue(w, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "fan-out PR test",
"status": "in_progress",
- })
- testHandler.CreateIssue(w, req)
+ }))
if w.Code != http.StatusCreated {
t.Fatalf("CreateIssue: %d %s", w.Code, w.Body.String())
}
var created IssueResponse
json.NewDecoder(w.Body).Decode(&created)
- const repoOwner, repoName = "route-acme", "route-widget"
- repoURL := "https://github.com/" + repoOwner + "/" + repoName
+ const repo = "fanout-repo"
+ const prNumber int32 = 4343
+ const installationID int64 = 778899101
- // Register the repo in workspace B's registry; remember the prior value.
- var prevRepos []byte
- if err := testPool.QueryRow(ctx, `SELECT repos FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&prevRepos); err != nil {
- t.Fatalf("read repos: %v", err)
- }
- if _, err := testPool.Exec(ctx, `UPDATE workspace SET repos = $1 WHERE id = $2`,
- []byte(`[{"url":"`+repoURL+`","description":"route test"}]`), testWorkspaceID); err != nil {
- t.Fatalf("set repos: %v", err)
- }
-
- // A DIFFERENT workspace A owns the App installation that delivers the
- // webhook; the repo is NOT registered here. Pre-delete any leftover from an
- // aborted run so the slug is free.
- testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, "route-test-install-ws")
+ // Workspace A is bound to the SAME installation but has no matching issue;
+ // it must still receive the PR mirror.
+ testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, "fanout-pr-ws-a")
wsA, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{
- Name: "route-test-install-ws",
- Slug: "route-test-install-ws",
- IssuePrefix: "RTW",
+ Name: "fanout-pr-ws-a", Slug: "fanout-pr-ws-a", IssuePrefix: "FPA",
})
if err != nil {
t.Fatalf("CreateWorkspace: %v", err)
}
- const installationID int64 = 778899001
+ // Bind the installation to BOTH workspaces.
if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
- WorkspaceID: wsA.ID,
- InstallationID: installationID,
- // Account owns the repo (owner == accountLogin); the registry override
- // is only honored for the delivering account.
- AccountLogin: repoOwner,
- AccountType: "User",
+ WorkspaceID: parseUUID(testWorkspaceID), InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
}); err != nil {
- t.Fatalf("CreateGitHubInstallation: %v", err)
+ t.Fatalf("CreateGitHubInstallation B: %v", err)
+ }
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: wsA.ID, InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
+ }); err != nil {
+ t.Fatalf("CreateGitHubInstallation A: %v", err)
}
t.Cleanup(func() {
testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)
- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE repo_owner = $1 AND repo_name = $2`, repoOwner, repoName)
+ testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE repo_owner = 'acme' AND repo_name = $1`, repo)
testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(ctx, `DELETE FROM activity_log WHERE issue_id = $1`, created.ID)
testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)
- testPool.Exec(ctx, `UPDATE workspace SET repos = $1 WHERE id = $2`, prevRepos, testWorkspaceID)
testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wsA.ID)
})
- const prNumber = 4242
- body := map[string]any{
- "action": "opened",
- "pull_request": map[string]any{
- "number": prNumber,
- "html_url": repoURL + "/pull/4242",
- "title": "Implement thing " + created.Identifier,
- "body": "Closes " + created.Identifier,
- "state": "open",
- "draft": false,
- "merged": false,
- "created_at": "2026-04-28T00:00:00Z",
- "updated_at": "2026-04-28T00:00:00Z",
- "head": map[string]any{"ref": "feat/thing"},
- "user": map[string]any{"login": "octocat", "avatar_url": ""},
- },
- "repository": map[string]any{
- "name": repoName,
- "owner": map[string]any{"login": repoOwner},
- },
- "installation": map[string]any{"id": installationID},
- }
- raw, _ := json.Marshal(body)
- mac := hmac.New(sha256.New, []byte(secret))
- mac.Write(raw)
- sig := "sha256=" + hex.EncodeToString(mac.Sum(nil))
-
- rec := httptest.NewRecorder()
- hookReq := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(raw))
- hookReq.Header.Set("X-GitHub-Event", "pull_request")
- hookReq.Header.Set("X-Hub-Signature-256", sig)
- testHandler.HandleGitHubWebhook(rec, hookReq)
- if rec.Code != http.StatusAccepted {
- t.Fatalf("webhook: expected 202, got %d (%s)", rec.Code, rec.Body.String())
- }
+ // One PR whose title references workspace B's issue.
+ firePullRequestWebhook(t, secret, created.Identifier, installationID, repo, prNumber, "open")
- // The PR must be filed under the repo-owning workspace B, not installation
- // workspace A.
+ // The PR must be mirrored in BOTH bound workspaces.
if _, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{
- WorkspaceID: parseUUID(testWorkspaceID),
- RepoOwner: repoOwner,
- RepoName: repoName,
- PrNumber: prNumber,
+ WorkspaceID: parseUUID(testWorkspaceID), RepoOwner: "acme", RepoName: repo, PrNumber: prNumber,
}); err != nil {
- t.Fatalf("expected PR filed under the repo-owning workspace: %v", err)
+ t.Fatalf("expected PR mirrored in workspace B: %v", err)
}
- if _, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{
- WorkspaceID: wsA.ID,
- RepoOwner: repoOwner,
- RepoName: repoName,
- PrNumber: prNumber,
- }); err == nil {
- t.Fatalf("PR should NOT be filed under the installation's workspace")
+ prA, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{
+ WorkspaceID: wsA.ID, RepoOwner: "acme", RepoName: repo, PrNumber: prNumber,
+ })
+ if err != nil {
+ t.Fatalf("expected PR fanned out to workspace A: %v", err)
}
- // And it must be linked to the repo-owning workspace's issue.
+ // Workspace B links its own issue; workspace A (no matching issue) does not.
linked, err := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID))
if err != nil {
t.Fatalf("ListPullRequestsByIssue: %v", err)
}
if len(linked) != 1 {
- t.Fatalf("expected 1 linked PR on the repo-owning workspace issue, got %d", len(linked))
+ t.Fatalf("expected 1 linked PR on workspace B's issue, got %d", len(linked))
+ }
+ if issues, _ := testHandler.Queries.ListIssueIDsForPullRequest(ctx, prA.ID); len(issues) != 0 {
+ t.Fatalf("workspace A has no matching issue, expected 0 links, got %d", len(issues))
}
}
-// TestWebhook_RegistryDoesNotCaptureForeignAccount guards the security gate: a
-// workspace that registers a repo whose owner is NOT the delivering
-// installation's account must not capture that repo's webhooks.
-func TestWebhook_RegistryDoesNotCaptureForeignAccount(t *testing.T) {
- if testHandler == nil {
+// TestWebhook_CheckSuite_FansOutToBoundWorkspaces mirrors the PR fan-out for CI:
+// a check_suite event must be recorded against every bound workspace's copy of
+// the referenced PR, not just one.
+func TestWebhook_CheckSuite_FansOutToBoundWorkspaces(t *testing.T) {
+ if testHandler == nil || testPool == nil {
t.Skip("handler test fixture not initialized (no DB?)")
}
ctx := context.Background()
- secret := "foreign-acct-secret"
+ secret := "fanout-cs-secret"
t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
- const repoOwner, repoName = "victim-org", "victim-repo"
- repoURL := "https://github.com/" + repoOwner + "/" + repoName
+ const repo = "fanout-ci-repo"
+ const prNumber int32 = 4344
+ const installationID int64 = 778899102
+ const suiteID int64 = 90019001
+ head := "fanoutsha123456"
- // Squatter workspace B (the shared test workspace) registers the repo and
- // has an issue, but the delivery is for a DIFFERENT account.
- var prevRepos []byte
- testPool.QueryRow(ctx, `SELECT repos FROM workspace WHERE id = $1`, testWorkspaceID).Scan(&prevRepos)
- if _, err := testPool.Exec(ctx, `UPDATE workspace SET repos = $1 WHERE id = $2`,
- []byte(`[{"url":"`+repoURL+`"}]`), testWorkspaceID); err != nil {
- t.Fatalf("set repos: %v", err)
+ testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, "fanout-ci-ws-a")
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, "fanout-ci-ws-b")
+ wsA, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{
+ Name: "fanout-ci-ws-a", Slug: "fanout-ci-ws-a", IssuePrefix: "FCA",
+ })
+ if err != nil {
+ t.Fatalf("CreateWorkspace A: %v", err)
+ }
+ wsB, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{
+ Name: "fanout-ci-ws-b", Slug: "fanout-ci-ws-b", IssuePrefix: "FCB",
+ })
+ if err != nil {
+ t.Fatalf("CreateWorkspace B: %v", err)
}
- w := httptest.NewRecorder()
- testHandler.CreateIssue(w, newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{"title": "foreign", "status": "todo"}))
- var created IssueResponse
- json.NewDecoder(w.Body).Decode(&created)
- // The installation maps to its OWN workspace (not the squatter), so when the
- // gate refuses the registry it falls back here — a workspace with no
- // matching issue — and the squatter genuinely gets zero links.
- testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, "foreign-acct-install-ws")
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: wsA.ID, InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
+ }); err != nil {
+ t.Fatalf("CreateGitHubInstallation A: %v", err)
+ }
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: wsB.ID, InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
+ }); err != nil {
+ t.Fatalf("CreateGitHubInstallation B: %v", err)
+ }
+
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM github_pull_request_check_suite WHERE pr_id IN (SELECT id FROM github_pull_request WHERE repo_owner = 'acme' AND repo_name = $1)`, repo)
+ testPool.Exec(ctx, `DELETE FROM github_pending_check_suite WHERE repo_owner = 'acme' AND repo_name = $1`, repo)
+ testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE repo_owner = 'acme' AND repo_name = $1`, repo)
+ testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wsA.ID)
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wsB.ID)
+ })
+
+ // Mirror the PR into both workspaces (no issue needed), then fire CI on the
+ // same head SHA.
+ firePullRequestWebhookWithHead(t, secret, "FCX-1", installationID, repo, prNumber, "opened", head, "")
+ fireCheckSuiteWebhook(t, secret, installationID, repo, []int32{prNumber}, suiteID, 7100, head, "failure", "2026-05-01T00:00:00Z")
+
+ // The suite must be recorded against BOTH workspaces' PR rows.
+ assertRecorded := func(label string, prID any) {
+ var n int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM github_pull_request_check_suite WHERE pr_id = $1 AND suite_id = $2`,
+ prID, suiteID).Scan(&n); err != nil {
+ t.Fatalf("workspace %s: count check suites: %v", label, err)
+ }
+ if n != 1 {
+ t.Fatalf("workspace %s: expected 1 recorded check_suite, got %d", label, n)
+ }
+ }
+
+ prA, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{
+ WorkspaceID: wsA.ID, RepoOwner: "acme", RepoName: repo, PrNumber: prNumber,
+ })
+ if err != nil {
+ t.Fatalf("workspace A: expected PR mirrored: %v", err)
+ }
+ prB, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{
+ WorkspaceID: wsB.ID, RepoOwner: "acme", RepoName: repo, PrNumber: prNumber,
+ })
+ if err != nil {
+ t.Fatalf("workspace B: expected PR mirrored: %v", err)
+ }
+ assertRecorded("A", prA.ID)
+ assertRecorded("B", prB.ID)
+}
+
+// TestWebhook_CheckSuite_OutOfOrderFansOutToBoundWorkspaces covers the most
+// error-prone multi-workspace path: a check_suite that arrives BEFORE the PR is
+// mirrored. Each bound workspace must stash its own pending row, and when the PR
+// event fans out, each workspace must drain its own pending row and record the
+// suite — one workspace's stash/drain must not stand in for another's.
+func TestWebhook_CheckSuite_OutOfOrderFansOutToBoundWorkspaces(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("handler test fixture not initialized (no DB?)")
+ }
+ ctx := context.Background()
+ secret := "fanout-cs-ooo-secret"
+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)
+
+ const repo = "fanout-ooo-repo"
+ const prNumber int32 = 4345
+ const installationID int64 = 778899103
+ const suiteID int64 = 90019002
+ head := "ooosha7654321"
+
+ testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, "fanout-ooo-ws-a")
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, "fanout-ooo-ws-b")
wsA, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{
- Name: "foreign-acct-install-ws", Slug: "foreign-acct-install-ws", IssuePrefix: "FAW",
+ Name: "fanout-ooo-ws-a", Slug: "fanout-ooo-ws-a", IssuePrefix: "OOA",
})
if err != nil {
- t.Fatalf("CreateWorkspace: %v", err)
+ t.Fatalf("CreateWorkspace A: %v", err)
}
- const installationID int64 = 778899002
- // Installation account != repo owner — the gate must refuse the registry.
+ wsB, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{
+ Name: "fanout-ooo-ws-b", Slug: "fanout-ooo-ws-b", IssuePrefix: "OOB",
+ })
+ if err != nil {
+ t.Fatalf("CreateWorkspace B: %v", err)
+ }
+
if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
- WorkspaceID: wsA.ID, InstallationID: installationID,
- AccountLogin: "some-other-account", AccountType: "User",
+ WorkspaceID: wsA.ID, InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
}); err != nil {
- t.Fatalf("CreateGitHubInstallation: %v", err)
+ t.Fatalf("CreateGitHubInstallation A: %v", err)
+ }
+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{
+ WorkspaceID: wsB.ID, InstallationID: installationID, AccountLogin: "acme", AccountType: "User",
+ }); err != nil {
+ t.Fatalf("CreateGitHubInstallation B: %v", err)
}
+
t.Cleanup(func() {
- testPool.Exec(ctx, `DELETE FROM issue_pull_request WHERE issue_id = $1`, created.ID)
- testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE repo_owner = $1 AND repo_name = $2`, repoOwner, repoName)
+ testPool.Exec(ctx, `DELETE FROM github_pull_request_check_suite WHERE pr_id IN (SELECT id FROM github_pull_request WHERE repo_owner = 'acme' AND repo_name = $1)`, repo)
+ testPool.Exec(ctx, `DELETE FROM github_pending_check_suite WHERE repo_owner = 'acme' AND repo_name = $1`, repo)
+ testPool.Exec(ctx, `DELETE FROM github_pull_request WHERE repo_owner = 'acme' AND repo_name = $1`, repo)
testPool.Exec(ctx, `DELETE FROM github_installation WHERE installation_id = $1`, installationID)
- testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, created.ID)
- testPool.Exec(ctx, `UPDATE workspace SET repos = $1 WHERE id = $2`, prevRepos, testWorkspaceID)
testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wsA.ID)
+ testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, wsB.ID)
})
- body := map[string]any{
- "action": "opened",
- "pull_request": map[string]any{
- "number": 5, "html_url": repoURL + "/pull/5", "title": "x " + created.Identifier,
- "body": "Closes " + created.Identifier, "state": "open", "draft": false, "merged": false,
- "created_at": "2026-04-28T00:00:00Z", "updated_at": "2026-04-28T00:00:00Z",
- "head": map[string]any{"ref": "x"}, "user": map[string]any{"login": "octocat"},
- },
- "repository": map[string]any{"name": repoName, "owner": map[string]any{"login": repoOwner}},
- "installation": map[string]any{"id": installationID},
+ pendingCount := func(wsID any) int {
+ var n int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM github_pending_check_suite WHERE workspace_id = $1 AND repo_owner = 'acme' AND repo_name = $2 AND pr_number = $3 AND suite_id = $4`,
+ wsID, repo, prNumber, suiteID).Scan(&n); err != nil {
+ t.Fatalf("count pending: %v", err)
+ }
+ return n
}
- raw, _ := json.Marshal(body)
- mac := hmac.New(sha256.New, []byte(secret))
- mac.Write(raw)
- rec := httptest.NewRecorder()
- hookReq := httptest.NewRequest("POST", "/api/webhooks/github", bytes.NewReader(raw))
- hookReq.Header.Set("X-GitHub-Event", "pull_request")
- hookReq.Header.Set("X-Hub-Signature-256", "sha256="+hex.EncodeToString(mac.Sum(nil)))
- testHandler.HandleGitHubWebhook(rec, hookReq)
- if rec.Code != http.StatusAccepted {
- t.Fatalf("webhook: expected 202, got %d (%s)", rec.Code, rec.Body.String())
+ suiteCount := func(prID any) int {
+ var n int
+ if err := testPool.QueryRow(ctx,
+ `SELECT count(*) FROM github_pull_request_check_suite WHERE pr_id = $1 AND suite_id = $2`,
+ prID, suiteID).Scan(&n); err != nil {
+ t.Fatalf("count suites: %v", err)
+ }
+ return n
}
- // The gate refused the registry, so the squatter workspace got nothing.
- if linked, _ := testHandler.Queries.ListPullRequestsByIssue(ctx, parseUUID(created.ID)); len(linked) != 0 {
- t.Fatalf("foreign-account repo must not link to the squatter workspace, got %d links", len(linked))
+ // 1. check_suite arrives BEFORE any PR mirror: each bound workspace stashes
+ // its own pending row.
+ fireCheckSuiteWebhook(t, secret, installationID, repo, []int32{prNumber}, suiteID, 7200, head, "failure", "2026-05-02T00:00:00Z")
+ if got := pendingCount(wsA.ID); got != 1 {
+ t.Fatalf("workspace A: expected 1 pending check_suite, got %d", got)
+ }
+ if got := pendingCount(wsB.ID); got != 1 {
+ t.Fatalf("workspace B: expected 1 pending check_suite, got %d", got)
+ }
+
+ // 2. The PR arrives and fans out: each workspace drains its own pending row
+ // and records the suite against its own PR mirror.
+ firePullRequestWebhookWithHead(t, secret, "OOX-1", installationID, repo, prNumber, "opened", head, "")
+
+ prA, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{
+ WorkspaceID: wsA.ID, RepoOwner: "acme", RepoName: repo, PrNumber: prNumber,
+ })
+ if err != nil {
+ t.Fatalf("workspace A: expected PR mirrored: %v", err)
+ }
+ prB, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{
+ WorkspaceID: wsB.ID, RepoOwner: "acme", RepoName: repo, PrNumber: prNumber,
+ })
+ if err != nil {
+ t.Fatalf("workspace B: expected PR mirrored: %v", err)
+ }
+ if got := suiteCount(prA.ID); got != 1 {
+ t.Fatalf("workspace A: expected 1 recorded check_suite after drain, got %d", got)
+ }
+ if got := suiteCount(prB.ID); got != 1 {
+ t.Fatalf("workspace B: expected 1 recorded check_suite after drain, got %d", got)
+ }
+ if got := pendingCount(wsA.ID); got != 0 {
+ t.Fatalf("workspace A: expected pending drained to 0, got %d", got)
+ }
+ if got := pendingCount(wsB.ID); got != 0 {
+ t.Fatalf("workspace B: expected pending drained to 0, got %d", got)
}
}
diff --git a/server/pkg/db/generated/github.sql.go b/server/pkg/db/generated/github.sql.go
index d6a9aa19d2..e68786b4d8 100644
--- a/server/pkg/db/generated/github.sql.go
+++ b/server/pkg/db/generated/github.sql.go
@@ -386,8 +386,8 @@ ORDER BY created_at ASC, id ASC
`
// One installation_id can be bound to several workspaces; webhook routing lists
-// every binding and picks the target workspace via the repos registry. Ordered
-// so the oldest binding is the deterministic routing fallback (insts[0]).
+// every binding and fans the event out to each bound workspace. Ordered oldest
+// first so processing is deterministic and replay-stable.
func (q *Queries) ListGitHubInstallationsByInstallationID(ctx context.Context, installationID int64) ([]GithubInstallation, error) {
rows, err := q.db.Query(ctx, listGitHubInstallationsByInstallationID, installationID)
if err != nil {
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index b82dcb61b5..63cd26f60f 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -208,39 +208,6 @@ func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Wor
return items, nil
}
-const listWorkspacesWithRepos = `-- name: ListWorkspacesWithRepos :many
-SELECT id, repos FROM workspace
-WHERE repos IS NOT NULL AND repos <> '[]'::jsonb
-ORDER BY id
-`
-
-type ListWorkspacesWithReposRow struct {
- ID pgtype.UUID `json:"id"`
- Repos []byte `json:"repos"`
-}
-
-// Workspaces with a non-empty repo registry, to route a webhook to the repo's
-// owning workspace. ORDER BY id keeps the resolver's tie-break stable on replay.
-func (q *Queries) ListWorkspacesWithRepos(ctx context.Context) ([]ListWorkspacesWithReposRow, error) {
- rows, err := q.db.Query(ctx, listWorkspacesWithRepos)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []ListWorkspacesWithReposRow{}
- for rows.Next() {
- var i ListWorkspacesWithReposRow
- if err := rows.Scan(&i.ID, &i.Repos); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
const updateWorkspace = `-- name: UpdateWorkspace :one
UPDATE workspace SET
name = COALESCE($2, name),
diff --git a/server/pkg/db/queries/github.sql b/server/pkg/db/queries/github.sql
index d250e37184..0b3fda2a41 100644
--- a/server/pkg/db/queries/github.sql
+++ b/server/pkg/db/queries/github.sql
@@ -9,8 +9,8 @@ ORDER BY created_at ASC;
-- name: ListGitHubInstallationsByInstallationID :many
-- One installation_id can be bound to several workspaces; webhook routing lists
--- every binding and picks the target workspace via the repos registry. Ordered
--- so the oldest binding is the deterministic routing fallback (insts[0]).
+-- every binding and fans the event out to each bound workspace. Ordered oldest
+-- first so processing is deterministic and replay-stable.
SELECT * FROM github_installation
WHERE installation_id = $1
ORDER BY created_at ASC, id ASC;
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index a1d15cc7f5..c1eff1d711 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -33,13 +33,6 @@ UPDATE workspace SET
WHERE id = $1
RETURNING *;
--- name: ListWorkspacesWithRepos :many
--- Workspaces with a non-empty repo registry, to route a webhook to the repo's
--- owning workspace. ORDER BY id keeps the resolver's tie-break stable on replay.
-SELECT id, repos FROM workspace
-WHERE repos IS NOT NULL AND repos <> '[]'::jsonb
-ORDER BY id;
-
-- name: IncrementIssueCounter :one
UPDATE workspace SET issue_counter = issue_counter + 1
WHERE id = $1