Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-3523: fix(github): route PR/check_suite webhooks by repo
Ivan Fokeevca43c83abc10
diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex cc24676983..c956293b9a 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -819,10 +819,14 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {return}+ // 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)+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: inst.WorkspaceID,+ WorkspaceID: wsID,InstallationID: inst.InstallationID,RepoOwner: p.Repository.Owner.Login,RepoName: p.Repository.Name,@@ -854,9 +858,9 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {// replayed through the same upsert path used by live check_suite// events; the DrainPending… query removes them atomically so a// concurrent PR upsert can't double-apply.- h.replayPendingCheckSuitesForPR(ctx, pr, inst.WorkspaceID)+ h.replayPendingCheckSuitesForPR(ctx, pr, wsID)- workspaceID := uuidToString(inst.WorkspaceID)+ workspaceID := uuidToString(wsID)resp := githubPullRequestToResponse(pr)// Auto-link: scan title/body/branch for issue identifiers, look them@@ -870,7 +874,7 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {// flag (which itself short-circuits when the master `github_enabled`// switch is off).linkedIssueIDs := make([]string, 0)- if h.workspaceAutoLinkPRsEnabled(ctx, inst.WorkspaceID) {+ if h.workspaceAutoLinkPRsEnabled(ctx, wsID) {idents := extractIdentifiers(p.PullRequest.Title, p.PullRequest.Body, p.PullRequest.Head.Ref)// closingIdents is the subset of identifiers that this PR explicitly// declared via a closing keyword ("Closes/Fixes/Resolves MUL-X").@@ -888,7 +892,7 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {// a terminal event, later edit/synchronize webhooks must not rewrite// the merge-time close decision.preserveCloseIntent := p.Action != "closed" && (state == "merged" || state == "closed")- prefix := h.getIssuePrefix(ctx, inst.WorkspaceID)+ prefix := h.getIssuePrefix(ctx, wsID)// reevalIssues collects each issue whose link row we just touched so// we can re-run the auto-advance gate against the persisted aggregate// after every link upsert in this event. Driving the gate off@@ -900,7 +904,7 @@ func (h *Handler) handlePullRequestEvent(ctx context.Context, body []byte) {// MUL-1 still advances.reevalIssues := make([]db.Issue, 0, len(idents))for _, id := range idents {- issue, ok := h.lookupIssueByIdentifier(ctx, inst.WorkspaceID, prefix, id)+ issue, ok := h.lookupIssueByIdentifier(ctx, wsID, prefix, id)if !ok {continue}@@ -1025,18 +1029,21 @@ 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)+affectedWorkspaces := map[string]struct{}{}affectedIssues := map[string]struct{}{}for _, prRef := range p.CheckSuite.PullRequests {- // Scope the lookup to the installation's workspace. The- // (workspace_id, repo_owner, repo_name, pr_number) tuple is the- // real uniqueness key: if the same repo lived under a different- // workspace historically, a bare (owner, repo, number) lookup- // could return either row arbitrarily and land this suite on- // the wrong PR (or skip the right one because the installation- // ids no longer match).+ // Scope the lookup to the repo's workspace. The (workspace_id,+ // repo_owner, repo_name, pr_number) tuple is the real uniqueness key:+ // a bare (owner, repo, number) lookup could return a row from a+ // different workspace that also tracks this repo and land the suite+ // on the wrong PR.pr, err := h.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{- WorkspaceID: inst.WorkspaceID,+ WorkspaceID: wsID,RepoOwner: p.Repository.Owner.Login,RepoName: p.Repository.Name,PrNumber: prRef.Number,@@ -1051,7 +1058,7 @@ func (h *Handler) handleCheckSuiteEvent(ctx context.Context, body []byte) {// event keyed by (workspace, repo, pr_number, suite_id); the// PR upsert path will drain and replay it.if err := h.Queries.UpsertPendingCheckSuite(ctx, db.UpsertPendingCheckSuiteParams{- WorkspaceID: inst.WorkspaceID,+ WorkspaceID: wsID,InstallationID: p.Installation.ID,RepoOwner: p.Repository.Owner.Login,RepoName: p.Repository.Name,@@ -1218,6 +1225,92 @@ 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 installation workspace when unmatched.+// 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 installation's own workspace+// wins, 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.goindex 09288421d2..8173a2431b 100644--- a/server/internal/handler/github_test.go+++ b/server/internal/handler/github_test.go@@ -2658,3 +2658,251 @@ func TestSetupCallback_ConsumesPendingInstallationCreated(t *testing.T) {t.Fatalf("pending installation row should be consumed, got count %d", pendingCount)}}++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 {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ ctx := context.Background()+ secret := "route-by-repo-secret"+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)++ // The issue lives in the repo-OWNING workspace B (the shared test workspace).+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{+ "title": "route-by-repo 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++ // 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")+ wsA, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{+ Name: "route-test-install-ws",+ Slug: "route-test-install-ws",+ IssuePrefix: "RTW",+ })+ if err != nil {+ t.Fatalf("CreateWorkspace: %v", err)+ }++ const installationID int64 = 778899001+ 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",+ }); err != nil {+ t.Fatalf("CreateGitHubInstallation: %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_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)+ })++ 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())+ }++ // The PR must be filed under the repo-owning workspace B, not installation+ // workspace A.+ if _, err := testHandler.Queries.GetGitHubPullRequest(ctx, db.GetGitHubPullRequestParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ RepoOwner: repoOwner,+ RepoName: repoName,+ PrNumber: prNumber,+ }); err != nil {+ t.Fatalf("expected PR filed under the repo-owning workspace: %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")+ }++ // And it must be linked to the repo-owning workspace's issue.+ 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))+ }+}++// 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 {+ t.Skip("handler test fixture not initialized (no DB?)")+ }+ ctx := context.Background()+ secret := "foreign-acct-secret"+ t.Setenv("GITHUB_WEBHOOK_SECRET", secret)++ const repoOwner, repoName = "victim-org", "victim-repo"+ repoURL := "https://github.com/" + repoOwner + "/" + repoName++ // 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)+ }+ 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")+ wsA, err := testHandler.Queries.CreateWorkspace(ctx, db.CreateWorkspaceParams{+ Name: "foreign-acct-install-ws", Slug: "foreign-acct-install-ws", IssuePrefix: "FAW",+ })+ if err != nil {+ t.Fatalf("CreateWorkspace: %v", err)+ }+ const installationID int64 = 778899002+ // Installation account != repo owner — the gate must refuse the registry.+ if _, err := testHandler.Queries.CreateGitHubInstallation(ctx, db.CreateGitHubInstallationParams{+ WorkspaceID: wsA.ID, InstallationID: installationID,+ AccountLogin: "some-other-account", AccountType: "User",+ }); err != nil {+ t.Fatalf("CreateGitHubInstallation: %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_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)+ })++ 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},+ }+ 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())+ }++ // 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))+ }+}diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.goindex 771e79b7a3..92f52d7ebe 100644--- a/server/pkg/db/generated/workspace.sql.go+++ b/server/pkg/db/generated/workspace.sql.go@@ -169,6 +169,45 @@ func (q *Queries) ListWorkspaces(ctx context.Context, userID pgtype.UUID) ([]Worreturn 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 that have at least one repository in their registry, returning+// only the id and the repos JSONB. Used to route an inbound GitHub webhook to+// the workspace that actually owns the event's repository (instead of the+// single workspace the delivering App installation happens to be mapped to —+// one GitHub account/installation can serve repos belonging to several+// workspaces).+// ORDER BY id so the multi-match tie-break in resolveWorkspaceForRepo is+// stable across webhook replays.+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 :oneUPDATE workspace SETname = COALESCE($2, name),diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sqlindex 92e43d7579..3f9daa0dd5 100644--- a/server/pkg/db/queries/workspace.sql+++ b/server/pkg/db/queries/workspace.sql@@ -33,6 +33,13 @@ UPDATE workspace SETWHERE id = $1RETURNING *;+-- 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 :oneUPDATE workspace SET issue_counter = issue_counter + 1WHERE id = $1