Skip to content

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

Go

MUL-9102: Support GitLab system hook merge request events (#10411)

xiaojiahuib70c8b96d0c6
diff --git a/apps/docs/content/docs/vcs-integration.mdx b/apps/docs/content/docs/vcs-integration.mdx
index d5a9b630e5..db0a4d5649 100644
--- a/apps/docs/content/docs/vcs-integration.mdx
+++ b/apps/docs/content/docs/vcs-integration.mdx
@@ -99,8 +99,11 @@ Settings → Webhooks:
</Tab>
</Tabs>
+GitLab also supports an instance-wide **System Hook** under the administrator area. Use the same URL and secret token, and enable **Merge request events**. Multica accepts its MR events only for repositories listed under this workspace's **Settings → Code → Repositories**, on the connected GitLab instance, and readable by the connected access token; unrelated or unauthorized system events are ignored. Repository entries may use HTTPS or SSH clone URLs. This avoids creating a hook in every project, but the GitLab administrator must configure the system hook. System Hooks deliver MR events only, not Pipeline events; retain repository or group Pipeline webhooks if you need CI status. Project/group hooks and a System Hook may coexist. A webhook delivery returning `202` means it was acknowledged, not that an issue was linked or moved. Existing merged MRs are not retroactively replayed when you connect the hook.
+
Multica authenticates every delivery against the stored secret, so a webhook without the matching secret is rejected.
+
## What gets mirrored
- **Pull / merge requests**: open, closed, merged, and draft state, author, branch, and (where the provider supplies them) diff stats.
diff --git a/apps/docs/content/docs/vcs-integration.zh.mdx b/apps/docs/content/docs/vcs-integration.zh.mdx
index 7e05f02635..9deeba99fe 100644
--- a/apps/docs/content/docs/vcs-integration.zh.mdx
+++ b/apps/docs/content/docs/vcs-integration.zh.mdx
@@ -99,6 +99,10 @@ Multica 不提供跳过证书校验的选项,因为连接请求会携带你的
</Tab>
</Tabs>
+<Callout type="info">
+GitLab 管理员也可以配置实例级 **System Hook**:使用同一 Webhook 地址与密钥,启用 **Merge request events**。Multica 只处理当前工作区 **设置 → 代码 → 代码仓库** 中列出的、属于已连接 GitLab 实例且可被连接令牌读取的仓库;其他系统事件会被忽略。代码仓库可以使用 HTTPS 或 SSH 克隆地址。System Hook 只发送 MR 事件,不发送 Pipeline 事件;如果需要 CI 状态,仍需保留项目级或群组级 Pipeline Webhook,二者可以同时配置。这样不必逐项目注册,但需要 GitLab 管理员权限。返回 `202` 仅代表请求已被接收,不保证任务已关联或改状态;接入前已合并的 MR 不会自动补处理。
+</Callout>
+
Multica 会用存储的密钥校验每次投递,因此没有匹配密钥的 Webhook 会被拒绝。
## 镜像的内容
diff --git a/server/internal/handler/vcs_webhook.go b/server/internal/handler/vcs_webhook.go
index 1855e70a1f..3124feef4a 100644
--- a/server/internal/handler/vcs_webhook.go
+++ b/server/internal/handler/vcs_webhook.go
@@ -2,10 +2,13 @@ package handler
import (
"context"
+ "encoding/json"
"errors"
"io"
"log/slog"
"net/http"
+ "net/url"
+ "strings"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
@@ -136,11 +139,40 @@ func (h *Handler) HandleVCSWebhook(w http.ResponseWriter, r *http.Request) {
return
}
- switch provider.EventKind(r.Header) {
+ systemHook := conn.Provider == string(vcs.KindGitLab) && r.Header.Get("X-Gitlab-Event") == "System Hook"
+ switch provider.EventKind(r.Header, body) {
case vcs.EventPullRequest:
if pr, err := provider.ParsePullRequest(body); err != nil {
slog.Warn("vcs: bad pull_request payload", "provider", conn.Provider, "err", err)
} else {
+ if systemHook {
+ ws, err := h.Queries.GetWorkspace(r.Context(), conn.WorkspaceID)
+ if err != nil {
+ slog.Warn("vcs: load workspace for system hook failed", "err", err)
+ writeError(w, http.StatusServiceUnavailable, "workspace lookup failed")
+ return
+ }
+ if !gitLabSystemHookRepoAllowed(ws.Repos, conn.InstanceUrl, pr.RepoOwner, pr.RepoName) {
+ break
+ }
+ if checker, ok := provider.(vcs.RepositoryAccessChecker); ok {
+ token, err := h.openVCSSecret(conn.AccessTokenEncrypted)
+ if err != nil || token == "" {
+ slog.Warn("vcs: open access token for system hook failed", "err", err)
+ writeError(w, http.StatusInternalServerError, "access token error")
+ return
+ }
+ readable, err := checker.RepositoryReadable(r.Context(), conn.InstanceUrl, pr.RepoOwner, pr.RepoName, token)
+ if err != nil {
+ slog.Warn("vcs: system-hook repository access lookup failed", "provider", conn.Provider, "err", err)
+ writeError(w, http.StatusServiceUnavailable, "repository access lookup failed")
+ return
+ }
+ if !readable {
+ break
+ }
+ }
+ }
h.mirrorVCSPullRequest(r.Context(), conn, pr)
}
case vcs.EventCIStatus:
@@ -155,6 +187,60 @@ func (h *Handler) HandleVCSWebhook(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
}
+// A system hook covers the entire GitLab instance. Only repositories explicitly
+// configured in this workspace may affect its issues; a similarly named repo
+// on another host or under another namespace must not match.
+func gitLabSystemHookRepoAllowed(raw []byte, instanceURL, owner, name string) bool {
+ var repos []workspaceRepoRef
+ if json.Unmarshal(raw, &repos) != nil || owner == "" || name == "" {
+ return false
+ }
+ instance, err := url.Parse(instanceURL)
+ if err != nil || instance.Host == "" {
+ return false
+ }
+ want := strings.Trim(instance.Path, "/")
+ if want != "" {
+ want += "/"
+ }
+ want += owner + "/" + name
+ for _, repo := range repos {
+ u, err := parseGitLabRepoURL(strings.TrimSpace(repo.URL))
+ if err != nil || !gitLabRepoURLMatchesInstance(u, instance) {
+ continue
+ }
+ path := strings.TrimSuffix(strings.Trim(u.Path, "/"), ".git")
+ if path == want {
+ return true
+ }
+ }
+ return false
+}
+
+func parseGitLabRepoURL(raw string) (*url.URL, error) {
+ if strings.Contains(raw, "://") {
+ return url.Parse(raw)
+ }
+ at := strings.Index(raw, "@")
+ colon := strings.Index(raw, ":")
+ if at <= 0 || colon <= at+1 || colon == len(raw)-1 {
+ return nil, errors.New("invalid scp-style repository URL")
+ }
+ return &url.URL{Scheme: "ssh", Host: raw[at+1 : colon], Path: "/" + raw[colon+1:], User: url.User(raw[:at])}, nil
+}
+func gitLabRepoURLMatchesInstance(repo, instance *url.URL) bool {
+ if repo.RawQuery != "" || repo.Fragment != "" {
+ return false
+ }
+ if repo.Scheme == "ssh" {
+ return strings.EqualFold(repo.Hostname(), instance.Hostname()) && repo.User != nil && repo.User.Username() == "git"
+ }
+ if repo.Scheme == "https" || repo.Scheme == "http" {
+ return repo.Scheme == instance.Scheme && strings.EqualFold(repo.Host, instance.Host) && repo.User == nil
+ }
+ return false
+}
+
func (h *Handler) mirrorVCSPullRequest(ctx context.Context, conn db.VcsConnection, ev vcs.PullRequestEvent) {
if ev.RepoOwner == "" || ev.RepoName == "" || ev.Number == 0 {
slog.Warn("vcs: pull_request missing repo identity", "provider", conn.Provider)
diff --git a/server/internal/handler/vcs_webhook_test.go b/server/internal/handler/vcs_webhook_test.go
index 81cbebffe0..e191abe5de 100644
--- a/server/internal/handler/vcs_webhook_test.go
+++ b/server/internal/handler/vcs_webhook_test.go
@@ -10,13 +10,18 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
+ "os"
+ "sync/atomic"
"testing"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/testutil"
"github.com/multica-ai/multica/server/internal/util/secretbox"
db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
func withVCSBox(t *testing.T) *secretbox.Box {
@@ -442,6 +447,251 @@ func TestVCSWebhook_StaleEventDoesNotRewriteLink(t *testing.T) {
}
}
+func TestGitLabSystemHookRepoAllowed(t *testing.T) {
+ repos := []byte(`[{"url":"https://gitlab.test/acme/widget.git"},{"url":"[email protected]:group/sub/widget.git"},{"url":"ssh://[email protected]/group/sub/other.git"},{"url":"ssh://[email protected]:2222/group/sub/ported.git"}]`)
+ for _, tc := range []struct {
+ instance, owner, name string
+ want bool
+ }{
+ {"https://gitlab.test", "acme", "widget", true},
+ {"https://gitlab.test", "other", "widget", false},
+ {"https://other.test", "acme", "widget", false},
+ {"https://gitlab.test", "acme", "widget-extra", false},
+ {"https://gitlab.test", "group/sub", "widget", true},
+ {"https://gitlab.test", "group/sub", "other", true},
+ {"https://gitlab.test", "group/sub", "ported", true},
+ {"https://gitlab.test:8443", "group/sub", "ported", true},
+ {"https://other.test", "group/sub", "ported", false},
+ {"https://gitlab.test:8443", "acme", "widget", false},
+ } {
+ if got := gitLabSystemHookRepoAllowed(repos, tc.instance, tc.owner, tc.name); got != tc.want {
+ t.Errorf("repo %s/%s on %s: got %v, want %v", tc.owner, tc.name, tc.instance, got, tc.want)
+ }
+ }
+ if gitLabSystemHookRepoAllowed(nil, "https://gitlab.test", "acme", "widget") {
+ t.Error("workspace without configured repos must reject system hook")
+ }
+}
+
+func gitlabSystemHookPayload(t *testing.T, title, repo string) []byte {
+ t.Helper()
+ // Preserve the public GitLab 19.5.3-ee sample's nulls, timestamps and state fields.
+ raw, err := os.ReadFile("../integrations/vcs/testdata/gitlab-system-hook-merge.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var payload map[string]any
+ if err := json.Unmarshal(raw, &payload); err != nil {
+ t.Fatal(err)
+ }
+ payload["project"].(map[string]any)["path_with_namespace"] = repo
+ attrs := payload["object_attributes"].(map[string]any)
+ attrs["title"] = title
+ attrs["url"] = "https://gitlab.test/" + repo + "/-/merge_requests/10"
+ raw, err = json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
+
+func configureGitlabSystemHook(t *testing.T, instance, mergeStatus string) {
+ t.Helper()
+ ws, err := testHandler.Queries.GetWorkspace(context.Background(), parseUUID(testWorkspaceID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ dbfx.Exec(t, `UPDATE workspace SET repos = $1, settings = $2 WHERE id = $3`, ws.Repos, ws.Settings, testWorkspaceID)
+ })
+ repos, err := json.Marshal([]map[string]string{{"url": instance + "/acme/widget.git"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ dbfx.Exec(t, `UPDATE workspace SET repos = $1, settings = jsonb_set(settings, '{pr_merge_status}', to_jsonb($2::text)) WHERE id = $3`, repos, mergeStatus, testWorkspaceID)
+}
+
+func TestVCSWebhook_SystemHookAuthorizationFailure(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ status, want int
+ badToken bool
+ }{
+ {"unauthorized", http.StatusUnauthorized, http.StatusAccepted, false},
+ {"forbidden", http.StatusForbidden, http.StatusAccepted, false},
+ {"not_found", http.StatusNotFound, http.StatusAccepted, false},
+ {"gitlab_unavailable", http.StatusInternalServerError, http.StatusServiceUnavailable, false},
+ {"gitlab_timeout", 0, http.StatusServiceUnavailable, false},
+ {"invalid_access_token", http.StatusOK, http.StatusInternalServerError, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := context.Background()
+ box := withVCSBox(t)
+ var lookups atomic.Int32
+ gitlab := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ lookups.Add(1)
+ if r.URL.EscapedPath() != "/api/v4/projects/acme%2Fwidget" || r.Header.Get("PRIVATE-TOKEN") != "tok" {
+ t.Error("project lookup must use the connection token and exact repository")
+ }
+ if tc.status == 0 {
+ <-r.Context().Done()
+ return
+ }
+ w.WriteHeader(tc.status)
+ }))
+ defer gitlab.Close()
+ connID := seedVCSConnection(t, ctx, box, "gitlab", gitlab.URL)
+ issueID := dbfx.Issue(t, "Denied system hook", testutil.Cols{"status": "in_progress"})
+ t.Cleanup(func() { cleanupVCS(ctx, "") })
+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ configureGitlabSystemHook(t, gitlab.URL, "done")
+ if tc.badToken {
+ dbfx.Exec(t, `UPDATE vcs_connection SET access_token_encrypted = 'invalid-ciphertext' WHERE id = $1`, connID)
+ }
+ h := *testHandler
+ h.Bus = events.New()
+ broadcasts := 0
+ h.Bus.SubscribeAll(func(events.Event) { broadcasts++ })
+ identifier := issueToResponse(issue, h.getIssuePrefix(ctx, issue.WorkspaceID)).Identifier
+ raw := gitlabSystemHookPayload(t, "Fix "+identifier, "acme/widget")
+ started := time.Now()
+ testutil.Call(t, h.HandleVCSWebhook, vcsWebhookReq(connID, map[string]string{
+ "X-Gitlab-Event": "System Hook", "X-Gitlab-Token": vcsTestSecret,
+ }, raw)).Want(tc.want)
+ if tc.status == 0 && time.Since(started) > 7*time.Second {
+ t.Fatalf("authorization lookup exceeded its five-second budget: %s", time.Since(started))
+ }
+ if !tc.badToken && lookups.Load() != 1 {
+ t.Fatalf("project lookups = %d, want 1", lookups.Load())
+ }
+ if tc.badToken && lookups.Load() != 0 {
+ t.Fatalf("lookup with invalid token: %d", lookups.Load())
+ }
+ var stored, linked int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM vcs_pull_request WHERE connection_id = $1`, connID).Scan(&stored); err != nil {
+ t.Fatal(err)
+ }
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue_vcs_pull_request WHERE issue_id = $1`, issueID).Scan(&linked); err != nil {
+ t.Fatal(err)
+ }
+ updated, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if stored != 0 || linked != 0 || updated.Status != "in_progress" || broadcasts != 0 {
+ t.Fatalf("unauthorized side effects: stored=%d linked=%d status=%s broadcasts=%d", stored, linked, updated.Status, broadcasts)
+ }
+ })
+ }
+}
+
+func TestVCSWebhook_ProjectAndSystemHookDuplicateDelivery(t *testing.T) {
+ for _, order := range [][]string{{"Merge Request Hook", "System Hook"}, {"System Hook", "Merge Request Hook"}} {
+ for _, target := range []string{"done", "none"} {
+ t.Run(order[0]+"/"+target, func(t *testing.T) {
+ ctx := context.Background()
+ box := withVCSBox(t)
+ gitlab := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`{"path_with_namespace":"acme/widget"}`))
+ }))
+ defer gitlab.Close()
+ connID := seedVCSConnection(t, ctx, box, "gitlab", gitlab.URL)
+ issueID := dbfx.Issue(t, "Duplicate hook delivery", testutil.Cols{"status": "in_progress"})
+ t.Cleanup(func() { cleanupVCS(ctx, "") })
+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ configureGitlabSystemHook(t, gitlab.URL, target)
+ h := *testHandler
+ h.Bus = events.New()
+ transitions := 0
+ h.Bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) {
+ if payload, ok := e.Payload.(map[string]any); ok && payload["status_changed"] == true {
+ transitions++
+ }
+ })
+ identifier := issueToResponse(issue, h.getIssuePrefix(ctx, issue.WorkspaceID)).Identifier
+ raw := gitlabSystemHookPayload(t, "Fix "+identifier, "acme/widget")
+ for _, event := range order {
+ testutil.Call(t, h.HandleVCSWebhook, vcsWebhookReq(connID, map[string]string{
+ "X-Gitlab-Event": event, "X-Gitlab-Token": vcsTestSecret,
+ }, raw)).Want(http.StatusAccepted)
+ }
+ rows, err := h.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var stored, linked int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM vcs_pull_request WHERE connection_id = $1`, connID).Scan(&stored); err != nil {
+ t.Fatal(err)
+ }
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM issue_vcs_pull_request WHERE issue_id = $1`, issueID).Scan(&linked); err != nil {
+ t.Fatal(err)
+ }
+ updated, err := h.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantStatus, wantTransitions := "done", 1
+ if target == "none" {
+ wantStatus, wantTransitions = "in_progress", 0
+ }
+ if len(rows) != 1 || stored != 1 || linked != 1 || updated.Status != wantStatus || transitions != wantTransitions {
+ t.Fatalf("rows=%+v stored=%d linked=%d status=%s transitions=%d; want one MR/link, status=%s transitions=%d", rows, stored, linked, updated.Status, transitions, wantStatus, wantTransitions)
+ }
+ })
+ }
+ }
+}
+
+func TestVCSWebhook_SystemHookOnlyMirrorsConfiguredRepos(t *testing.T) {
+ ctx := context.Background()
+ box := withVCSBox(t)
+ gitlab := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.EscapedPath() != "/api/v4/projects/acme%2Fwidget" || r.Header.Get("PRIVATE-TOKEN") != "tok" {
+ w.WriteHeader(http.StatusForbidden)
+ return
+ }
+ _, _ = w.Write([]byte(`{"path_with_namespace":"acme/widget"}`))
+ }))
+ defer gitlab.Close()
+ connID := seedVCSConnection(t, ctx, box, "gitlab", gitlab.URL)
+ issue := newVCSIssue(t, "System hook test")
+ t.Cleanup(func() { cleanupVCS(ctx, issue.ID) })
+ _, err := testPool.Exec(ctx, `UPDATE workspace SET repos = $1 WHERE id = $2`,
+ `[{"url":"`+gitlab.URL+`/acme/widget.git"}]`, testWorkspaceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `UPDATE workspace SET repos = '[]' WHERE id = $1`, testWorkspaceID)
+ })
+ for _, repo := range []string{"other/widget", "acme/widget"} {
+ raw := gitlabSystemHookPayload(t, issue.Identifier+" fix", repo)
+ w := httptest.NewRecorder()
+ testHandler.HandleVCSWebhook(w, vcsWebhookReq(connID, map[string]string{
+ "X-Gitlab-Event": "System Hook", "X-Gitlab-Token": vcsTestSecret,
+ }, raw))
+ if w.Code != http.StatusAccepted {
+ t.Fatalf("%s: status %d", repo, w.Code)
+ }
+ rows, err := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issue.ID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if repo == "other/widget" && len(rows) != 0 {
+ t.Fatalf("unconfigured repo linked: %+v", rows)
+ }
+ if repo == "acme/widget" && (len(rows) != 1 || rows[0].State != "merged") {
+ t.Fatalf("configured repo not linked: %+v", rows)
+ }
+ }
+}
+
func TestVCSWebhook_GitlabMergeRequest(t *testing.T) {
ctx := context.Background()
box := withVCSBox(t)
@@ -485,6 +735,41 @@ func TestVCSWebhook_GitlabMergeRequest(t *testing.T) {
}
}
+func TestVCSWebhook_GitlabPipelineWithSystemHook(t *testing.T) {
+ ctx := context.Background()
+ box := withVCSBox(t)
+ connID := seedVCSConnection(t, ctx, box, "gitlab", "https://gitlab.test")
+ issueID := dbfx.Issue(t, "GitLab pipeline coexistence")
+ t.Cleanup(func() { cleanupVCS(ctx, "") })
+ issue, err := testHandler.Queries.GetIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ identifier := issueToResponse(issue, testHandler.getIssuePrefix(ctx, issue.WorkspaceID)).Identifier
+ raw := gitlabSystemHookPayload(t, "Fix "+identifier, "acme/widget")
+ testutil.Call(t, testHandler.HandleVCSWebhook, vcsWebhookReq(connID, map[string]string{
+ "X-Gitlab-Event": "Merge Request Hook", "X-Gitlab-Token": vcsTestSecret,
+ }, raw)).Want(http.StatusAccepted)
+
+ pipeline := []byte(`{"object_kind":"pipeline","object_attributes":{"sha":"2222222222222222222222222222222222222222","status":"success","finished_at":"2026-11-01T09:16:00Z"}}`)
+ for _, event := range []string{"System Hook", "Pipeline Hook"} {
+ testutil.Call(t, testHandler.HandleVCSWebhook, vcsWebhookReq(connID, map[string]string{
+ "X-Gitlab-Event": event, "X-Gitlab-Token": vcsTestSecret,
+ }, pipeline)).Want(http.StatusAccepted)
+ rows, err := testHandler.Queries.ListVCSPullRequestsByIssue(ctx, parseUUID(issueID))
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantChecks := int64(0)
+ if event == "Pipeline Hook" {
+ wantChecks = 1
+ }
+ if len(rows) != 1 || rows[0].ChecksTotal != wantChecks || rows[0].ChecksPassed != wantChecks {
+ t.Fatalf("%s: want %d passed checks, got %+v", event, wantChecks, rows)
+ }
+ }
+}
+
func TestVCSWebhook_CommitStatusMirrors(t *testing.T) {
ctx := context.Background()
box := withVCSBox(t)
diff --git a/server/internal/integrations/vcs/forgejo.go b/server/internal/integrations/vcs/forgejo.go
index 6b6906ca78..3dad16f166 100644
--- a/server/internal/integrations/vcs/forgejo.go
+++ b/server/internal/integrations/vcs/forgejo.go
@@ -29,7 +29,7 @@ func init() {
func (p forgejoProvider) Kind() Kind { return p.kind }
-func (p forgejoProvider) EventKind(h http.Header) EventKind {
+func (p forgejoProvider) EventKind(h http.Header, _ []byte) EventKind {
event := h.Get("X-Gitea-Event")
if event == "" {
event = h.Get("X-GitHub-Event") // Gitea mirrors this header too
diff --git a/server/internal/integrations/vcs/gitlab.go b/server/internal/integrations/vcs/gitlab.go
index 615a0be5ce..42ab3459a0 100644
--- a/server/internal/integrations/vcs/gitlab.go
+++ b/server/internal/integrations/vcs/gitlab.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"net/http"
+ "net/url"
"strings"
"time"
)
@@ -24,15 +25,21 @@ func init() { register(gitlabProvider{}) }
func (gitlabProvider) Kind() Kind { return KindGitLab }
-func (gitlabProvider) EventKind(h http.Header) EventKind {
+func (gitlabProvider) EventKind(h http.Header, body []byte) EventKind {
switch h.Get("X-Gitlab-Event") {
case "Merge Request Hook":
return EventPullRequest
case "Pipeline Hook":
return EventCIStatus
- default:
- return EventOther
+ case "System Hook":
+ var event struct {
+ ObjectKind string `json:"object_kind"`
+ }
+ if json.Unmarshal(body, &event) == nil && event.ObjectKind == "merge_request" {
+ return EventPullRequest
+ }
}
+ return EventOther
}
// VerifySignature compares the X-Gitlab-Token header to the stored secret in
@@ -236,6 +243,42 @@ func (gitlabProvider) ValidateToken(ctx context.Context, instanceURL, token stri
return Account{Login: u.Username}, nil
}
+// RepositoryReadable checks the exact project named by a system-hook event.
+// /user validation only proves that the token is valid, not that it can read
+// every private project listed in a workspace.
+func (gitlabProvider) RepositoryReadable(ctx context.Context, instanceURL, owner, name, token string) (bool, error) {
+ // Finish authorization before GitLab's webhook delivery window expires.
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+ project := url.PathEscape(owner + "/" + name)
+ endpoint := NormalizeInstanceURL(instanceURL) + "/api/v4/projects/" + project
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
+ if err != nil {
+ return false, fmt.Errorf("gitlab: build project request: %w", err)
+ }
+ req.Header.Set("PRIVATE-TOKEN", token)
+ req.Header.Set("Accept", "application/json")
+ resp, err := httpClient.Do(req)
+ if err != nil {
+ return false, fmt.Errorf("gitlab: project request: %w", err)
+ }
+ defer resp.Body.Close()
+ switch resp.StatusCode {
+ case http.StatusOK:
+ var projectInfo struct {
+ PathWithNamespace string `json:"path_with_namespace"`
+ }
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&projectInfo); err != nil {
+ return false, fmt.Errorf("gitlab: decode project: %w", err)
+ }
+ return projectInfo.PathWithNamespace == owner+"/"+name, nil
+ case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound:
+ return false, nil
+ default:
+ return false, fmt.Errorf("gitlab: GET project: status %d", resp.StatusCode)
+ }
+}
+
// splitNamespace splits a GitLab path_with_namespace ("group/subgroup/repo")
// into owner ("group/subgroup") and repo name ("repo"). Subgroups are kept in
// the owner so the identity stays unique.
diff --git a/server/internal/integrations/vcs/testdata/gitlab-system-hook-merge.json b/server/internal/integrations/vcs/testdata/gitlab-system-hook-merge.json
new file mode 100644
index 0000000000..0552a6a614
--- /dev/null
+++ b/server/internal/integrations/vcs/testdata/gitlab-system-hook-merge.json
@@ -0,0 +1,149 @@
+{
+ "object_kind": "merge_request",
+ "event_type": "merge_request",
+ "user": {
+ "id": 101,
+ "name": "example-merge-bot",
+ "username": "project_200_bot_00000000000000000000000000000000",
+ "avatar_url": "https://secure.gravatar.com/avatar/0000000000000000000000000000000000000000000000000000000000000000?s=80&d=identicon",
+ "email": "[REDACTED]"
+ },
+ "project": {
+ "id": 200,
+ "name": "Example Project",
+ "description": "",
+ "web_url": "https://gitlab.example.com/example-user/example-project",
+ "avatar_url": null,
+ "git_ssh_url": "[email protected]:example-user/example-project.git",
+ "git_http_url": "https://gitlab.example.com/example-user/example-project.git",
+ "namespace": "Example User",
+ "visibility_level": 0,
+ "path_with_namespace": "example-user/example-project",
+ "default_branch": "main",
+ "ci_config_path": "",
+ "homepage": "https://gitlab.example.com/example-user/example-project",
+ "url": "[email protected]:example-user/example-project.git",
+ "ssh_url": "[email protected]:example-user/example-project.git",
+ "http_url": "https://gitlab.example.com/example-user/example-project.git"
+ },
+ "object_attributes": {
+ "assignee_id": null,
+ "author_id": 100,
+ "created_at": "2026-11-01T08:26:40.226Z",
+ "description": null,
+ "draft": false,
+ "head_pipeline_id": 300,
+ "id": 400,
+ "iid": 10,
+ "last_edited_at": null,
+ "last_edited_by_id": null,
+ "merge_commit_sha": "1111111111111111111111111111111111111111",
+ "merge_error": null,
+ "merge_params": {
+ "force_remove_source_branch": true
+ },
+ "merge_status": "can_be_merged",
+ "merge_user_id": null,
+ "merge_when_pipeline_succeeds": false,
+ "milestone_id": null,
+ "source_branch": "feature/example-change",
+ "source_project_id": 200,
+ "squash_commit_sha": null,
+ "state_id": 3,
+ "target_branch": "main",
+ "target_project_id": 200,
+ "time_estimate": 0,
+ "title": "Example merge request",
+ "updated_at": "2026-11-01T09:15:57.549Z",
+ "updated_by_id": null,
+ "prepared_at": "2026-11-01T08:26:40.951Z",
+ "assignee_ids": [],
+ "blocking_discussions_resolved": true,
+ "detailed_merge_status": "not_open",
+ "first_contribution": false,
+ "human_time_change": null,
+ "human_time_estimate": null,
+ "human_total_time_spent": null,
+ "labels": [],
+ "last_commit": {
+ "id": "2222222222222222222222222222222222222222",
+ "message": "Example commit message\n\nCo-Authored-By: Example Contributor <[email protected]>\n",
+ "title": "Example commit message",
+ "timestamp": "2026-11-01T11:26:30+03:00",
+ "url": "https://gitlab.example.com/example-user/example-project/-/commit/2222222222222222222222222222222222222222",
+ "author": {
+ "name": "example-user",
+ "email": "[REDACTED]"
+ }
+ },
+ "merged_at": "2026-11-01T09:15:57.652Z",
+ "reviewer_ids": [],
+ "source": {
+ "id": 200,
+ "name": "Example Project",
+ "description": "",
+ "web_url": "https://gitlab.example.com/example-user/example-project",
+ "avatar_url": null,
+ "git_ssh_url": "[email protected]:example-user/example-project.git",
+ "git_http_url": "https://gitlab.example.com/example-user/example-project.git",
+ "namespace": "Example User",
+ "visibility_level": 0,
+ "path_with_namespace": "example-user/example-project",
+ "default_branch": "main",
+ "ci_config_path": "",
+ "homepage": "https://gitlab.example.com/example-user/example-project",
+ "url": "[email protected]:example-user/example-project.git",
+ "ssh_url": "[email protected]:example-user/example-project.git",
+ "http_url": "https://gitlab.example.com/example-user/example-project.git"
+ },
+ "state": "merged",
+ "system": false,
+ "target": {
+ "id": 200,
+ "name": "Example Project",
+ "description": "",
+ "web_url": "https://gitlab.example.com/example-user/example-project",
+ "avatar_url": null,
+ "git_ssh_url": "[email protected]:example-user/example-project.git",
+ "git_http_url": "https://gitlab.example.com/example-user/example-project.git",
+ "namespace": "Example User",
+ "visibility_level": 0,
+ "path_with_namespace": "example-user/example-project",
+ "default_branch": "main",
+ "ci_config_path": "",
+ "homepage": "https://gitlab.example.com/example-user/example-project",
+ "url": "[email protected]:example-user/example-project.git",
+ "ssh_url": "[email protected]:example-user/example-project.git",
+ "http_url": "https://gitlab.example.com/example-user/example-project.git"
+ },
+ "target_branch_protected": true,
+ "time_change": 0,
+ "total_time_spent": 0,
+ "url": "https://gitlab.example.com/example-user/example-project/-/merge_requests/10",
+ "work_in_progress": false,
+ "approval_rules": [],
+ "action": "merge",
+ "actioned_at": "2026-11-01T09:15:57.902Z"
+ },
+ "labels": [],
+ "changes": {
+ "merge_commit_sha": {
+ "previous": null,
+ "current": "1111111111111111111111111111111111111111"
+ },
+ "state_id": {
+ "previous": 1,
+ "current": 3
+ },
+ "updated_at": {
+ "previous": "2026-11-01T08:26:40.969Z",
+ "current": "2026-11-01T09:15:57.549Z"
+ }
+ },
+ "repository": {
+ "name": "Example Project",
+ "url": "[email protected]:example-user/example-project.git",
+ "description": "",
+ "homepage": "https://gitlab.example.com/example-user/example-project"
+ }
+}
diff --git a/server/internal/integrations/vcs/vcs.go b/server/internal/integrations/vcs/vcs.go
index 3c0a59f73e..7c265562e7 100644
--- a/server/internal/integrations/vcs/vcs.go
+++ b/server/internal/integrations/vcs/vcs.go
@@ -117,7 +117,7 @@ type Account struct {
type Provider interface {
Kind() Kind
// EventKind classifies an inbound webhook from its headers.
- EventKind(h http.Header) EventKind
+ EventKind(h http.Header, body []byte) EventKind
// VerifySignature authenticates the raw body against the connection's
// stored secret. Forgejo/Gitea use HMAC-SHA256 (X-Gitea-Signature);
// GitLab uses a plaintext token compare (X-Gitlab-Token).
@@ -131,6 +131,13 @@ type Provider interface {
ValidateToken(ctx context.Context, instanceURL, token string) (Account, error)
}
+// RepositoryAccessChecker verifies that the connection token can read the
+// exact repository named by a GitLab system-hook event. Workspace registration
+// is an allowlist, not proof of provider access.
+type RepositoryAccessChecker interface {
+ RepositoryReadable(ctx context.Context, instanceURL, owner, name, token string) (bool, error)
+}
+
// registry maps a Kind to its Provider. Populated by package init in the
// adapter files (forgejo.go, gitlab.go).
var registry = map[Kind]Provider{}
diff --git a/server/internal/integrations/vcs/vcs_test.go b/server/internal/integrations/vcs/vcs_test.go
index 9091f3ee48..959c09e5ea 100644
--- a/server/internal/integrations/vcs/vcs_test.go
+++ b/server/internal/integrations/vcs/vcs_test.go
@@ -5,9 +5,11 @@ import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
+ "encoding/json"
"errors"
"net/http"
"net/http/httptest"
+ "os"
"testing"
"time"
)
@@ -96,11 +98,11 @@ func TestForgejoEventKindAndParse(t *testing.T) {
p, _ := For("gitea")
h := http.Header{}
h.Set("X-Gitea-Event", "pull_request")
- if p.EventKind(h) != EventPullRequest {
+ if p.EventKind(h, nil) != EventPullRequest {
t.Error("pull_request not classified")
}
h.Set("X-Gitea-Event", "status")
- if p.EventKind(h) != EventCIStatus {
+ if p.EventKind(h, nil) != EventCIStatus {
t.Error("status not classified")
}
@@ -139,7 +141,7 @@ func TestGitlabParse(t *testing.T) {
p, _ := For("gitlab")
h := http.Header{}
h.Set("X-Gitlab-Event", "Merge Request Hook")
- if p.EventKind(h) != EventPullRequest {
+ if p.EventKind(h, nil) != EventPullRequest {
t.Error("MR hook not classified")
}
@@ -164,7 +166,7 @@ func TestGitlabParse(t *testing.T) {
}
h.Set("X-Gitlab-Event", "Pipeline Hook")
- if p.EventKind(h) != EventCIStatus {
+ if p.EventKind(h, nil) != EventCIStatus {
t.Error("pipeline hook not classified")
}
st, err := p.ParseCIStatus([]byte(`{"object_kind":"pipeline","object_attributes":{"sha":"deadbeef","status":"failed"}}`))
@@ -176,6 +178,74 @@ func TestGitlabParse(t *testing.T) {
}
}
+func TestGitlabSystemHookMergeRequest(t *testing.T) {
+ p, _ := For("gitlab")
+ h := http.Header{}
+ h.Set("X-Gitlab-Event", "System Hook")
+ // GitLab 19.5.3-ee: https://github.com/multica-ai/multica/pull/10411#issuecomment-6943978266
+ body, err := os.ReadFile("testdata/gitlab-system-hook-merge.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := p.EventKind(h, body); got != EventPullRequest {
+ t.Fatalf("system MR kind = %v, want EventPullRequest", got)
+ }
+ pr, err := p.ParsePullRequest(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if pr.State != "merged" || pr.RepoOwner != "example-user" || pr.RepoName != "example-project" || pr.Number != 10 ||
+ pr.Body != "" || pr.HeadSHA != "2222222222222222222222222222222222222222" ||
+ pr.UpdatedAt != "2026-11-01T09:15:57.549Z" || pr.AuthorLogin != "project_200_bot_00000000000000000000000000000000" {
+ t.Fatalf("system MR = %+v", pr)
+ }
+ if got := p.EventKind(h, []byte(`{"object_kind":"project_create"}`)); got != EventOther {
+ t.Fatalf("unrelated system event kind = %v, want EventOther", got)
+ }
+}
+
+func TestGitlabSystemHookStateUsesExplicitState(t *testing.T) {
+ p, _ := For("gitlab")
+ for _, tc := range []struct {
+ state string
+ stateID int
+ want string
+ }{
+ {"merged", 2, "merged"},
+ {"closed", 3, "closed"},
+ {"opened", 3, "open"},
+ {"", 3, "open"},
+ } {
+ name := tc.state
+ if name == "" {
+ name = "missing_state"
+ }
+ t.Run(name, func(t *testing.T) {
+ body, err := os.ReadFile("testdata/gitlab-system-hook-merge.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var payload map[string]any
+ if err := json.Unmarshal(body, &payload); err != nil {
+ t.Fatal(err)
+ }
+ attrs := payload["object_attributes"].(map[string]any)
+ attrs["state"], attrs["state_id"] = tc.state, tc.stateID
+ if tc.state == "" {
+ delete(attrs, "state")
+ }
+ body, err = json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pr, err := p.ParsePullRequest(body)
+ if err != nil || pr.State != tc.want {
+ t.Fatalf("state=%q state_id=%d: got %q err=%v, want %q", tc.state, tc.stateID, pr.State, err, tc.want)
+ }
+ })
+ }
+}
+
func TestGitlabDraftDetection(t *testing.T) {
p, _ := For("gitlab")
pr, _ := p.ParsePullRequest([]byte(`{"object_kind":"merge_request",
@@ -285,6 +355,37 @@ func TestForgejoStatusTimestamp(t *testing.T) {
}
}
+func TestGitlabRepositoryReadable(t *testing.T) {
+ cases := []struct {
+ status int
+ want bool
+ }{
+ {http.StatusOK, true},
+ {http.StatusForbidden, false},
+ {http.StatusNotFound, false},
+ }
+ for _, tc := range cases {
+ t.Run(http.StatusText(tc.status), func(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/v4/projects/group%2Fsub%2Frepo" && r.URL.EscapedPath() != "/api/v4/projects/group%2Fsub%2Frepo" {
+ t.Errorf("path = %q", r.URL.Path)
+ }
+ if r.Header.Get("PRIVATE-TOKEN") != "tok" {
+ t.Errorf("PRIVATE-TOKEN missing")
+ }
+ w.WriteHeader(tc.status)
+ if tc.status == http.StatusOK {
+ _, _ = w.Write([]byte(`{"path_with_namespace":"group/sub/repo"}`))
+ }
+ }))
+ defer srv.Close()
+ got, err := (&gitlabProvider{}).RepositoryReadable(context.Background(), srv.URL, "group/sub", "repo", "tok")
+ if err != nil || got != tc.want {
+ t.Fatalf("got=%v err=%v want=%v", got, err, tc.want)
+ }
+ })
+ }
+}
func TestValidateTokenUnauthorized(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)