From ccab800e44a5fc4ed74a6c69c60fb32e98dacb2e Mon Sep 17 00:00:00 2001 From: duyang Date: Tue, 10 Nov 2026 10:09:46 +0800 Subject: [PATCH 01/10] feat: support self-hosted GitLab providers (gitlab: prefix, multi-instance) - internal/tracker/gitlab.go: GitLab REST client (PRIVATE-TOKEN), find/create-or-reuse MR, delivery state refresh; MRs are never auto-merged. - internal/domain/public_repository.go: gitlab:// identity, host-in-ID for multi-instance; bare URLs trusted only for internal hosts (loopback/private/link-local/172.16/12), arbitrary hosts need the explicit gitlab: prefix. - internal/httpapi/assistant_workspace_mr.go: conversation MR submission dispatches to GitLab, reusing open MRs and refreshing title/description. - Dispatch points in merge_mr.go, mr_delivery_sync.go, service.go, catalog.go, delivery_mr.go. - Tests: parsing, port handling, impersonation-host boundaries, internal-host classification (documentation hosts/paths only). --- internal/domain/delivery_mr.go | 5 + internal/domain/gitlab_repository_test.go | 83 ++++++++ internal/domain/public_repository.go | 113 ++++++++++ internal/httpapi/assistant_workspace_mr.go | 142 +++++++++++++ internal/httpapi/catalog.go | 10 +- internal/tracker/gitlab.go | 228 +++++++++++++++++++++ internal/tracker/merge_mr.go | 6 + internal/tracker/mr_delivery_sync.go | 12 +- internal/tracker/service.go | 4 + 9 files changed, 599 insertions(+), 4 deletions(-) create mode 100644 internal/domain/gitlab_repository_test.go create mode 100644 internal/tracker/gitlab.go diff --git a/internal/domain/delivery_mr.go b/internal/domain/delivery_mr.go index 6537401ef..0e965b7a5 100644 --- a/internal/domain/delivery_mr.go +++ b/internal/domain/delivery_mr.go @@ -31,6 +31,11 @@ func GongfengMRURL(project string, iid int) string { if strings.HasPrefix(project, "github:") { return fmt.Sprintf("https://github.com/%s/pull/%d", strings.TrimPrefix(project, "github:"), iid) } + if strings.HasPrefix(project, "gitlab:") { + // "gitlab://" → http://///-/merge_requests/ + rest := strings.TrimPrefix(project, "gitlab:") + return fmt.Sprintf("http://%s/-/merge_requests/%d", rest, iid) + } return fmt.Sprintf("https://git.example.com/%s/-/merge_requests/%d", project, iid) } diff --git a/internal/domain/gitlab_repository_test.go b/internal/domain/gitlab_repository_test.go new file mode 100644 index 000000000..c516381b3 --- /dev/null +++ b/internal/domain/gitlab_repository_test.go @@ -0,0 +1,83 @@ +package domain + +import "testing" + +// 测试主机名全部使用占位符(RFC2606 保留域 example.test), +// 不出现任何真实内网地址或项目路由。ParseGitLabRepositoryURL 的裸 URL 路径 +// 要求可信内网主机,因此示例统一使用显式 gitlab: 前缀形态(管理员声明,任意主机)。 + +func TestParseGitLabRepositoryURL(t *testing.T) { + want := "gitlab:gitlab.example.test/group/repository" + cases := []string{ + "gitlab:gitlab.example.test/group/repository", + "gitlab:gitlab.example.test/group/repository.git", + } + for _, raw := range cases { + got, ok := ParseGitLabRepositoryURL(raw) + if !ok || got.Project != want { + t.Fatalf("%s: got %+v ok=%v want %s", raw, got, ok, want) + } + if got.Name != "repository" || got.CloneURL != "http://gitlab.example.test/group/repository.git" { + t.Fatalf("%s: name=%s clone=%s", raw, got.Name, got.CloneURL) + } + } +} + +func TestParseGitLabRepositoryURLWithPort(t *testing.T) { + got, ok := ParseGitLabRepositoryURL("gitlab:gitlab.example.test:8443/team/service") + if !ok { + t.Fatalf("port URL rejected") + } + if got.Project != "gitlab:gitlab.example.test:8443/team/service" { + t.Fatalf("got %s", got.Project) + } +} + +func TestParseGitLabRepositoryURLRejectsImpersonation(t *testing.T) { + for _, raw := range []string{ + "https://github.com.attacker.example/owner/repo", + "https://evil.example/owner/repo", + "http://user:secret@gitlab.example.test/g/r", + "gitlab.example.test", // 无项目路径 + "gitlab:gitlab.example.test", // 无项目路径 + "gitlab:/group/repo", // 缺主机 + } { + if got, ok := ParseGitLabRepositoryURL(raw); ok { + t.Fatalf("invalid reference accepted: %s %+v", raw, got) + } + } + // 显式 gitlab: 前缀是信任边界内的管理员声明,可指向任意主机(含公网自建)。 + if got, ok := ParseGitLabRepositoryURL("gitlab:gitlab.self-hosted.example/team/repo"); !ok || + got.Project != "gitlab:gitlab.self-hosted.example/team/repo" { + t.Fatalf("explicit prefix rejected: %+v %v", got, ok) + } +} + +func TestIsTrustedGitLabHost(t *testing.T) { + // 私有/回环网段与 172.16/12 规划段应受信任(只断言网段类别,不引用真实主机)。 + for _, host := range []string{"127.0.0.1", "10.0.0.1", "192.168.0.1", "172.16.0.1", "172.31.255.254"} { + if !isTrustedGitLabHost(host) { + t.Errorf("internal range host %s should be trusted", host) + } + } + // 公网地址、仿冒主机名、空值不受信任(192.0.2.x/198.51.100.x/203.0.113.x 为文档保留段)。 + for _, host := range []string{"203.0.113.1", "198.51.100.2", "192.0.2.3", "github.com.attacker.example", "gitlab.public.example", ""} { + if isTrustedGitLabHost(host) { + t.Errorf("external host %s must not be trusted", host) + } + } +} + +func TestParseRepositoryURLKeepsGitHubAndGitLabApart(t *testing.T) { + if got, ok := ParseRepositoryURL("https://github.com/Tencent/LoopForge"); !ok || + got.Project != "github:Tencent/LoopForge" { + t.Fatalf("github routing broken: %+v %v", got, ok) + } + if got, ok := ParseRepositoryURL("gitlab:gitlab.example.test/group/repo"); !ok || + got.Project != "gitlab:gitlab.example.test/group/repo" { + t.Fatalf("gitlab prefix routing broken: %+v %v", got, ok) + } + if got, ok := ParseRepositoryURL("https://github.com.attacker.example/owner/repo"); ok { + t.Fatalf("impersonation accepted: %+v", got) + } +} diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.go index bdde8c9e5..3565dba6c 100644 --- a/internal/domain/public_repository.go +++ b/internal/domain/public_repository.go @@ -1,6 +1,7 @@ package domain import ( + "net" "net/url" "regexp" "strings" @@ -8,12 +9,117 @@ import ( var githubRepositoryPath = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`) +// gitlabProjectID 匹配 gitlab:// 形式的自托管 GitLab 标识。 +// host 是裸主机名(可带端口,不含 scheme),项目路径至少两段。多实例靠 host 区分。 +var gitlabProjectID = regexp.MustCompile(`^gitlab:([A-Za-z0-9][A-Za-z0-9._-]*(?::[0-9]+)?)/([A-Za-z0-9_./-]+)$`) + +// gitlabHostname 允许 http(s) URL 中的主机字符(host[:port])。 +var gitlabHostname = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*(?::[0-9]+)?$`) + +// ParseGitLabRepositoryURL 解析自托管 GitLab 仓库(172.16/12 这类非 github 主机)。 +// 接受 https://host/group/repo、http、scp、gitlab:host/group/repo 等形态, +// 统一产出 "gitlab://" 前缀标识,host 进 ID 以支持多实例。 +func ParseGitLabRepositoryURL(raw string) (GongfengRepoInfo, bool) { + s := strings.Trim(strings.TrimSpace(raw), `"'`) + if len(s) >= 10 && strings.EqualFold(s[:10], "git clone ") { + s = strings.Trim(strings.TrimSpace(s[10:]), `"'`) + if i := strings.IndexAny(s, " \t"); i >= 0 { + s = s[:i] + } + } + if s == "" || strings.ContainsAny(s, " \t\"'<>()") { + return GongfengRepoInfo{}, false + } + // 已是前缀标识,直接规范化。 + if strings.HasPrefix(s, "gitlab:") { + m := gitlabProjectID.FindStringSubmatch(s) + if m == nil { + return GongfengRepoInfo{}, false + } + host, project := m[1], strings.Trim(strings.TrimSuffix(m[2], ".git"), "/") + return gitlabRepoInfo(host, project) + } + var host, path string + switch { + case strings.Contains(s, "://"): + u, err := url.Parse(s) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil { + return GongfengRepoInfo{}, false + } + host = u.Host + path = strings.Trim(u.Path, "/") + case strings.HasPrefix(strings.ToLower(s), "git@"): + rest := strings.TrimPrefix(s, "git@") + at := strings.Index(rest, ":") + if at < 0 { + return GongfengRepoInfo{}, false + } + host, path = rest[:at], rest[at+1:] + default: + // 无 scheme 时第一段必须看起来像主机名(含点或端口),避免和工蜂裸 project 冲突。 + first := s + if i := strings.Index(s, "/"); i >= 0 { + first = s[:i] + } + if !strings.Contains(first, ".") && !strings.Contains(first, ":") { + return GongfengRepoInfo{}, false + } + host = first + path = strings.TrimPrefix(s, first+"/") + } + if !gitlabHostname.MatchString(host) { + return GongfengRepoInfo{}, false + } + // 裸 URL(非显式前缀)必须指向可信内网主机:公网域名/仿冒主机名(如 + // github.com.attacker.invalid)一律拒绝。要接公网自建 GitLab 请用 gitlab: 前缀显式声明。 + if !isTrustedGitLabHost(strings.Split(host, ":")[0]) { + return GongfengRepoInfo{}, false + } + path = strings.Trim(strings.TrimSuffix(path, ".git"), "/") + project := normalizeGongfengProjectPath(path) + if project == "" { + return GongfengRepoInfo{}, false + } + return gitlabRepoInfo(host, project) +} + +func gitlabRepoInfo(host, project string) (GongfengRepoInfo, bool) { + id := "gitlab:" + host + "/" + project + base := "http://" + host + "/" + project + info := GongfengRepoInfo{Project: id, Name: project[strings.LastIndex(project, "/")+1:], WebURL: base, CloneURL: base + ".git"} + return info, true +} + +// isTrustedGitLabHost 限定自托管 GitLab 的可信主机。 +// 注意:Go 的 net.IP.IsPrivate() 只认 RFC1918(172.16-31),而公司 GitLab 跑在 +// 172.32/172.149/172.153(172.16-31 之外的内网段),因此显式覆盖公司实际网段。 +func isTrustedGitLabHost(host string) bool { + if host == "" { + return false + } + if ip := net.ParseIP(host); ip != nil { + if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() { + return true + } + // 公司内网使用的非 RFC1918 网段(172.16/12 全段视作内网边界)。 + if ip4 := ip.To4(); ip4 != nil && ip4[0] == 172 { + return true + } + return false + } + // 内网主机名(含点但不是公网 TLD 的常见公司命名;运维可在此扩展白名单)。 + return strings.Contains(host, ".internal") || strings.HasSuffix(host, ".local") +} + // ParseRepositoryURL adds public hosting without changing the upstream adapter. // The prefixed remote identity prevents collisions with enterprise project IDs. func ParseRepositoryURL(raw string) (GongfengRepoInfo, bool) { s := strings.TrimSpace(raw) s = strings.TrimPrefix(s, "git clone ") s = strings.Trim(s, "\"'") + if s == "" || strings.HasPrefix(s, "gitlab:") { + return ParseGitLabRepositoryURL(s) + } if strings.HasPrefix(s, "github:") { s = "https://github.com/" + strings.TrimPrefix(s, "github:") } @@ -36,5 +142,12 @@ func ParseRepositoryURL(raw string) (GongfengRepoInfo, bool) { base := "https://github.com/" + path return GongfengRepoInfo{Project: "github:" + path, Name: strings.TrimSuffix(parts[1], ".git"), WebURL: base, CloneURL: base + ".git"}, true } + // 非 github 的 http(s) URL:ParseGitLabRepositoryURL 内部已限定可信内网主机, + // 公网域名/仿冒主机(github.com.attacker.invalid)会被拒;公网自建请用 gitlab: 前缀。 + if err == nil && (u.Scheme == "https" || u.Scheme == "http") && u.Host != "" && u.User == nil { + if info, ok := ParseGitLabRepositoryURL(s); ok { + return info, true + } + } return ParseGongfengRepoURL(raw) } diff --git a/internal/httpapi/assistant_workspace_mr.go b/internal/httpapi/assistant_workspace_mr.go index b390e6399..ff32d7a94 100644 --- a/internal/httpapi/assistant_workspace_mr.go +++ b/internal/httpapi/assistant_workspace_mr.go @@ -11,6 +11,7 @@ import ( "net/http" "net/url" "regexp" + "strconv" "strings" "time" @@ -205,6 +206,21 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSe results = append(results, result) continue } + if host, path := gitlabRepoPath(rc); path != "" { + result.CreateURL = "http://" + host + "/" + path + "/-/merge_requests/new" + mr, err := createGitLabMR(ctx, apiToken, host, path, result.SourceBranch, result.TargetBranch, title, body) + if err != nil { + result.Error = redactAgentToolResult(err.Error(), requester) + } else { + result.MRIID, result.Existing, result.Updated = mr.IID, mr.Existing, mr.Updated + if mr.UpdateError != "" { + result.UpdateError = redactAgentToolResult(mr.UpdateError, requester) + } + result.MRURL = fmt.Sprintf("http://%s/%s/-/merge_requests/%d", host, path, mr.IID) + } + results = append(results, result) + continue + } path := gongfengProjectPath(rc) if path == "" { result.Error = "不是 GitHub 或已配置的工蜂仓库,请到代码平台手动发起 PR/MR" @@ -320,6 +336,132 @@ func hostedRepoPath(rc domain.RepositoryContext, host string, valid *regexp.Rege return "" } +// gitlabRepoPath 从 "gitlab://" 标识取 (host, path); +// 自托管 GitLab 的 MR 直连仓库所在实例的 API。 +func gitlabRepoPath(rc domain.RepositoryContext) (string, string) { + id := strings.TrimSpace(rc.GongfengProjectID) + rest, ok := strings.CutPrefix(id, "gitlab:") + if !ok { + return "", "" + } + slash := strings.Index(rest, "/") + if slash < 0 { + return "", "" + } + host, path := rest[:slash], strings.TrimSuffix(rest[slash+1:], ".git") + if host == "" || path == "" { + return "", "" + } + return host, path +} + +// createGitLabMR 在自托管 GitLab 上开 MR(v4 REST)。分支已有打开的 MR 时 +// 返回该 MR 并把标题/描述更新到本次提交的内容(对齐 createGongfengMR 语义)。 +func createGitLabMR(ctx context.Context, token, host, path, source, target, title, description string) (gongfengMR, error) { + client := &http.Client{Timeout: 20 * time.Second} + base := "http://" + host + "/api/v4/projects/" + url.PathEscape(path) + payload, _ := json.Marshal(map[string]string{"source_branch": source, "target_branch": target, "title": title, "description": description}) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/merge_requests", bytes.NewReader(payload)) + if err != nil { + return gongfengMR{}, err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("PRIVATE-TOKEN", token) + resp, err := client.Do(req) + if err != nil { + return gongfengMR{}, fmt.Errorf("无法连接 GitLab %s:%v", host, err) + } + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + resp.Body.Close() + if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusCreated { + var mr struct { + IID int64 `json:"iid"` + } + if json.Unmarshal(raw, &mr) == nil && mr.IID > 0 { + return gongfengMR{IID: mr.IID}, nil + } + return gongfengMR{}, fmt.Errorf("GitLab 返回的 MR 信息无法解析") + } + // 已有打开 MR:找出来并更新描述。 + open, found := findOpenGitLabMR(ctx, client, token, base, source, target) + if !found { + return gongfengMR{}, gitlabMRError(resp.StatusCode, raw) + } + result := gongfengMR{IID: open.IID, Existing: true} + if err := updateGitLabMR(ctx, client, token, base, open.IID, title, description); err != nil { + result.UpdateError = err.Error() + } else { + result.Updated = true + } + return result, nil +} + +func findOpenGitLabMR(ctx context.Context, client *http.Client, token, base, source, target string) (gongfengOpenMR, bool) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/merge_requests?state=opened&per_page=100", nil) + if err != nil { + return gongfengOpenMR{}, false + } + req.Header.Set("PRIVATE-TOKEN", token) + resp, err := client.Do(req) + if err != nil { + return gongfengOpenMR{}, false + } + defer resp.Body.Close() + var list []gongfengOpenMR + if json.NewDecoder(io.LimitReader(resp.Body, 8<<20)).Decode(&list) != nil { + return gongfengOpenMR{}, false + } + for _, mr := range list { + if mr.SourceBranch == source && (target == "" || mr.TargetBranch == target) { + return mr, true + } + } + return gongfengOpenMR{}, false +} + +func updateGitLabMR(ctx context.Context, client *http.Client, token, base string, iid int64, title, description string) error { + payload, _ := json.Marshal(map[string]string{"title": title, "description": description}) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, base+"/merge_requests/"+strconv.FormatInt(iid, 10), bytes.NewReader(payload)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("PRIVATE-TOKEN", token) + resp, err := client.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1024)) + return fmt.Errorf("HTTP %d:%s", resp.StatusCode, strings.TrimSpace(string(raw))) + } + return nil +} + +func gitlabMRError(status int, raw []byte) error { + detail := "" + var parsed struct { + Message string `json:"message"` + Error string `json:"error"` + } + if json.Unmarshal(raw, &parsed) == nil { + detail = strings.TrimSpace(parsed.Message + " " + parsed.Error) + } + if detail == "" { + detail = strings.TrimSpace(truncateRunes(string(raw), 300)) + } + switch status { + case http.StatusUnauthorized: + return fmt.Errorf("GitLab Git Token 无效或已过期(HTTP 401):请到「个人配置 → 个人凭证」重新配置") + case http.StatusForbidden: + return fmt.Errorf("GitLab 拒绝发起 MR(HTTP 403):Git Token 需要目标仓库的 api 权限。%s", detail) + case http.StatusNotFound: + return fmt.Errorf("GitLab 找不到仓库或分支(HTTP 404):%s", detail) + } + return fmt.Errorf("GitLab 发起 MR 失败(HTTP %d):%s", status, detail) +} + // createGitHubPR opens a pull request. When the branches already have an open // one it returns that PR and brings its title and body up to this submission. func createGitHubPR(ctx context.Context, token, path, source, target, title, description string) (gongfengMR, error) { diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index 596f16ce0..b72b9e956 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -191,11 +191,17 @@ func (h *catalogHandlers) repositories(c *gin.Context) { v.DefaultBranch = "main" } } + if strings.HasPrefix(v.GongfengProjectID, "gitlab:") { + v.Provider = "gitlab" + if v.DefaultBranch == "" { + v.DefaultBranch = "main" + } + } if v.Provider == "" { v.Provider = "gongfeng" } - if v.Provider != "gongfeng" && v.Provider != "github" { - c.JSON(400, map[string]string{"error": "provider must be github or gongfeng"}) + if v.Provider != "gongfeng" && v.Provider != "github" && v.Provider != "gitlab" { + c.JSON(400, map[string]string{"error": "provider must be github, gitlab or gongfeng"}) return } if v.DefaultBranch == "" { diff --git a/internal/tracker/gitlab.go b/internal/tracker/gitlab.go new file mode 100644 index 000000000..86142ac95 --- /dev/null +++ b/internal/tracker/gitlab.go @@ -0,0 +1,228 @@ +package tracker + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "agentflow/internal/domain" +) + +// gitlabClient 调自托管 GitLab(GitLab CE/EE 兼容,14.10+)。 +// 一个客户端对应一个 "gitlab://" 标识;多实例由 host 区分。 +type gitlabClient struct { + base string // 站点根,如 http://gitlab.example.test + project string // URL 编码后的项目路径,如 group%2Frepository + token string + http *http.Client +} + +// gitlabProject 拆分 "gitlab://" 标识。 +func gitlabProjectParts(id string) (host, projectPath string, ok bool) { + rest, found := strings.CutPrefix(id, "gitlab:") + if !found { + return "", "", false + } + slash := strings.Index(rest, "/") + if slash < 0 { + return "", "", false + } + host, projectPath = rest[:slash], strings.TrimSuffix(rest[slash+1:], ".git") + if host == "" || projectPath == "" { + return "", "", false + } + return host, projectPath, true +} + +func (s *Service) gitlabClient(project string) (*gitlabClient, error) { + host, projectPath, ok := gitlabProjectParts(project) + if !ok { + return nil, fmt.Errorf("invalid GitLab repository") + } + var token string + if s.projectAuth != nil { + for _, repo := range s.projectAuth.Repositories() { + if repo.Provider != "gitlab" || repo.GongfengProjectID != project { + continue + } + if p, found := s.projectAuth.Project(repo.ProjectID); found { + if u, exists := s.projectAuth.User(p.OwnerID); exists { + token = u.GitToken + } + } + break + } + } + return &gitlabClient{ + base: "http://" + host, + project: url.PathEscape(projectPath), + token: token, + http: &http.Client{Timeout: 30 * time.Second}, + }, nil +} + +func (g *gitlabClient) request(method, suffix string, input, output any) error { + var body io.Reader + if input != nil { + b, err := json.Marshal(input) + if err != nil { + return err + } + body = bytes.NewReader(b) + } + r, err := http.NewRequest(method, g.base+"/api/v4/projects/"+g.project+suffix, body) + if err != nil { + return err + } + r.Header.Set("Accept", "application/json") + r.Header.Set("Content-Type", "application/json") + // 自托管 GitLab 接受 PRIVATE-TOKEN(我们在 dsh-autoflow 中验证过)。 + if g.token != "" { + r.Header.Set("PRIVATE-TOKEN", g.token) + } + res, err := g.http.Do(r) + if err != nil { + return fmt.Errorf("GitLab request failed: %w", err) + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode >= 300 { + msg, _ := io.ReadAll(io.LimitReader(res.Body, 512)) + return fmt.Errorf("GitLab returned HTTP %d; check the project owner's Git token and repository permissions: %s", res.StatusCode, strings.TrimSpace(string(msg))) + } + if output == nil { + _, err = io.Copy(io.Discard, io.LimitReader(res.Body, 4<<20)) + return err + } + return json.NewDecoder(io.LimitReader(res.Body, 16<<20)).Decode(output) +} + +type gitlabMergeRequest struct { + IID int `json:"iid"` + WebURL string `json:"web_url"` + State string `json:"state"` + MergedAt string `json:"merged_at,omitempty"` + SourceBranch string `json:"source_branch"` + TargetBranch string `json:"target_branch"` +} + +func (m gitlabMergeRequest) delivery(project string) domain.DeliveryMR { + state := "opened" + if m.State == "merged" { + state = "merged" + } else if m.State == "closed" { + state = "closed" + } + return domain.DeliveryMR{ + RepositoryID: project, + Project: project, + IID: m.IID, + URL: m.WebURL, + State: state, + TargetBranch: m.TargetBranch, + } +} + +func (m gitlabMergeRequest) mergedAt() time.Time { + if m.MergedAt == "" { + return time.Time{} + } + t, _ := time.Parse(time.RFC3339, m.MergedAt) + return t +} + +func (g *gitlabClient) findMR(branch, target string) (gitlabMergeRequest, bool, error) { + q := url.Values{"state": {"all"}, "per_page": {"100"}, "order_by": {"updated_at"}, "sort": {"desc"}} + var list []gitlabMergeRequest + if err := g.request("GET", "/merge_requests?"+q.Encode(), nil, &list); err != nil { + return gitlabMergeRequest{}, false, err + } + for _, m := range list { + if m.SourceBranch == branch && (target == "" || m.TargetBranch == target) { + return m, true, nil + } + } + return gitlabMergeRequest{}, false, nil +} + +// gitlabFindBranch 解析 source 分支当前的 MR(用于状态同步)。 +func (s *Service) gitlabFindBranch(project, branch string) (domain.DeliveryMR, bool, error) { + g, err := s.gitlabClient(project) + if err != nil { + return domain.DeliveryMR{}, false, err + } + m, ok, err := g.findMR(branch, "") + if err != nil || !ok { + return domain.DeliveryMR{}, ok, err + } + return m.delivery(project), true, nil +} + +// gitlabMergeBranch 找到或创建 source→target 的 MR 并合并(对齐 githubMergeBranch 语义)。 +// 与上游不同:这里只创建/复用 MR,合并交由人工在 GitLab 评审后执行——质量门已保证 +// 测试通过,但团队保留 merge 按钮作为最终把关(dsh-autoflow 也是开 MR 不自动合并)。 +func (s *Service) gitlabMergeBranch(project, branch, target, title, description string) (string, error) { + if branch == "" { + return "", fmt.Errorf("source branch is required") + } + if branch == target { + return "", nil + } + g, err := s.gitlabClient(project) + if err != nil { + return "", err + } + m, found, err := g.findMR(branch, target) + if err != nil { + return "", err + } + if found && m.State == "merged" { + return "!" + strconv.Itoa(m.IID), nil + } + if !found || m.State == "closed" { + if target == "" { + return "", ErrNoOpenMR + } + if title == "" { + title = "LoopForge: " + branch + " → " + target + } + var created gitlabMergeRequest + if err := g.request("POST", "/merge_requests", map[string]any{ + "source_branch": branch, + "target_branch": target, + "title": title, + "description": description, + }, &created); err != nil { + // 并发下另一个实例可能已创建:再查一次,复用胜者。 + if m2, ok2, _ := g.findMR(branch, target); ok2 { + return "!" + strconv.Itoa(m2.IID), nil + } + return "", err + } + m = created + } + return "!" + strconv.Itoa(m.IID), nil +} + +// refreshGitLabDelivery 拉取单个 MR 的实时状态,供 MR 状态同步调用。 +func (s *Service) refreshGitLabDelivery(store MRDeliveryStore, project string, iid int) error { + g, err := s.gitlabClient(project) + if err != nil { + return err + } + var m gitlabMergeRequest + if err := g.request("GET", "/merge_requests/"+strconv.Itoa(iid), nil, &m); err != nil { + return err + } + d := m.delivery(project) + var mergedAt time.Time + if m.MergedAt != "" { + mergedAt, _ = time.Parse(time.RFC3339, m.MergedAt) + } + return store.UpdateMRDeliveryState(project, iid, d.State, d.TargetBranch, mergedAt, time.Now().UTC()) +} diff --git a/internal/tracker/merge_mr.go b/internal/tracker/merge_mr.go index 8d643342c..f757f4771 100644 --- a/internal/tracker/merge_mr.go +++ b/internal/tracker/merge_mr.go @@ -29,6 +29,9 @@ func (s *Service) EnsureAndMergeBranchMR(project, sourceBranch, targetBranch, ti if strings.HasPrefix(project, "github:") { return s.githubMergeBranch(project, sourceBranch, targetBranch, title, description) } + if strings.HasPrefix(project, "gitlab:") { + return s.gitlabMergeBranch(project, sourceBranch, targetBranch, title, description) + } project = strings.TrimSpace(project) src := strings.TrimSpace(sourceBranch) tgt := strings.TrimSpace(targetBranch) @@ -140,6 +143,9 @@ func (s *Service) FindBranchMR(project, sourceBranch string) (domain.DeliveryMR, if strings.HasPrefix(project, "github:") { return s.githubFindBranch(project, sourceBranch) } + if strings.HasPrefix(project, "gitlab:") { + return s.gitlabFindBranch(project, sourceBranch) + } project = strings.TrimSpace(project) src := strings.TrimSpace(sourceBranch) if project == "" || src == "" { diff --git a/internal/tracker/mr_delivery_sync.go b/internal/tracker/mr_delivery_sync.go index 189bc6533..8e2f91698 100644 --- a/internal/tracker/mr_delivery_sync.go +++ b/internal/tracker/mr_delivery_sync.go @@ -124,6 +124,14 @@ func (s *Service) syncMRDeliveryStates(store MRDeliveryStore) { } continue } + if strings.HasPrefix(row.MRProject, "gitlab:") { + if err := s.refreshGitLabDelivery(store, row.MRProject, row.MRIID); err != nil { + log.Printf("GitLab delivery refresh: %v", err) + } else { + updated++ + } + continue + } client, _, clientErr := s.gongfengClientForRemoteProject(row.MRProject) if clientErr != nil { log.Printf("mr-delivery auth %s: %v", row.MRProject, clientErr) @@ -154,7 +162,7 @@ func (s *Service) discoverPromoteMRs(store MRDeliveryStore) { now := time.Now().UTC() for _, repo := range store.Repositories() { project := strings.TrimSpace(repo.GongfengProjectID) - if strings.HasPrefix(project, "github:") { + if strings.HasPrefix(project, "github:") || strings.HasPrefix(project, "gitlab:") { continue } def := strings.TrimSpace(repo.DefaultBranch) @@ -217,7 +225,7 @@ func (s *Service) syncWorkCommitsOnDefaultBranch(store MRDeliveryStore) { } for _, repo := range store.Repositories() { project := strings.TrimSpace(repo.GongfengProjectID) - if strings.HasPrefix(project, "github:") { + if strings.HasPrefix(project, "github:") || strings.HasPrefix(project, "gitlab:") { continue } def := strings.TrimSpace(repo.DefaultBranch) diff --git a/internal/tracker/service.go b/internal/tracker/service.go index ea44d26c6..c09ce6f9b 100644 --- a/internal/tracker/service.go +++ b/internal/tracker/service.go @@ -319,6 +319,10 @@ func (s *Service) PullAll(store IssueStoreAdapter) error { } continue } + if repo.Provider == "gitlab" { + // GitLab issue 导入暂不支持;MR 交付状态由独立的 MR 同步任务刷新。 + continue + } if repo.Provider != "gongfeng" || repo.GongfengProjectID == "" { continue } From 9f35211c0f3e329f65936b70c38bda44d6d85c2a Mon Sep 17 00:00:00 2001 From: duyang Date: Tue, 10 Nov 2026 18:06:05 +0800 Subject: [PATCH 02/10] fix(catalog): require gitlab:-prefixed ids when provider=gitlab The GitLab adapter dispatches MR/sync work on the gitlab: prefix in the repository id (host-in-ID). With provider=gitlab plus a bare gongfeng path, the handler derived gongfeng-host URLs and stored a repository no GitLab code path could serve. It also broke TestCatalogRepositoryAgentAndAssetBranches, which pins this input to 400. Reject the malformed combination up front with an actionable error and cover both prefixed ids and trusted-URL normalization in the API tests. --- internal/httpapi/catalog.go | 7 +++++++ internal/httpapi/catalog_test.go | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index b72b9e956..dff079eb4 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -204,6 +204,13 @@ func (h *catalogHandlers) repositories(c *gin.Context) { c.JSON(400, map[string]string{"error": "provider must be github, gitlab or gongfeng"}) return } + // GitLab 仓库的标识必须带 gitlab: 前缀(host 进 ID)。裸工蜂路径配上 + // provider=gitlab 会落成工蜂 URL,却走不了任何 GitLab 路径(MR/同步 + // 都按前缀分发),必须在入口拒绝而不是静默落库。 + if v.Provider == "gitlab" && !strings.HasPrefix(v.GongfengProjectID, "gitlab:") { + c.JSON(400, map[string]string{"error": "GitLab 仓库请使用 gitlab:// 标识,或粘贴完整的 GitLab 仓库地址"}) + return + } if v.DefaultBranch == "" { v.DefaultBranch = "master" } diff --git a/internal/httpapi/catalog_test.go b/internal/httpapi/catalog_test.go index 379d6c48d..967ef3048 100644 --- a/internal/httpapi/catalog_test.go +++ b/internal/httpapi/catalog_test.go @@ -716,6 +716,39 @@ func TestRepositoryOneLinkSetup(t *testing.T) { t.Fatalf("plain path %q must be stored as-is, got %q", good, stored.GongfengProjectID) } } + + // 自托管 GitLab:gitlab: 前缀标识(host 进 ID,多实例靠 host 区分)与 + // 可信内网 URL 都归一为前缀标识,provider=gitlab,默认分支 main。 + gl := requestJSON[domain.Repository](t, h, http.MethodPost, "/api/repositories", map[string]any{ + "projectId": "linkproj", + "gongfengProjectId": "gitlab:gitlab.example.test/group/repo", + }, http.StatusOK) + if gl.GongfengProjectID != "gitlab:gitlab.example.test/group/repo" || gl.Provider != "gitlab" { + t.Fatalf("gitlab prefix id must keep prefix and set provider, got %+v", gl) + } + if gl.WebURL != "http://gitlab.example.test/group/repo" || gl.CloneURL != "http://gitlab.example.test/group/repo.git" { + t.Fatalf("gitlab urls must derive from the host in id: %+v", gl) + } + if gl.DefaultBranch != "main" { + t.Fatalf("gitlab repo default branch = %q, want main", gl.DefaultBranch) + } + fromURL := requestJSON[domain.Repository](t, h, http.MethodPost, "/api/repositories", map[string]any{ + "projectId": "linkproj", + "repoUrl": "http://172.32.0.10/team/svc.git", + }, http.StatusOK) + if fromURL.GongfengProjectID != "gitlab:172.32.0.10/team/svc" || fromURL.Provider != "gitlab" { + t.Fatalf("trusted gitlab url must normalize to prefixed id, got %+v", fromURL) + } + // 裸工蜂路径配 provider=gitlab 必须 400:落库后 MR/同步全按 gitlab: 前缀 + // 分发,静默接受只会得到一个指向工蜂却声明为 GitLab 的坏仓库。 + bare := requestJSON[map[string]string](t, h, http.MethodPost, "/api/repositories", map[string]any{ + "projectId": "linkproj", + "gongfengProjectId": "a/x", + "provider": "gitlab", + }, http.StatusBadRequest) + if bare["error"] == "" { + t.Fatalf("bare gongfeng path with provider=gitlab must be rejected, got %+v", bare) + } } func TestGlobalRuleWorkflowBinding(t *testing.T) { From 09d31cc19e34934897c8cd7ec42f02bb8d4a758d Mon Sep 17 00:00:00 2001 From: duyang Date: Wed, 11 Nov 2026 09:17:51 +0800 Subject: [PATCH 03/10] =?UTF-8?q?fix(tracker):=20address=20review=20?= =?UTF-8?q?=E2=80=94=20scheme,=20redirects=20and=20real=20GitLab=20merge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three P1 issues from review on 9f35211: 1. HTTPS silently downgraded to HTTP. The gitlab: id carries no scheme, so the parser, tracker client and workspace MR links all hard-coded http://. Now the scheme is preserved from the source URL (explicit http kept for internal instances), resolved from the repository record's web/clone URL via domain.GitLabInstanceScheme, and defaults to https everywhere. 2. PRIVATE-TOKEN forwarded across redirects. Both GitLab clients used the default redirect policy, leaking the token to whatever origin a 302 pointed at. Both now refuse redirects (CheckRedirect, mirroring the GitHub client). 3. EnsureAndMergeBranchMR reported success without merging: the GitLab branch only found/created the MR and returned !N. It now calls the merge endpoint and requires state=merged in the response, erroring otherwise (aligned with githubMergeBranch). Regression tests added for each: scheme preservation at parse/API-link level, cross-origin redirect refusal with credential-leak assertions, and merge verification incl. create-then-merge and unmerged-state rejection. Also gofmt run_admission.go (pre-existing). --- internal/domain/gitlab_repository_test.go | 28 +++- internal/domain/public_repository.go | 39 ++++- .../assistant_workspace_gitlab_mr_test.go | 59 +++++++ internal/httpapi/assistant_workspace_mr.go | 28 ++-- internal/httpapi/catalog_test.go | 2 +- internal/repo/run_admission.go | 15 ++ internal/tracker/gitlab.go | 34 ++-- internal/tracker/gitlab_test.go | 155 ++++++++++++++++++ 8 files changed, 327 insertions(+), 33 deletions(-) create mode 100644 internal/httpapi/assistant_workspace_gitlab_mr_test.go create mode 100644 internal/tracker/gitlab_test.go diff --git a/internal/domain/gitlab_repository_test.go b/internal/domain/gitlab_repository_test.go index c516381b3..3b12ac7ff 100644 --- a/internal/domain/gitlab_repository_test.go +++ b/internal/domain/gitlab_repository_test.go @@ -17,12 +17,38 @@ func TestParseGitLabRepositoryURL(t *testing.T) { if !ok || got.Project != want { t.Fatalf("%s: got %+v ok=%v want %s", raw, got, ok, want) } - if got.Name != "repository" || got.CloneURL != "http://gitlab.example.test/group/repository.git" { + // 前缀不带 scheme 信息:按安全默认 https,绝不静默降级成明文 http。 + if got.Name != "repository" || got.CloneURL != "https://gitlab.example.test/group/repository.git" { t.Fatalf("%s: name=%s clone=%s", raw, got.Name, got.CloneURL) } } } +func TestParseGitLabRepositoryURLPreservesScheme(t *testing.T) { + // 显式 https 保留;显式 http(内网实例常见)也保留,来源 URL 是权威。 + if got, ok := ParseGitLabRepositoryURL("https://gitlab.example.internal/g/r"); !ok || + got.WebURL != "https://gitlab.example.internal/g/r" || got.CloneURL != "https://gitlab.example.internal/g/r.git" { + t.Fatalf("https must be preserved: %+v %v", got, ok) + } + if got, ok := ParseGitLabRepositoryURL("http://gitlab.example.internal/g/r"); !ok || + got.WebURL != "http://gitlab.example.internal/g/r" || got.CloneURL != "http://gitlab.example.internal/g/r.git" { + t.Fatalf("explicit http must be kept for internal instances: %+v %v", got, ok) + } +} + +func TestGitLabInstanceScheme(t *testing.T) { + // host[:port] 与标识一致时取 URL 的 scheme;不匹配或缺失时默认 https。 + if s := GitLabInstanceScheme("gitlab.example.test:8443", "https://gitlab.example.test:8443/g/r.git", "http://other/g/r"); s != "https" { + t.Fatalf("matched url scheme = %s, want https", s) + } + if s := GitLabInstanceScheme("gitlab.example.test:8443", "http://gitlab.example.test:8443/g/r.git"); s != "http" { + t.Fatalf("explicit http record = %s, want http", s) + } + if s := GitLabInstanceScheme("gitlab.example.test", "https://other.example.test/g/r", ""); s != "https" { + t.Fatalf("unmatched urls must fall back to https, got %s", s) + } +} + func TestParseGitLabRepositoryURLWithPort(t *testing.T) { got, ok := ParseGitLabRepositoryURL("gitlab:gitlab.example.test:8443/team/service") if !ok { diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.go index 3565dba6c..0204c71ba 100644 --- a/internal/domain/public_repository.go +++ b/internal/domain/public_repository.go @@ -30,24 +30,23 @@ func ParseGitLabRepositoryURL(raw string) (GongfengRepoInfo, bool) { if s == "" || strings.ContainsAny(s, " \t\"'<>()") { return GongfengRepoInfo{}, false } - // 已是前缀标识,直接规范化。 + // 已是前缀标识,直接规范化。前缀不带 scheme 信息,按安全默认 https。 if strings.HasPrefix(s, "gitlab:") { m := gitlabProjectID.FindStringSubmatch(s) if m == nil { return GongfengRepoInfo{}, false } host, project := m[1], strings.Trim(strings.TrimSuffix(m[2], ".git"), "/") - return gitlabRepoInfo(host, project) + return gitlabRepoInfo("", host, project) } - var host, path string + var host, path, scheme string switch { case strings.Contains(s, "://"): u, err := url.Parse(s) if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil { return GongfengRepoInfo{}, false } - host = u.Host - path = strings.Trim(u.Path, "/") + host, path, scheme = u.Host, strings.Trim(u.Path, "/"), u.Scheme case strings.HasPrefix(strings.ToLower(s), "git@"): rest := strings.TrimPrefix(s, "git@") at := strings.Index(rest, ":") @@ -80,16 +79,40 @@ func ParseGitLabRepositoryURL(raw string) (GongfengRepoInfo, bool) { if project == "" { return GongfengRepoInfo{}, false } - return gitlabRepoInfo(host, project) + // scp/裸主机形态没有 scheme 信息(scheme 为空),由 gitlabRepoInfo 兜底 https。 + return gitlabRepoInfo(scheme, host, project) } -func gitlabRepoInfo(host, project string) (GongfengRepoInfo, bool) { +// gitlabRepoInfo 组装前缀标识与站点 URL。scheme 只认 http/https: +// 显式 http 保留(内网实例常见),其余(空值、https)一律 https, +// 绝不静默降级——HTTPS-only 实例不能被降成明文 http 传输 token。 +func gitlabRepoInfo(scheme, host, project string) (GongfengRepoInfo, bool) { + if scheme != "http" { + scheme = "https" + } id := "gitlab:" + host + "/" + project - base := "http://" + host + "/" + project + base := scheme + "://" + host + "/" + project info := GongfengRepoInfo{Project: id, Name: project[strings.LastIndex(project, "/")+1:], WebURL: base, CloneURL: base + ".git"} return info, true } +// GitLabInstanceScheme 从仓库记录的 URL 解析实例 scheme:host[:port] 与 +// "gitlab:/" 标识一致时返回该 URL 的 scheme,否则默认 https。 +// 标识本身不带 scheme,API 调用与 MR 链接统一经此对齐,防止硬编码降级。 +func GitLabInstanceScheme(host string, urls ...string) string { + host = strings.TrimSpace(host) + for _, raw := range urls { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") { + continue + } + if strings.EqualFold(u.Host, host) { + return u.Scheme + } + } + return "https" +} + // isTrustedGitLabHost 限定自托管 GitLab 的可信主机。 // 注意:Go 的 net.IP.IsPrivate() 只认 RFC1918(172.16-31),而公司 GitLab 跑在 // 172.32/172.149/172.153(172.16-31 之外的内网段),因此显式覆盖公司实际网段。 diff --git a/internal/httpapi/assistant_workspace_gitlab_mr_test.go b/internal/httpapi/assistant_workspace_gitlab_mr_test.go new file mode 100644 index 000000000..cfedd450e --- /dev/null +++ b/internal/httpapi/assistant_workspace_gitlab_mr_test.go @@ -0,0 +1,59 @@ +package httpapi + +import ( + "agentflow/internal/domain" + "context" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +// 回归(评审 P1-2):工作区 MR client 遇到 302 时必须拒绝跟随, +// PRIVATE-TOKEN 绝不能被转发到重定向目标。 +func TestCreateGitLabMRRefusesCrossOriginRedirect(t *testing.T) { + var foreignHits int32 + foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("PRIVATE-TOKEN") != "" { + t.Errorf("PRIVATE-TOKEN leaked to redirect target") + } + atomic.AddInt32(&foreignHits, 1) + w.WriteHeader(200) + })) + defer foreign.Close() + origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, foreign.URL+"/hook", http.StatusFound) + })) + defer origin.Close() + if _, err := createGitLabMR(context.Background(), "secret-token", origin.URL, "group/repo", "feat", "main", "T", "D"); err == nil { + t.Fatal("redirect must be rejected, not followed") + } + if n := atomic.LoadInt32(&foreignHits); n != 0 { + t.Fatalf("redirect target was hit %d times", n) + } +} + +// 回归(评审 P1-1):MR 链接的 scheme 按仓库记录的 URL 对齐,默认 https, +// 不再硬编码 http://。 +func TestGitLabRepoPathDerivesSchemeFromRecord(t *testing.T) { + rc := domain.RepositoryContext{ + GongfengProjectID: "gitlab:gitlab.example.test:8443/group/repo", + WebURL: "https://gitlab.example.test:8443/group/repo", + } + base, path := gitlabRepoPath(rc) + if base != "https://gitlab.example.test:8443" || path != "group/repo" { + t.Fatalf("recorded https scheme must be kept, got base=%s path=%s", base, path) + } + rc.WebURL = "" + rc.CloneURL = "http://gitlab.example.test:8443/group/repo.git" + base, _ = gitlabRepoPath(rc) + if base != "http://gitlab.example.test:8443" { + t.Fatalf("explicit http record must be kept, got %s", base) + } + rc.WebURL, rc.CloneURL = "", "" + base, _ = gitlabRepoPath(rc) + if !strings.HasPrefix(base, "https://") { + t.Fatalf("default scheme must be https, got %s", base) + } +} diff --git a/internal/httpapi/assistant_workspace_mr.go b/internal/httpapi/assistant_workspace_mr.go index ff32d7a94..fa12c92b5 100644 --- a/internal/httpapi/assistant_workspace_mr.go +++ b/internal/httpapi/assistant_workspace_mr.go @@ -206,9 +206,9 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSe results = append(results, result) continue } - if host, path := gitlabRepoPath(rc); path != "" { - result.CreateURL = "http://" + host + "/" + path + "/-/merge_requests/new" - mr, err := createGitLabMR(ctx, apiToken, host, path, result.SourceBranch, result.TargetBranch, title, body) + if base, path := gitlabRepoPath(rc); path != "" { + result.CreateURL = base + "/" + path + "/-/merge_requests/new" + mr, err := createGitLabMR(ctx, apiToken, base, path, result.SourceBranch, result.TargetBranch, title, body) if err != nil { result.Error = redactAgentToolResult(err.Error(), requester) } else { @@ -216,7 +216,7 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSe if mr.UpdateError != "" { result.UpdateError = redactAgentToolResult(mr.UpdateError, requester) } - result.MRURL = fmt.Sprintf("http://%s/%s/-/merge_requests/%d", host, path, mr.IID) + result.MRURL = fmt.Sprintf("%s/%s/-/merge_requests/%d", base, path, mr.IID) } results = append(results, result) continue @@ -336,7 +336,8 @@ func hostedRepoPath(rc domain.RepositoryContext, host string, valid *regexp.Rege return "" } -// gitlabRepoPath 从 "gitlab://" 标识取 (host, path); +// gitlabRepoPath 从 "gitlab://" 标识取 (base, path); +// base 是 scheme://host——scheme 按仓库记录的 URL 对齐(默认 https), // 自托管 GitLab 的 MR 直连仓库所在实例的 API。 func gitlabRepoPath(rc domain.RepositoryContext) (string, string) { id := strings.TrimSpace(rc.GongfengProjectID) @@ -352,16 +353,17 @@ func gitlabRepoPath(rc domain.RepositoryContext) (string, string) { if host == "" || path == "" { return "", "" } - return host, path + return domain.GitLabInstanceScheme(host, rc.CloneURL, rc.WebURL) + "://" + host, path } // createGitLabMR 在自托管 GitLab 上开 MR(v4 REST)。分支已有打开的 MR 时 // 返回该 MR 并把标题/描述更新到本次提交的内容(对齐 createGongfengMR 语义)。 -func createGitLabMR(ctx context.Context, token, host, path, source, target, title, description string) (gongfengMR, error) { - client := &http.Client{Timeout: 20 * time.Second} - base := "http://" + host + "/api/v4/projects/" + url.PathEscape(path) +func createGitLabMR(ctx context.Context, token, base, path, source, target, title, description string) (gongfengMR, error) { + // 不跟随重定向:PRIVATE-TOKEN 是凭证,302 到别的 origin 不能携带。 + client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} + apiBase := base + "/api/v4/projects/" + url.PathEscape(path) payload, _ := json.Marshal(map[string]string{"source_branch": source, "target_branch": target, "title": title, "description": description}) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+"/merge_requests", bytes.NewReader(payload)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiBase+"/merge_requests", bytes.NewReader(payload)) if err != nil { return gongfengMR{}, err } @@ -369,7 +371,7 @@ func createGitLabMR(ctx context.Context, token, host, path, source, target, titl req.Header.Set("PRIVATE-TOKEN", token) resp, err := client.Do(req) if err != nil { - return gongfengMR{}, fmt.Errorf("无法连接 GitLab %s:%v", host, err) + return gongfengMR{}, fmt.Errorf("无法连接 GitLab %s:%v", base, err) } raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) resp.Body.Close() @@ -383,12 +385,12 @@ func createGitLabMR(ctx context.Context, token, host, path, source, target, titl return gongfengMR{}, fmt.Errorf("GitLab 返回的 MR 信息无法解析") } // 已有打开 MR:找出来并更新描述。 - open, found := findOpenGitLabMR(ctx, client, token, base, source, target) + open, found := findOpenGitLabMR(ctx, client, token, apiBase, source, target) if !found { return gongfengMR{}, gitlabMRError(resp.StatusCode, raw) } result := gongfengMR{IID: open.IID, Existing: true} - if err := updateGitLabMR(ctx, client, token, base, open.IID, title, description); err != nil { + if err := updateGitLabMR(ctx, client, token, apiBase, open.IID, title, description); err != nil { result.UpdateError = err.Error() } else { result.Updated = true diff --git a/internal/httpapi/catalog_test.go b/internal/httpapi/catalog_test.go index 967ef3048..6061ac0a7 100644 --- a/internal/httpapi/catalog_test.go +++ b/internal/httpapi/catalog_test.go @@ -726,7 +726,7 @@ func TestRepositoryOneLinkSetup(t *testing.T) { if gl.GongfengProjectID != "gitlab:gitlab.example.test/group/repo" || gl.Provider != "gitlab" { t.Fatalf("gitlab prefix id must keep prefix and set provider, got %+v", gl) } - if gl.WebURL != "http://gitlab.example.test/group/repo" || gl.CloneURL != "http://gitlab.example.test/group/repo.git" { + if gl.WebURL != "https://gitlab.example.test/group/repo" || gl.CloneURL != "https://gitlab.example.test/group/repo.git" { t.Fatalf("gitlab urls must derive from the host in id: %+v", gl) } if gl.DefaultBranch != "main" { diff --git a/internal/repo/run_admission.go b/internal/repo/run_admission.go index f9c26976e..8b86fac7a 100644 --- a/internal/repo/run_admission.go +++ b/internal/repo/run_admission.go @@ -3,6 +3,7 @@ package repo import ( "database/sql" "fmt" + "log" "sort" "strings" "time" @@ -359,8 +360,16 @@ func (r *RunsRepo) checkParentAdmission(tx *gorm.DB, run domain.Run) error { func (r *RunsRepo) PromoteQueuedRuns() ([]string, error) { var raw []*string if err := r.DB.Model(&runRow{}).Where("status = ?", "queued").Distinct("quota_bucket").Pluck("quota_bucket", &raw).Error; err != nil { + log.Printf("promote: query buckets failed: %v", err) return nil, err } + vals := make([]string, 0, len(raw)) + for _, b := range raw { + if b != nil { + vals = append(vals, *b) + } + } + log.Printf("promote: queued bucket values=%v", vals) keys := make([]string, 0, len(raw)) for _, key := range raw { if key != nil && *key != "" { @@ -385,19 +394,24 @@ func (r *RunsRepo) promoteBucket(key string) ([]string, error) { err := r.DB.Transaction(func(tx *gorm.DB) error { promoted = nil if err := lockAdmissionGate(r.deps, tx, key); err != nil { + log.Printf("promote: lock gate %s failed: %v", key, err) return err } s := newAdmissionScope(tx) limit, err := s.limit(key) if err != nil { + log.Printf("promote: limit err: %v", err) return err } occupied := 0 if limit > 0 { if occupied, err = s.occupied(key, ""); err != nil { + log.Printf("promote: occupied err: %v", err) return err } + log.Printf("promote: before-gate key=%s limit=%d occupied=%d", key, limit, occupied) if occupied >= limit { + log.Printf("promote: gate full, skipping") return nil } } @@ -406,6 +420,7 @@ func (r *RunsRepo) promoteBucket(key string) ([]string, error) { Order("queue_entered_at, created_at, id").Find(&queued).Error; err != nil { return err } + log.Printf("promote: bucket=%s limit=%d occupied=%d queued_rows=%d", key, limit, occupied, len(queued)) for _, row := range queued { if limit > 0 && occupied >= limit { break diff --git a/internal/tracker/gitlab.go b/internal/tracker/gitlab.go index 86142ac95..86becc3ce 100644 --- a/internal/tracker/gitlab.go +++ b/internal/tracker/gitlab.go @@ -46,6 +46,7 @@ func (s *Service) gitlabClient(project string) (*gitlabClient, error) { return nil, fmt.Errorf("invalid GitLab repository") } var token string + var siteURLs []string if s.projectAuth != nil { for _, repo := range s.projectAuth.Repositories() { if repo.Provider != "gitlab" || repo.GongfengProjectID != project { @@ -56,14 +57,18 @@ func (s *Service) gitlabClient(project string) (*gitlabClient, error) { token = u.GitToken } } + // 实例 scheme 以仓库记录的 URL 为准(https 默认),不在 ID 里硬编码。 + siteURLs = []string{repo.WebURL, repo.CloneURL} break } } return &gitlabClient{ - base: "http://" + host, + base: domain.GitLabInstanceScheme(host, siteURLs...) + "://" + host, project: url.PathEscape(projectPath), token: token, - http: &http.Client{Timeout: 30 * time.Second}, + // 与 GitHub client 一致:不跟随重定向。PRIVATE-TOKEN 是凭证, + // 302 到别的 origin 绝不能把 token 带过去。 + http: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}, }, nil } @@ -163,9 +168,9 @@ func (s *Service) gitlabFindBranch(project, branch string) (domain.DeliveryMR, b return m.delivery(project), true, nil } -// gitlabMergeBranch 找到或创建 source→target 的 MR 并合并(对齐 githubMergeBranch 语义)。 -// 与上游不同:这里只创建/复用 MR,合并交由人工在 GitLab 评审后执行——质量门已保证 -// 测试通过,但团队保留 merge 按钮作为最终把关(dsh-autoflow 也是开 MR 不自动合并)。 +// gitlabMergeBranch 找到或创建 source→target 的 MR 并真正合并(对齐 +// githubMergeBranch 语义):调用 merge 端点后校验返回的 MR 状态必须是 +// merged,否则报错——未合并绝不能返回成功,否则交付会虚进。 func (s *Service) gitlabMergeBranch(project, branch, target, title, description string) (string, error) { if branch == "" { return "", fmt.Errorf("source branch is required") @@ -198,13 +203,22 @@ func (s *Service) gitlabMergeBranch(project, branch, target, title, description "title": title, "description": description, }, &created); err != nil { - // 并发下另一个实例可能已创建:再查一次,复用胜者。 - if m2, ok2, _ := g.findMR(branch, target); ok2 { - return "!" + strconv.Itoa(m2.IID), nil + // 并发下另一个实例可能已创建:再查一次,复用胜者继续走合并。 + rematch, ok2, err2 := g.findMR(branch, target) + if err2 != nil || !ok2 { + return "", err } - return "", err + m = rematch + } else { + m = created } - m = created + } + var merged gitlabMergeRequest + if err := g.request("PUT", "/merge_requests/"+strconv.Itoa(m.IID)+"/merge", map[string]any{"merge_method": "merge"}, &merged); err != nil { + return "", err + } + if merged.State != "merged" { + return "", fmt.Errorf("GitLab did not merge merge request !%d (state %q)", m.IID, merged.State) } return "!" + strconv.Itoa(m.IID), nil } diff --git a/internal/tracker/gitlab_test.go b/internal/tracker/gitlab_test.go new file mode 100644 index 000000000..902c18e08 --- /dev/null +++ b/internal/tracker/gitlab_test.go @@ -0,0 +1,155 @@ +package tracker + +import ( + "agentflow/internal/domain" + "agentflow/internal/repo" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" +) + +// gitLabFixture 起一个本地 GitLab(httptest),注册 owner 凭证与 gitlab: 仓库行。 +// 仓库行的 WebURL 指向测试服务器,因此实例 scheme 为 http(scheme 以记录为准)。 +func gitLabFixture(t *testing.T, handler http.HandlerFunc) (*Service, string) { + t.Helper() + srv := httptest.NewServer(handler) + t.Cleanup(srv.Close) + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + if err := st.PutUser(domain.User{LoginName: "gitlab-owner", GitToken: "gl-private-token"}); err != nil { + t.Fatal(err) + } + u, _ := st.UserByLoginName("gitlab-owner") + if err := st.PutProject(domain.Project{ID: "glproj", Name: "GL", OwnerID: u.ID}); err != nil { + t.Fatal(err) + } + host := strings.TrimPrefix(srv.URL, "http://") + project := "gitlab:" + host + "/group/repo" + if err := st.PutRepository(domain.Repository{ID: "gl-repo", ProjectID: "glproj", Provider: "gitlab", Name: "repo", GongfengProjectID: project, DefaultBranch: "main", WebURL: srv.URL + "/group/repo"}); err != nil { + t.Fatal(err) + } + s := NewService() + s.ConfigureWithStore(domain.SyncConfig{}, st) + return s, project +} + +// 回归:EnsureAndMergeBranchMR 必须真正调用 merge 端点并校验 state=merged, +// 未合并绝不能报成功(评审 P1-3:只建 MR 返回 !7 让交付虚进)。 +func TestGitLabMergeBranchMergesAndVerifies(t *testing.T) { + mergeCalls := 0 + s, project := gitLabFixture(t, func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("PRIVATE-TOKEN") != "gl-private-token" { + t.Errorf("wrong credential: %q", r.Header.Get("PRIVATE-TOKEN")) + } + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/merge_requests"): + _, _ = w.Write([]byte(`[{"iid":7,"state":"opened","source_branch":"feat","target_branch":"main"}]`)) + case r.Method == "PUT" && strings.HasSuffix(r.URL.Path, "/merge_requests/7/merge"): + mergeCalls++ + _, _ = w.Write([]byte(`{"iid":7,"state":"merged","merged_at":"2026-11-11T01:00:00Z"}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(404) + } + }) + ref, err := s.EnsureAndMergeBranchMR(project, "feat", "main", "Title", "") + if err != nil || ref != "!7" { + t.Fatalf("merge: %s %v", ref, err) + } + if mergeCalls != 1 { + t.Fatalf("merge endpoint called %d times, want 1", mergeCalls) + } +} + +// 回归:merge 端点返回非 merged 状态时必须报错(HTTP 成功 ≠ 合并成功)。 +func TestGitLabMergeBranchRejectsUnmergedState(t *testing.T) { + s, project := gitLabFixture(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/merge_requests"): + _, _ = w.Write([]byte(`[{"iid":7,"state":"opened","source_branch":"feat","target_branch":"main"}]`)) + case r.Method == "PUT" && strings.HasSuffix(r.URL.Path, "/merge_requests/7/merge"): + // GitLab 在流水线未过/冲突时返回 405;这里模拟 200 但未合并的病态响应。 + _, _ = w.Write([]byte(`{"iid":7,"state":"opened"}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(404) + } + }) + if _, err := s.EnsureAndMergeBranchMR(project, "feat", "main", "Title", ""); err == nil { + t.Fatal("unmerged state must be reported as an error") + } +} + +// 回归:没有现成 MR 时先创建再合并,全程校验凭证只发给本实例。 +func TestGitLabMergeBranchCreatesThenMerges(t *testing.T) { + s, project := gitLabFixture(t, func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("PRIVATE-TOKEN") != "gl-private-token" { + t.Errorf("wrong credential") + } + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == "GET" && strings.HasSuffix(r.URL.Path, "/merge_requests"): + _, _ = w.Write([]byte(`[]`)) + case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/merge_requests"): + _, _ = w.Write([]byte(`{"iid":9,"state":"opened","source_branch":"feat","target_branch":"main"}`)) + case r.Method == "PUT" && strings.HasSuffix(r.URL.Path, "/merge_requests/9/merge"): + _, _ = w.Write([]byte(`{"iid":9,"state":"merged","merged_at":"2026-11-11T01:00:00Z"}`)) + default: + t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(404) + } + }) + if ref, err := s.EnsureAndMergeBranchMR(project, "feat", "main", "Title", ""); err != nil || ref != "!9" { + t.Fatalf("create+merge: %s %v", ref, err) + } +} + +// 回归(评审 P1-2):实例返回 302 指向第二个 origin 时,客户端必须拒绝跟随, +// PRIVATE-TOKEN 绝不能到达重定向目标。 +func TestGitLabClientRefusesCrossOriginRedirect(t *testing.T) { + var foreignHits int32 + foreign := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("PRIVATE-TOKEN") != "" { + t.Errorf("PRIVATE-TOKEN leaked to redirect target") + } + atomic.AddInt32(&foreignHits, 1) + w.WriteHeader(200) + })) + defer foreign.Close() + s, project := gitLabFixture(t, func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, foreign.URL+"/hook", http.StatusFound) + }) + if _, err := s.EnsureAndMergeBranchMR(project, "feat", "main", "Title", ""); err == nil { + t.Fatal("redirect must be rejected, not followed") + } + if n := atomic.LoadInt32(&foreignHits); n != 0 { + t.Fatalf("redirect target was hit %d times", n) + } +} + +// 回归(评审 P1-1):实例 scheme 以仓库记录的 URL 为准(此处 http), +// 无记录时默认 https——两端都不再硬编码。 +func TestGitLabClientSchemeFollowsRepositoryRecord(t *testing.T) { + s, project := gitLabFixture(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[]`)) + }) + g, err := s.gitlabClient(project) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(g.base, "http://") { + t.Fatalf("recorded http scheme must be used, base=%s", g.base) + } + // 同一 host 但记录里没有匹配 URL 时默认 https。 + if s2 := domain.GitLabInstanceScheme("gitlab.example.test"); s2 != "https" { + t.Fatalf("default scheme = %s, want https", s2) + } +} From fdd146749d5080b172d8ddad21d0bc5c39ea4ac5 Mon Sep 17 00:00:00 2001 From: duyang Date: Wed, 11 Nov 2026 11:34:06 +0800 Subject: [PATCH 04/10] fix(domain): restrict bare-URL GitLab trust to RFC1918 ranges MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit isTrustedGitLabHost matched the entire 172.0.0.0/8 by first octet only, silently treating public ranges in that /8 (172.217.0.0/16 Google, 172.64.0.0/13 Cloudflare, ...) as internal instances for bare http(s) URLs — bypassing the explicit gitlab: prefix that arbitrary hosts are required to use. Drop the 172 wildcard: bare URLs now trust only loopback, RFC1918 (IsPrivate, i.e. 10/8, 172.16/12, 192.168/16) and link-local addresses, plus .internal/.local hostnames. Non-RFC1918 internal deployments use the gitlab: prefix, which remains the admin-declared escape hatch for any host. Adds the requested counter-examples (172.217.0.1, 172.64.1.1 and other public 172.x hosts rejected; bare public 172.x URL rejected; explicit prefix still accepted). --- internal/domain/gitlab_repository_test.go | 13 +++++++++++-- internal/domain/public_repository.go | 18 +++++++----------- internal/httpapi/catalog_test.go | 4 ++-- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/internal/domain/gitlab_repository_test.go b/internal/domain/gitlab_repository_test.go index 3b12ac7ff..e33a5881d 100644 --- a/internal/domain/gitlab_repository_test.go +++ b/internal/domain/gitlab_repository_test.go @@ -80,18 +80,27 @@ func TestParseGitLabRepositoryURLRejectsImpersonation(t *testing.T) { } func TestIsTrustedGitLabHost(t *testing.T) { - // 私有/回环网段与 172.16/12 规划段应受信任(只断言网段类别,不引用真实主机)。 + // 私有/回环网段应受信任(只断言网段类别,不引用真实主机)。 for _, host := range []string{"127.0.0.1", "10.0.0.1", "192.168.0.1", "172.16.0.1", "172.31.255.254"} { if !isTrustedGitLabHost(host) { t.Errorf("internal range host %s should be trusted", host) } } // 公网地址、仿冒主机名、空值不受信任(192.0.2.x/198.51.100.x/203.0.113.x 为文档保留段)。 - for _, host := range []string{"203.0.113.1", "198.51.100.2", "192.0.2.3", "github.com.attacker.example", "gitlab.public.example", ""} { + // 172.0.0.0/8 内 RFC1918 之外的公网段(172.217/16 Google、172.64/13 Cloudflare) + // 必须拒绝:整段放行等于让公网主机冒充内网实例。 + for _, host := range []string{"203.0.113.1", "198.51.100.2", "192.0.2.3", "172.217.0.1", "172.64.1.1", "172.32.0.1", "172.149.0.1", "172.153.0.1", "github.com.attacker.example", "gitlab.public.example", ""} { if isTrustedGitLabHost(host) { t.Errorf("external host %s must not be trusted", host) } } + // 非常规网段走显式 gitlab: 前缀声明(管理员行为,任意主机含公网自建)。 + if got, ok := ParseGitLabRepositoryURL("gitlab:gitlab.self-hosted.example/team/repo"); !ok { + t.Fatalf("explicit prefix must remain the escape hatch for non-RFC1918 instances: %+v", got) + } + if got, ok := ParseGitLabRepositoryURL("http://172.217.0.1/group/repo"); ok { + t.Fatalf("bare public 172.x URL must be rejected without the prefix: %+v", got) + } } func TestParseRepositoryURLKeepsGitHubAndGitLabApart(t *testing.T) { diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.go index 0204c71ba..574efcdf1 100644 --- a/internal/domain/public_repository.go +++ b/internal/domain/public_repository.go @@ -113,22 +113,18 @@ func GitLabInstanceScheme(host string, urls ...string) string { return "https" } -// isTrustedGitLabHost 限定自托管 GitLab 的可信主机。 -// 注意:Go 的 net.IP.IsPrivate() 只认 RFC1918(172.16-31),而公司 GitLab 跑在 -// 172.32/172.149/172.153(172.16-31 之外的内网段),因此显式覆盖公司实际网段。 +// isTrustedGitLabHost 限定自托管 GitLab 的可信主机:裸 URL(无 gitlab: 前缀) +// 只信 RFC1918/回环/链路本地地址与内网命名(.internal/.local)。 +// 172 系只认 RFC1918 的 172.16.0.0/12——172.0.0.0/8 其余大半是公网 +// (如 172.217/16 Google、172.64/13 Cloudflare),整段放行会让公网主机 +// 冒充内网实例,绕过"任意主机需显式 gitlab: 前缀声明"的信任边界。 +// 非常规网段的内网实例请用 gitlab: 前缀显式声明(管理员行为,任意主机)。 func isTrustedGitLabHost(host string) bool { if host == "" { return false } if ip := net.ParseIP(host); ip != nil { - if ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() { - return true - } - // 公司内网使用的非 RFC1918 网段(172.16/12 全段视作内网边界)。 - if ip4 := ip.To4(); ip4 != nil && ip4[0] == 172 { - return true - } - return false + return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() } // 内网主机名(含点但不是公网 TLD 的常见公司命名;运维可在此扩展白名单)。 return strings.Contains(host, ".internal") || strings.HasSuffix(host, ".local") diff --git a/internal/httpapi/catalog_test.go b/internal/httpapi/catalog_test.go index 6061ac0a7..4ce048a64 100644 --- a/internal/httpapi/catalog_test.go +++ b/internal/httpapi/catalog_test.go @@ -734,9 +734,9 @@ func TestRepositoryOneLinkSetup(t *testing.T) { } fromURL := requestJSON[domain.Repository](t, h, http.MethodPost, "/api/repositories", map[string]any{ "projectId": "linkproj", - "repoUrl": "http://172.32.0.10/team/svc.git", + "repoUrl": "http://172.20.0.10/team/svc.git", }, http.StatusOK) - if fromURL.GongfengProjectID != "gitlab:172.32.0.10/team/svc" || fromURL.Provider != "gitlab" { + if fromURL.GongfengProjectID != "gitlab:172.20.0.10/team/svc" || fromURL.Provider != "gitlab" { t.Fatalf("trusted gitlab url must normalize to prefixed id, got %+v", fromURL) } // 裸工蜂路径配 provider=gitlab 必须 400:落库后 MR/同步全按 gitlab: 前缀 From 12ccf145e653785d38ba8e267306b2c383a397e7 Mon Sep 17 00:00:00 2001 From: duyang Date: Thu, 12 Nov 2026 08:41:58 +0800 Subject: [PATCH 05/10] =?UTF-8?q?fix:=20address=20follow-up=20review=20?= =?UTF-8?q?=E2=80=94=20drop=20debug=20logs,=20https=20MR=20links,=20no=20l?= =?UTF-8?q?ink-local=20trust?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. [P2] Remove the unrelated claim/admission debug logging that rode along with this PR (internal/repo/run_admission.go): the promote loop ticks every 2s via StartClaimLoop, so even an idle instance would emit ~43k log lines/day. The whole diff is reverted to base. 2. [P2] GongfengMRURL still hard-coded http:// for gitlab: ids — the last leftover from the original scheme review. It now falls back to https://, consistent with GitLabInstanceScheme; real instances are covered by the web_url from API responses. 3. [non-blocking] isTrustedGitLabHost no longer trusts link-local addresses (169.254.0.0/16): there is no reason to point a GitLab instance at the cloud metadata range; http://169.254.169.254/... is now rejected for bare URLs. Tests: GongfengMRURL https fallback assertion, link-local rejection cases added to TestIsTrustedGitLabHost. --- internal/domain/delivery_mr.go | 6 ++++-- internal/domain/gitlab_repository_test.go | 12 ++++++++++-- internal/domain/public_repository.go | 12 ++++++------ internal/repo/run_admission.go | 15 --------------- 4 files changed, 20 insertions(+), 25 deletions(-) diff --git a/internal/domain/delivery_mr.go b/internal/domain/delivery_mr.go index 0e965b7a5..0a66839cb 100644 --- a/internal/domain/delivery_mr.go +++ b/internal/domain/delivery_mr.go @@ -32,9 +32,11 @@ func GongfengMRURL(project string, iid int) string { return fmt.Sprintf("https://github.com/%s/pull/%d", strings.TrimPrefix(project, "github:"), iid) } if strings.HasPrefix(project, "gitlab:") { - // "gitlab://" → http://///-/merge_requests/ + // "gitlab://" → https://///-/merge_requests/ + // 这里拿不到仓库记录,按安全默认 https(与 GitLabInstanceScheme 一致); + // http 实例以 API 返回的 web_url 为准,覆盖这个兜底值。 rest := strings.TrimPrefix(project, "gitlab:") - return fmt.Sprintf("http://%s/-/merge_requests/%d", rest, iid) + return fmt.Sprintf("https://%s/-/merge_requests/%d", rest, iid) } return fmt.Sprintf("https://git.example.com/%s/-/merge_requests/%d", project, iid) } diff --git a/internal/domain/gitlab_repository_test.go b/internal/domain/gitlab_repository_test.go index e33a5881d..9b58ff7a5 100644 --- a/internal/domain/gitlab_repository_test.go +++ b/internal/domain/gitlab_repository_test.go @@ -88,8 +88,8 @@ func TestIsTrustedGitLabHost(t *testing.T) { } // 公网地址、仿冒主机名、空值不受信任(192.0.2.x/198.51.100.x/203.0.113.x 为文档保留段)。 // 172.0.0.0/8 内 RFC1918 之外的公网段(172.217/16 Google、172.64/13 Cloudflare) - // 必须拒绝:整段放行等于让公网主机冒充内网实例。 - for _, host := range []string{"203.0.113.1", "198.51.100.2", "192.0.2.3", "172.217.0.1", "172.64.1.1", "172.32.0.1", "172.149.0.1", "172.153.0.1", "github.com.attacker.example", "gitlab.public.example", ""} { + // 必须拒绝:整段放行等于让公网主机冒充内网实例。link-local(云元数据端点)同样拒绝。 + for _, host := range []string{"203.0.113.1", "198.51.100.2", "192.0.2.3", "172.217.0.1", "172.64.1.1", "172.32.0.1", "172.149.0.1", "172.153.0.1", "169.254.169.254", "169.254.0.1", "github.com.attacker.example", "gitlab.public.example", ""} { if isTrustedGitLabHost(host) { t.Errorf("external host %s must not be trusted", host) } @@ -116,3 +116,11 @@ func TestParseRepositoryURLKeepsGitHubAndGitLabApart(t *testing.T) { t.Fatalf("impersonation accepted: %+v", got) } } + +// MR 兜底网页链接与解析层同一安全默认:https,不再硬编码 http://。 +// 真实 web_url 由 API 响应覆盖,这里只兜底。 +func TestGongfengMRURLDefaultsToHTTPSForGitLab(t *testing.T) { + if got := GongfengMRURL("gitlab:gitlab.example.test/g/r", 7); got != "https://gitlab.example.test/g/r/-/merge_requests/7" { + t.Fatalf("gitlab MR url = %s, want https fallback", got) + } +} diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.go index 574efcdf1..b8b5d0ec0 100644 --- a/internal/domain/public_repository.go +++ b/internal/domain/public_repository.go @@ -114,17 +114,17 @@ func GitLabInstanceScheme(host string, urls ...string) string { } // isTrustedGitLabHost 限定自托管 GitLab 的可信主机:裸 URL(无 gitlab: 前缀) -// 只信 RFC1918/回环/链路本地地址与内网命名(.internal/.local)。 -// 172 系只认 RFC1918 的 172.16.0.0/12——172.0.0.0/8 其余大半是公网 -// (如 172.217/16 Google、172.64/13 Cloudflare),整段放行会让公网主机 -// 冒充内网实例,绕过"任意主机需显式 gitlab: 前缀声明"的信任边界。 -// 非常规网段的内网实例请用 gitlab: 前缀显式声明(管理员行为,任意主机)。 +// 只信 RFC1918/回环地址与内网命名(.internal/.local)。172 系只认 RFC1918 的 +// 172.16.0.0/12——172.0.0.0/8 其余大半是公网(如 172.217/16 Google、172.64/13 +// Cloudflare),整段放行会让公网主机冒充内网实例。link-local(169.254/16, +// 云元数据端点)同样不放行:没有任何理由把实例指向它。非常规网段的内网 +// 实例请用 gitlab: 前缀显式声明(管理员行为,任意主机)。 func isTrustedGitLabHost(host string) bool { if host == "" { return false } if ip := net.ParseIP(host); ip != nil { - return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() + return ip.IsLoopback() || ip.IsPrivate() } // 内网主机名(含点但不是公网 TLD 的常见公司命名;运维可在此扩展白名单)。 return strings.Contains(host, ".internal") || strings.HasSuffix(host, ".local") diff --git a/internal/repo/run_admission.go b/internal/repo/run_admission.go index 8b86fac7a..f9c26976e 100644 --- a/internal/repo/run_admission.go +++ b/internal/repo/run_admission.go @@ -3,7 +3,6 @@ package repo import ( "database/sql" "fmt" - "log" "sort" "strings" "time" @@ -360,16 +359,8 @@ func (r *RunsRepo) checkParentAdmission(tx *gorm.DB, run domain.Run) error { func (r *RunsRepo) PromoteQueuedRuns() ([]string, error) { var raw []*string if err := r.DB.Model(&runRow{}).Where("status = ?", "queued").Distinct("quota_bucket").Pluck("quota_bucket", &raw).Error; err != nil { - log.Printf("promote: query buckets failed: %v", err) return nil, err } - vals := make([]string, 0, len(raw)) - for _, b := range raw { - if b != nil { - vals = append(vals, *b) - } - } - log.Printf("promote: queued bucket values=%v", vals) keys := make([]string, 0, len(raw)) for _, key := range raw { if key != nil && *key != "" { @@ -394,24 +385,19 @@ func (r *RunsRepo) promoteBucket(key string) ([]string, error) { err := r.DB.Transaction(func(tx *gorm.DB) error { promoted = nil if err := lockAdmissionGate(r.deps, tx, key); err != nil { - log.Printf("promote: lock gate %s failed: %v", key, err) return err } s := newAdmissionScope(tx) limit, err := s.limit(key) if err != nil { - log.Printf("promote: limit err: %v", err) return err } occupied := 0 if limit > 0 { if occupied, err = s.occupied(key, ""); err != nil { - log.Printf("promote: occupied err: %v", err) return err } - log.Printf("promote: before-gate key=%s limit=%d occupied=%d", key, limit, occupied) if occupied >= limit { - log.Printf("promote: gate full, skipping") return nil } } @@ -420,7 +406,6 @@ func (r *RunsRepo) promoteBucket(key string) ([]string, error) { Order("queue_entered_at, created_at, id").Find(&queued).Error; err != nil { return err } - log.Printf("promote: bucket=%s limit=%d occupied=%d queued_rows=%d", key, limit, occupied, len(queued)) for _, row := range queued { if limit > 0 && occupied >= limit { break From cfbd36d8f360fcf43bd011c8c18171549664ad15 Mon Sep 17 00:00:00 2001 From: duyang Date: Thu, 12 Nov 2026 11:29:31 +0800 Subject: [PATCH 06/10] fix(domain): hostname trust must match suffix, not substring MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit isTrustedGitLabHost used strings.Contains(host, ".internal"), so a public attacker domain merely containing the substring — e.g. gitlab.internal.attacker.example — passed the bare-URL trust check, was stored as a gitlab: project, and received members' PRIVATE-TOKEN on sync/MR calls: a token-exfiltration primitive for any project owner via a pasted URL. Match real suffixes only (HasSuffix .internal / .local, mirroring the .local check). Regression test adds gitlab.internal.attacker.example and internal.example.com to the rejected list. --- internal/domain/gitlab_repository_test.go | 4 +++- internal/domain/public_repository.go | 7 +++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/internal/domain/gitlab_repository_test.go b/internal/domain/gitlab_repository_test.go index 9b58ff7a5..46e994da5 100644 --- a/internal/domain/gitlab_repository_test.go +++ b/internal/domain/gitlab_repository_test.go @@ -89,7 +89,9 @@ func TestIsTrustedGitLabHost(t *testing.T) { // 公网地址、仿冒主机名、空值不受信任(192.0.2.x/198.51.100.x/203.0.113.x 为文档保留段)。 // 172.0.0.0/8 内 RFC1918 之外的公网段(172.217/16 Google、172.64/13 Cloudflare) // 必须拒绝:整段放行等于让公网主机冒充内网实例。link-local(云元数据端点)同样拒绝。 - for _, host := range []string{"203.0.113.1", "198.51.100.2", "192.0.2.3", "172.217.0.1", "172.64.1.1", "172.32.0.1", "172.149.0.1", "172.153.0.1", "169.254.169.254", "169.254.0.1", "github.com.attacker.example", "gitlab.public.example", ""} { + // 主机名只认 .internal/.local 后缀:包含 ".internal" 子串的公网攻击域名 + // (gitlab.internal.attacker.example)不是内网主机。 + for _, host := range []string{"203.0.113.1", "198.51.100.2", "192.0.2.3", "172.217.0.1", "172.64.1.1", "172.32.0.1", "172.149.0.1", "172.153.0.1", "169.254.169.254", "169.254.0.1", "gitlab.internal.attacker.example", "internal.example.com", "github.com.attacker.example", "gitlab.public.example", ""} { if isTrustedGitLabHost(host) { t.Errorf("external host %s must not be trusted", host) } diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.go index b8b5d0ec0..bb17ddd61 100644 --- a/internal/domain/public_repository.go +++ b/internal/domain/public_repository.go @@ -126,8 +126,11 @@ func isTrustedGitLabHost(host string) bool { if ip := net.ParseIP(host); ip != nil { return ip.IsLoopback() || ip.IsPrivate() } - // 内网主机名(含点但不是公网 TLD 的常见公司命名;运维可在此扩展白名单)。 - return strings.Contains(host, ".internal") || strings.HasSuffix(host, ".local") + // 内网主机名:只认 .internal/.local 结尾的后缀。绝不能用子串匹配 + // (Contains)——gitlab.internal.attacker.example 这类公网攻击域名 + // 包含 ".internal" 子串,会被当成内网实例,成员 token 随 PRIVATE-TOKEN + // 发到攻击者主机。运维可在此扩展精确后缀白名单。 + return strings.HasSuffix(host, ".internal") || strings.HasSuffix(host, ".local") } // ParseRepositoryURL adds public hosting without changing the upstream adapter. From fe3c3523e972b6e34b75eec2d85901d14d06a443 Mon Sep 17 00:00:00 2001 From: duyang Date: Mon, 16 Nov 2026 09:10:18 +0800 Subject: [PATCH 07/10] chore: drop internal project reference from code comment Reviewer note (#2): the PRIVATE-TOKEN comment mentioned an internal project name; replaced with the neutral statement. --- internal/tracker/gitlab.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/tracker/gitlab.go b/internal/tracker/gitlab.go index 86becc3ce..7019f5095 100644 --- a/internal/tracker/gitlab.go +++ b/internal/tracker/gitlab.go @@ -87,7 +87,7 @@ func (g *gitlabClient) request(method, suffix string, input, output any) error { } r.Header.Set("Accept", "application/json") r.Header.Set("Content-Type", "application/json") - // 自托管 GitLab 接受 PRIVATE-TOKEN(我们在 dsh-autoflow 中验证过)。 + // 自托管 GitLab(CE/EE)以 PRIVATE-TOKEN 头认证(v4 REST 标准方式)。 if g.token != "" { r.Header.Set("PRIVATE-TOKEN", g.token) } From 1211522a02b6dad5a1ac506b86afbe158ddc7713 Mon Sep 17 00:00:00 2001 From: duyang Date: Tue, 17 Nov 2026 20:45:18 +0800 Subject: [PATCH 08/10] fix(gitlab): only send credentials to admin-declared instances MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `gitlab:` 前缀只说明"这是 GitLab",不代表 host 可信:任何能写 POST /api/repositories 的项目成员都能绑定任意 host,随后 MR 同步会把 owner 的 Git 令牌当 PRIVATE-TOKEN 发到该 host(评审阻塞项)。 新增 AGENTFLOW_GITLAB_ALLOWED_HOSTS(逗号分隔 host[:port],可带 scheme)作为凭据信任边界:绑定入口与 tracker / 工作区 MR 客户端双重 校验,未声明的实例直接拒绝且不发任何认证头;公网、内网、回环地址 一视同仁——内网也能起一个服务收走令牌。未配置用户令牌时不再发送 空 PRIVATE-TOKEN 头(空头同样是一次凭证提交)。 测试:allowlist 归一化与端口匹配、catalog 绑定拦截(公网/内网/裸 URL)、tracker 拒绝未声明实例、工作区 MR 拒绝未声明实例、无凭据时 不带认证头。 --- docs/deployment.md | 4 + internal/domain/gitlab_allowlist.go | 87 +++++++++++++++++++ internal/domain/gitlab_allowlist_test.go | 53 +++++++++++ .../assistant_workspace_gitlab_mr_test.go | 34 ++++++++ internal/httpapi/assistant_workspace_mr.go | 22 ++++- internal/httpapi/catalog.go | 16 ++++ internal/httpapi/catalog_test.go | 50 +++++++++++ internal/tracker/gitlab.go | 9 ++ internal/tracker/gitlab_test.go | 50 ++++++++++- 9 files changed, 321 insertions(+), 4 deletions(-) create mode 100644 internal/domain/gitlab_allowlist.go create mode 100644 internal/domain/gitlab_allowlist_test.go diff --git a/docs/deployment.md b/docs/deployment.md index e50aea6f4..5341e6f0c 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -104,6 +104,10 @@ Use Git SSH for GitLab.com, self-managed GitLab, Gitea, Gogs, GitHub, and other Repositories automatically use the current user's key for their SSH host and port; repositories on the same host and port share that key. The repository form only shows a red warning when that host has no personal key. This reminder does not block saving the repository or completing setup; credentials and host trust can be configured before the first Git operation. There is no repository-specific or default fallback key. Checkout and SOP execution use the responsible user's keys. Conversation submission and the workspace terminal use the requesting user's keys. The temporary signing agent closes when the command or terminal ends. A terminal's agent never lives in the shared workspace: with the `bwrap` driver it sits in a private directory bound only into that terminal, and with the `local` driver (no isolation) it stays outside the workspace in a 0700 directory. Docker and seatbelt workspaces share one filesystem view among all their processes, so their terminals get no personal SSH key; push from there with the platform's submit action. `git@github.com:` and `ssh://git@github.com/` addresses are saved as GitHub repositories (HTTPS + token, automatic pull requests) unless `provider` is explicitly `ssh`. To rotate a key, replace it in settings and revoke the old public key at the host. +### Self-hosted GitLab over HTTPS + +Self-hosted GitLab MR delivery is opt-in per instance. Set `AGENTFLOW_GITLAB_ALLOWED_HOSTS` to a comma-separated list of instances, each as `host` or `host:port`; an `https://` prefix, a trailing slash and letter case are normalized away. For example: `gitlab.example.com,gitlab.internal:8443`. Only listed hosts can be bound as `gitlab://` repositories, and the owning or requesting user's Git token is sent to them as `PRIVATE-TOKEN` for MR create/merge and status sync. Unlisted hosts are rejected when a repository is saved, and the platform refuses to send any credential to them; loopback and RFC1918 addresses are not exempt, because a service on an internal address can capture the token too. An empty or unset list disables GitLab repository bindings. The list is read per request, so an edit takes effect without a restart; declare the instance before users bind repositories. + SSH handles clone, fetch and push. A conversation delivery returns the branch and commit SHA. You can optionally add a repository web URL to open the host and create a PR/MR manually. Issue import and PR/MR automation need a hosting API credential. To automate those actions, add a hosting-specific MCP in **Settings → Assets → MCP**, give it its own scoped token, and attach it to the relevant agent or workflow. [CNB does not support Git SSH](https://docs.cnb.cool/en/guide/git-access.html); it uses HTTPS with a CNB access token, which is outside this integration. ## Accounts diff --git a/internal/domain/gitlab_allowlist.go b/internal/domain/gitlab_allowlist.go new file mode 100644 index 000000000..94a1f09da --- /dev/null +++ b/internal/domain/gitlab_allowlist.go @@ -0,0 +1,87 @@ +package domain + +import ( + "net" + "os" + "strings" +) + +// GitLabAllowedHostsEnv 声明本部署允许接入的自托管 GitLab 实例:逗号分隔, +// 每项为 host 或 host:port,可带 http(s):// 前缀(归一化时去掉)。 +// +// 它是凭据的信任边界而不是可选项:PRIVATE-TOKEN 只会发往这里声明的实例。 +// 未声明时一律拒绝,包括回环与内网地址——项目成员可以在任意内网地址上起 +// 一个服务,若按"内网即可信"放行,owner 的 Git 令牌仍会被送过去。运维在 +// 部署配置里显式声明实例,才把该实例纳入凭据可达范围。 +const GitLabAllowedHostsEnv = "AGENTFLOW_GITLAB_ALLOWED_HOSTS" + +// GitLabAllowedHosts 返回归一化后的实例 allowlist(小写、去 scheme/斜杠)。 +func GitLabAllowedHosts() []string { + raw := os.Getenv(GitLabAllowedHostsEnv) + if strings.TrimSpace(raw) == "" { + return nil + } + entries := []string{} + for _, item := range strings.Split(raw, ",") { + if entry := normalizeGitLabHost(item); entry != "" { + entries = append(entries, entry) + } + } + return entries +} + +// GitLabHostAllowed 报告 host[:port] 是否是管理员显式声明的 GitLab 实例。 +// 带端口的条目光精确匹配 host:port;只写 host 的条目匹配该 host 的任意端口。 +func GitLabHostAllowed(host string) bool { + target := normalizeGitLabHost(host) + if target == "" { + return false + } + targetHost, _ := splitGitLabHostPort(target) + for _, entry := range GitLabAllowedHosts() { + if entry == target { + return true + } + entryHost, entryHasPort := splitGitLabHostPort(entry) + // 显式写了端口的条目只匹配同一端口(上面的精确比较已覆盖), + // 不再按 host 放宽。 + if !entryHasPort && entryHost == targetHost { + return true + } + } + return false +} + +// GitLabInstanceHost 从 "gitlab://" 标识取 host。 +func GitLabInstanceHost(id string) (string, bool) { + rest, found := strings.CutPrefix(strings.TrimSpace(id), "gitlab:") + if !found { + return "", false + } + slash := strings.Index(rest, "/") + if slash <= 0 { + return "", false + } + return rest[:slash], true +} + +// normalizeGitLabHost 归一化 allowlist 条目与待匹配 host:去空白、去 +// http(s):// 前缀与结尾斜杠、转小写。 +func normalizeGitLabHost(raw string) string { + host := strings.ToLower(strings.TrimSpace(raw)) + host = strings.TrimPrefix(host, "https://") + host = strings.TrimPrefix(host, "http://") + return strings.TrimSuffix(host, "/") +} + +// splitGitLabHostPort 拆出 host 与"是否显式带端口"。解析失败(如 IPv6 字面量 +// 未加方括号)时按无端口处理,由精确比较兜底。 +func splitGitLabHostPort(hostport string) (string, bool) { + if host, _, err := net.SplitHostPort(hostport); err == nil { + return host, true + } + if strings.HasPrefix(hostport, "[") && strings.HasSuffix(hostport, "]") { + return strings.Trim(hostport, "[]"), false + } + return hostport, false +} diff --git a/internal/domain/gitlab_allowlist_test.go b/internal/domain/gitlab_allowlist_test.go new file mode 100644 index 000000000..762e83cf5 --- /dev/null +++ b/internal/domain/gitlab_allowlist_test.go @@ -0,0 +1,53 @@ +package domain + +import "testing" + +// 回归(评审阻塞项):token 只能发往管理员显式声明的 GitLab 实例。 +// 未配置白名单时任何主机(含回环/内网)都不得放行,避免成员绑定 +// gitlab:<任意 host> 后把 owner 的 Git 令牌当 PRIVATE-TOKEN 发出去。 +func TestGitLabHostAllowedRequiresExplicitAllowlist(t *testing.T) { + t.Setenv(GitLabAllowedHostsEnv, "") + for _, host := range []string{ + "gitlab.example.test", + "gitlab.example.test:8443", + "127.0.0.1:8080", + "10.1.2.3", + "gitlab.corp.internal", + } { + if GitLabHostAllowed(host) { + t.Fatalf("host %q must be rejected without an admin allowlist", host) + } + } +} + +func TestGitLabHostAllowedMatchesConfiguredInstances(t *testing.T) { + t.Setenv(GitLabAllowedHostsEnv, " https://GitLab.Example.Test , gitlab.port.test:8443 ,,") + cases := map[string]bool{ + "gitlab.example.test": true, // scheme 前缀与大小写都归一化 + "GitLab.Example.Test": true, // host 匹配大小写不敏感 + "gitlab.example.test:8443": true, // 只写 host 的条目匹配任意端口 + "gitlab.port.test:8443": true, // 带端口的条目精确匹配 + "gitlab.port.test": false, // 条目已钉死端口 + "gitlab.port.test:9443": false, + "sub.gitlab.example.test": false, // 不做通配/子串匹配 + "gitlab.attacker.example": false, + "": false, + } + for host, want := range cases { + if got := GitLabHostAllowed(host); got != want { + t.Fatalf("GitLabHostAllowed(%q) = %v, want %v", host, got, want) + } + } +} + +func TestGitLabInstanceHostParsesPrefixedID(t *testing.T) { + host, ok := GitLabInstanceHost("gitlab:gitlab.example.test:8443/group/repo") + if !ok || host != "gitlab.example.test:8443" { + t.Fatalf("host = %q ok = %v, want gitlab.example.test:8443", host, ok) + } + for _, bad := range []string{"", "gitlab:", "gitlab:/group/repo", "gitlab:host", "group/repo"} { + if _, ok := GitLabInstanceHost(bad); ok { + t.Fatalf("GitLabInstanceHost(%q) must fail", bad) + } + } +} diff --git a/internal/httpapi/assistant_workspace_gitlab_mr_test.go b/internal/httpapi/assistant_workspace_gitlab_mr_test.go index cfedd450e..ee2ddc24b 100644 --- a/internal/httpapi/assistant_workspace_gitlab_mr_test.go +++ b/internal/httpapi/assistant_workspace_gitlab_mr_test.go @@ -26,6 +26,8 @@ func TestCreateGitLabMRRefusesCrossOriginRedirect(t *testing.T) { http.Redirect(w, r, foreign.URL+"/hook", http.StatusFound) })) defer origin.Close() + // 实例必须由管理员显式声明:凭据只会发往 allowlist 内的 host。 + t.Setenv(domain.GitLabAllowedHostsEnv, strings.TrimPrefix(origin.URL, "http://")) if _, err := createGitLabMR(context.Background(), "secret-token", origin.URL, "group/repo", "feat", "main", "T", "D"); err == nil { t.Fatal("redirect must be rejected, not followed") } @@ -34,6 +36,38 @@ func TestCreateGitLabMRRefusesCrossOriginRedirect(t *testing.T) { } } +// 回归(评审阻塞项):未在管理员 allowlist 中的 GitLab 实例,工作区 MR +// 客户端必须在发请求前就拒绝,绝不能把发起人 token 带过去。 +func TestCreateGitLabMRRejectsUnlistedInstance(t *testing.T) { + t.Setenv(domain.GitLabAllowedHostsEnv, "") + _, err := createGitLabMR(context.Background(), "secret-token", "https://gitlab.attacker.example", "group/repo", "feat", "main", "T", "D") + if err == nil || !strings.Contains(err.Error(), domain.GitLabAllowedHostsEnv) { + t.Fatalf("unlisted instance must be rejected with an actionable error, got %v", err) + } +} + +// 未配置该实例凭据时,请求里不能出现 PRIVATE-TOKEN 头(空值也不行)。 +func TestCreateGitLabMROmitsTokenWithoutCredential(t *testing.T) { + var tokenHeaders int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if n := len(r.Header.Values("PRIVATE-TOKEN")); n > 0 { + atomic.AddInt32(&tokenHeaders, int32(n)) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"iid":4}`)) + })) + defer srv.Close() + t.Setenv(domain.GitLabAllowedHostsEnv, strings.TrimPrefix(srv.URL, "http://")) + mr, err := createGitLabMR(context.Background(), "", srv.URL, "group/repo", "feat", "main", "T", "D") + if err != nil || mr.IID != 4 { + t.Fatalf("MR = %+v err = %v", mr, err) + } + if n := atomic.LoadInt32(&tokenHeaders); n != 0 { + t.Fatalf("PRIVATE-TOKEN must not be sent without a credential, saw %d", n) + } +} + // 回归(评审 P1-1):MR 链接的 scheme 按仓库记录的 URL 对齐,默认 https, // 不再硬编码 http://。 func TestGitLabRepoPathDerivesSchemeFromRecord(t *testing.T) { diff --git a/internal/httpapi/assistant_workspace_mr.go b/internal/httpapi/assistant_workspace_mr.go index 3fc861403..c8e6d1f86 100644 --- a/internal/httpapi/assistant_workspace_mr.go +++ b/internal/httpapi/assistant_workspace_mr.go @@ -379,6 +379,15 @@ func gitlabRepoPath(rc domain.RepositoryContext) (string, string) { // createGitLabMR 在自托管 GitLab 上开 MR(v4 REST)。分支已有打开的 MR 时 // 返回该 MR 并把标题/描述更新到本次提交的内容(对齐 createGongfengMR 语义)。 func createGitLabMR(ctx context.Context, token, base, path, source, target, title, description string) (gongfengMR, error) { + // 实例必须由管理员显式声明:任何 host 都能由仓库标识推导出来,若不在 + // allowlist 内,连请求都不发(PRIVATE-TOKEN 是发起人的 Git 令牌)。 + u, err := url.Parse(base) + if err != nil || u.Host == "" { + return gongfengMR{}, fmt.Errorf("无效的 GitLab 地址 %q", base) + } + if !domain.GitLabHostAllowed(u.Host) { + return gongfengMR{}, fmt.Errorf("GitLab 实例 %s 未在管理员允许列表(%s)中:已拒绝发送凭据", u.Host, domain.GitLabAllowedHostsEnv) + } // 不跟随重定向:PRIVATE-TOKEN 是凭证,302 到别的 origin 不能携带。 client := &http.Client{Timeout: 20 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} apiBase := base + "/api/v4/projects/" + url.PathEscape(path) @@ -388,7 +397,10 @@ func createGitLabMR(ctx context.Context, token, base, path, source, target, titl return gongfengMR{}, err } req.Header.Set("Content-Type", "application/json") - req.Header.Set("PRIVATE-TOKEN", token) + // 没有该实例的凭据就不发认证头(空头也会被服务端当成一次凭证提交)。 + if token != "" { + req.Header.Set("PRIVATE-TOKEN", token) + } resp, err := client.Do(req) if err != nil { return gongfengMR{}, fmt.Errorf("无法连接 GitLab %s:%v", base, err) @@ -423,7 +435,9 @@ func findOpenGitLabMR(ctx context.Context, client *http.Client, token, base, sou if err != nil { return gongfengOpenMR{}, false } - req.Header.Set("PRIVATE-TOKEN", token) + if token != "" { + req.Header.Set("PRIVATE-TOKEN", token) + } resp, err := client.Do(req) if err != nil { return gongfengOpenMR{}, false @@ -448,7 +462,9 @@ func updateGitLabMR(ctx context.Context, client *http.Client, token, base string return err } req.Header.Set("Content-Type", "application/json") - req.Header.Set("PRIVATE-TOKEN", token) + if token != "" { + req.Header.Set("PRIVATE-TOKEN", token) + } resp, err := client.Do(req) if err != nil { return err diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index 4fc15a2b8..6f07780f7 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -250,6 +250,22 @@ func (h *catalogHandlers) repositories(c *gin.Context) { c.JSON(400, map[string]string{"error": "GitLab 仓库请使用 gitlab:// 标识,或粘贴完整的 GitLab 仓库地址"}) return } + // 能写 POST /api/repositories 的成员很多,而 gitlab: 前缀本身只说明 + // "这是 GitLab",不代表该 host 可信。实例必须由管理员在部署配置里显式 + // 声明(allowlist),否则后续 MR/同步会把 owner 的 Git 令牌当 + // PRIVATE-TOKEN 发到该 host。公网与内网/回环地址一视同仁——内网也能起 + // 一个服务把令牌收走。这里在入口拒绝,tracker 侧再兜底。 + if v.Provider == "gitlab" { + host, ok := domain.GitLabInstanceHost(v.GongfengProjectID) + if !ok { + c.JSON(400, map[string]string{"error": "GitLab 仓库标识无效:请使用 gitlab://"}) + return + } + if !domain.GitLabHostAllowed(host) { + c.JSON(400, map[string]string{"error": fmt.Sprintf("GitLab 实例 %s 未在管理员允许列表(%s)中:请由管理员在部署配置中声明该实例后再绑定", host, domain.GitLabAllowedHostsEnv)}) + return + } + } if v.DefaultBranch == "" { v.DefaultBranch = "master" } diff --git a/internal/httpapi/catalog_test.go b/internal/httpapi/catalog_test.go index 9e0eb6550..41b260ee2 100644 --- a/internal/httpapi/catalog_test.go +++ b/internal/httpapi/catalog_test.go @@ -732,6 +732,8 @@ func TestRepositoryOneLinkSetup(t *testing.T) { // 自托管 GitLab:gitlab: 前缀标识(host 进 ID,多实例靠 host 区分)与 // 可信内网 URL 都归一为前缀标识,provider=gitlab,默认分支 main。 + // 实例须由管理员在 allowlist 中声明,这里显式给出两个测试实例。 + t.Setenv(domain.GitLabAllowedHostsEnv, "gitlab.example.test,172.20.0.10") gl := requestJSON[domain.Repository](t, h, http.MethodPost, "/api/repositories", map[string]any{ "projectId": "linkproj", "gongfengProjectId": "gitlab:gitlab.example.test/group/repo", @@ -764,6 +766,54 @@ func TestRepositoryOneLinkSetup(t *testing.T) { } } +// 回归(评审阻塞项):GitLab 实例必须由管理员显式声明(部署配置 +// AGENTFLOW_GITLAB_ALLOWED_HOSTS)。项目成员能写 POST /api/repositories, +// 若放行任意 gitlab:,后续 MR 同步会把 owner 的 Git token 当 +// PRIVATE-TOKEN 发到该 host——公网主机与内网/回环地址同样危险。 +func TestRepositoryGitLabBindingRequiresAllowlistedHost(t *testing.T) { + t.Setenv(domain.GitLabAllowedHostsEnv, "") + s, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + h := New(s, engine.New(s, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") + requestJSON[domain.Project](t, h, http.MethodPost, "/api/projects", domain.Project{ID: "allowproj", Key: "ALLOW", Name: "Allow"}, http.StatusOK) + + for _, id := range []string{ + "gitlab:gitlab.attacker.example/group/repo", + "gitlab:127.0.0.1:8080/group/repo", + } { + resp := requestJSON[map[string]string](t, h, http.MethodPost, "/api/repositories", map[string]any{ + "projectId": "allowproj", + "gongfengProjectId": id, + }, http.StatusBadRequest) + if !strings.Contains(resp["error"], domain.GitLabAllowedHostsEnv) { + t.Fatalf("error for %q = %q, want it to name %s", id, resp["error"], domain.GitLabAllowedHostsEnv) + } + } + + // 粘贴内网 URL 同样不能绕过:归一成 gitlab: 标识后仍走 allowlist + // (内网地址也能起服务收 token)。 + resp := requestJSON[map[string]string](t, h, http.MethodPost, "/api/repositories", map[string]any{ + "projectId": "allowproj", + "repoUrl": "http://172.20.0.10/team/svc.git", + }, http.StatusBadRequest) + if !strings.Contains(resp["error"], domain.GitLabAllowedHostsEnv) { + t.Fatalf("bare internal URL error = %q, want it to name %s", resp["error"], domain.GitLabAllowedHostsEnv) + } + + // 管理员声明后即可绑定,标识保持 gitlab: 前缀形式。 + t.Setenv(domain.GitLabAllowedHostsEnv, "gitlab.attacker.example") + created := requestJSON[domain.Repository](t, h, http.MethodPost, "/api/repositories", map[string]any{ + "projectId": "allowproj", + "gongfengProjectId": "gitlab:gitlab.attacker.example/group/repo", + }, http.StatusOK) + if created.Provider != "gitlab" || created.GongfengProjectID != "gitlab:gitlab.attacker.example/group/repo" { + t.Fatalf("declared instance must bind as a gitlab repo, got %+v", created) + } +} + func TestGlobalRuleWorkflowBinding(t *testing.T) { s, err := repo.OpenTest() if err != nil { diff --git a/internal/tracker/gitlab.go b/internal/tracker/gitlab.go index 7019f5095..3ade0d24d 100644 --- a/internal/tracker/gitlab.go +++ b/internal/tracker/gitlab.go @@ -45,6 +45,15 @@ func (s *Service) gitlabClient(project string) (*gitlabClient, error) { if !ok { return nil, fmt.Errorf("invalid GitLab repository") } + // 凭据只发往管理员显式声明的实例(AGENTFLOW_GITLAB_ALLOWED_HOSTS)。 + // 成员只要能写 POST /api/repositories 就能绑定任意 gitlab:,若按 + // "前缀即管理员声明"放行,owner 的 Git 令牌会被当 PRIVATE-TOKEN 发到 + // 攻击者主机。这里与绑定入口双重拦截,失败即拒绝构造客户端、不携带任何 + // 凭据;反过来,声明实例也即管理员确认"该实例可以使用部署的 Git 令牌", + // 未声明则绝不下发。 + if !domain.GitLabHostAllowed(host) { + return nil, fmt.Errorf("GitLab 实例 %s 未在管理员允许列表(%s)中:已拒绝发送凭据,请让管理员在部署配置中声明该实例", host, domain.GitLabAllowedHostsEnv) + } var token string var siteURLs []string if s.projectAuth != nil { diff --git a/internal/tracker/gitlab_test.go b/internal/tracker/gitlab_test.go index 902c18e08..124b32aa3 100644 --- a/internal/tracker/gitlab_test.go +++ b/internal/tracker/gitlab_test.go @@ -12,7 +12,13 @@ import ( // gitLabFixture 起一个本地 GitLab(httptest),注册 owner 凭证与 gitlab: 仓库行。 // 仓库行的 WebURL 指向测试服务器,因此实例 scheme 为 http(scheme 以记录为准)。 +// 实例 host 写进管理员 allowlist:凭据只允许发往显式声明的实例。 func gitLabFixture(t *testing.T, handler http.HandlerFunc) (*Service, string) { + t.Helper() + return gitLabFixtureWithToken(t, handler, "gl-private-token") +} + +func gitLabFixtureWithToken(t *testing.T, handler http.HandlerFunc, token string) (*Service, string) { t.Helper() srv := httptest.NewServer(handler) t.Cleanup(srv.Close) @@ -21,7 +27,7 @@ func gitLabFixture(t *testing.T, handler http.HandlerFunc) (*Service, string) { t.Fatal(err) } t.Cleanup(st.Close) - if err := st.PutUser(domain.User{LoginName: "gitlab-owner", GitToken: "gl-private-token"}); err != nil { + if err := st.PutUser(domain.User{LoginName: "gitlab-owner", GitToken: token}); err != nil { t.Fatal(err) } u, _ := st.UserByLoginName("gitlab-owner") @@ -29,6 +35,7 @@ func gitLabFixture(t *testing.T, handler http.HandlerFunc) (*Service, string) { t.Fatal(err) } host := strings.TrimPrefix(srv.URL, "http://") + t.Setenv(domain.GitLabAllowedHostsEnv, host) project := "gitlab:" + host + "/group/repo" if err := st.PutRepository(domain.Repository{ID: "gl-repo", ProjectID: "glproj", Provider: "gitlab", Name: "repo", GongfengProjectID: project, DefaultBranch: "main", WebURL: srv.URL + "/group/repo"}); err != nil { t.Fatal(err) @@ -38,6 +45,47 @@ func gitLabFixture(t *testing.T, handler http.HandlerFunc) (*Service, string) { return s, project } +// 回归(评审阻塞项):实例未在管理员 allowlist 中时,连客户端都不能建, +// 更不能带着 owner 的 Git 令牌发请求。 +func TestGitLabClientRejectsInstanceOutsideAllowlist(t *testing.T) { + t.Setenv(domain.GitLabAllowedHostsEnv, "") + if _, err := NewService().gitlabClient("gitlab:gitlab.attacker.example/group/repo"); err == nil || + !strings.Contains(err.Error(), domain.GitLabAllowedHostsEnv) { + t.Fatalf("unlisted GitLab instance must be rejected with an actionable error, got %v", err) + } +} + +// 声明过的公网实例可以建客户端;没有用户令牌时不注入任何凭证。 +func TestGitLabClientAllowsDeclaredInstanceWithoutToken(t *testing.T) { + t.Setenv(domain.GitLabAllowedHostsEnv, "gitlab.example.test") + g, err := NewService().gitlabClient("gitlab:gitlab.example.test/group/repo") + if err != nil { + t.Fatalf("declared instance must be accepted: %v", err) + } + if g.base != "https://gitlab.example.test" || g.token != "" { + t.Fatalf("base = %q token = %q, want https base and no token", g.base, g.token) + } +} + +// 未配置用户 Git 令牌时,请求里不能出现 PRIVATE-TOKEN 头。 +func TestGitLabFindBranchOmitsTokenWithoutCredential(t *testing.T) { + var tokenHeaders int32 + s, project := gitLabFixtureWithToken(t, func(w http.ResponseWriter, r *http.Request) { + if n := len(r.Header.Values("PRIVATE-TOKEN")); n > 0 { + atomic.AddInt32(&tokenHeaders, int32(n)) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[{"iid":3,"state":"merged","source_branch":"feat","target_branch":"main"}]`)) + }, "") + mr, ok, err := s.gitlabFindBranch(project, "feat") + if err != nil || !ok || mr.IID != 3 { + t.Fatalf("find branch = %+v ok=%v err=%v", mr, ok, err) + } + if n := atomic.LoadInt32(&tokenHeaders); n != 0 { + t.Fatalf("PRIVATE-TOKEN must not be sent without a user credential, saw %d", n) + } +} + // 回归:EnsureAndMergeBranchMR 必须真正调用 merge 端点并校验 state=merged, // 未合并绝不能报成功(评审 P1-3:只建 MR 返回 !7 让交付虚进)。 func TestGitLabMergeBranchMergesAndVerifies(t *testing.T) { From 8227571ef692f26792fb78b63c261a2a369d83e5 Mon Sep 17 00:00:00 2001 From: duyang Date: Wed, 18 Nov 2026 09:08:59 +0800 Subject: [PATCH 09/10] feat(workspaces): register GitLab MRs opened by the agent as turn deliveries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main 的 #947 改成 agent 自己 push + 开 PR、平台在 turn 结束后检测 GitHub PR 登记交付;GitLab 没有等价检测,对话里的 GitLab 交付不会登记。 - 枚举工作区远端,按已绑定仓库记录映射到 gitlab: 项目(https/ssh/scp、 .git 后缀、带 token 的 URL 都归一),只查询管理员声明过的实例; - 复用 GitLab v4 API(scope=created_by_me),按 head commit 仍在工作区、 创建时间不早于 workspace 过滤 open/merged MR; - GitHub PR 与 GitLab MR 统一走 turnDelivery,未登记才登记;deliveredMR 直接携带 project/iid(GitLab MR URL 不在 Gongfeng 解析规则内); - 登记后由现有 MR 状态同步按 gitlab: 前缀刷新状态。 测试:head/时间/状态过滤、未声明实例不发请求不发凭据、无凭据不发 PRIVATE-TOKEN、远端形态归一化、直接 project/iid 登记到需求。 --- docs/deployment.md | 2 +- .../httpapi/assistant_conversation_issue.go | 10 +- .../httpapi/assistant_workspace_gitlab_mr.go | 229 ++++++++++++++++++ .../assistant_workspace_gitlab_mr_test.go | 171 +++++++++++++ internal/httpapi/assistant_workspace_mr.go | 78 +++--- 5 files changed, 461 insertions(+), 29 deletions(-) create mode 100644 internal/httpapi/assistant_workspace_gitlab_mr.go create mode 100644 internal/httpapi/assistant_workspace_gitlab_mr_test.go diff --git a/docs/deployment.md b/docs/deployment.md index b0516dbe1..04a2f3723 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -106,7 +106,7 @@ Repositories automatically use the current user's key for their SSH host and por ### Self-hosted GitLab over HTTPS -Self-hosted GitLab MR delivery is opt-in per instance. Set `AGENTFLOW_GITLAB_ALLOWED_HOSTS` to a comma-separated list of instances, each as `host` or `host:port`; an `https://` prefix, a trailing slash and letter case are normalized away. For example: `gitlab.example.com,gitlab.internal:8443`. Only listed hosts can be bound as `gitlab://` repositories, and the owning or requesting user's Git token is sent to them as `PRIVATE-TOKEN` for MR create/merge and status sync. Unlisted hosts are rejected when a repository is saved, and the platform refuses to send any credential to them; loopback and RFC1918 addresses are not exempt, because a service on an internal address can capture the token too. An empty or unset list disables GitLab repository bindings. The list is read per request, so an edit takes effect without a restart; declare the instance before users bind repositories. +Self-hosted GitLab MR delivery is opt-in per instance. Set `AGENTFLOW_GITLAB_ALLOWED_HOSTS` to a comma-separated list of instances, each as `host` or `host:port`; an `https://` prefix, a trailing slash and letter case are normalized away. For example: `gitlab.example.com,gitlab.internal:8443`. Only listed hosts can be bound as `gitlab://` repositories, and the owning or requesting user's Git token is sent to them as `PRIVATE-TOKEN` for MR create/merge and status sync. Unlisted hosts are rejected when a repository is saved, and the platform refuses to send any credential to them; loopback and RFC1918 addresses are not exempt, because a service on an internal address can capture the token too. An empty or unset list disables GitLab repository bindings. The list is read per request, so an edit takes effect without a restart; declare the instance before users bind repositories. When a turn ends, merge requests the agent opened on a declared instance (authored by the speaking user, head commit still in the workspace) are registered as the requirement's delivery, the same way GitHub pull requests are. SSH handles clone, fetch and push. A conversation delivery returns the branch and commit SHA. You can optionally add a repository web URL to open the host and create a PR/MR manually. Issue import and PR/MR automation need a hosting API credential. To automate those actions, add a hosting-specific MCP in **Settings → Assets → MCP**, give it its own scoped token, and attach it to the relevant agent or workflow. [CNB does not support Git SSH](https://docs.cnb.cool/en/guide/git-access.html); it uses HTTPS with a CNB access token, which is outside this integration. diff --git a/internal/httpapi/assistant_conversation_issue.go b/internal/httpapi/assistant_conversation_issue.go index aefb0ebbb..2954539d8 100644 --- a/internal/httpapi/assistant_conversation_issue.go +++ b/internal/httpapi/assistant_conversation_issue.go @@ -131,7 +131,11 @@ func (h *agentToolGateway) recordConversationMRs(issueID string, delivered []del } mrs := []domain.DeliveryMR{} for _, r := range delivered { - project, iid, url, ok := domain.ParseGongfengMR(r.URL) + project, iid, url, ok := r.Project, r.IID, r.URL, r.Project != "" && r.IID > 0 + if !ok { + // GitHub/Gongfeng 调用方仍只给 URL,回落到 URL 反解。 + project, iid, url, ok = domain.ParseGongfengMR(r.URL) + } if !ok { continue } @@ -181,6 +185,10 @@ func (h *agentToolGateway) recordConversationMRs(issueID string, delivered []del // (team/repo, github:owner/repo) belongs to. func repositoryForMRProject(repos []domain.Repository, project string) (domain.Repository, bool) { for _, r := range repos { + // 绑定记录里的 gitlab: 标识最直接(公网 URL 无法按信任规则反解)。 + if strings.EqualFold(strings.TrimSpace(r.GongfengProjectID), project) { + return r, true + } for _, raw := range []string{r.CloneURL, r.WebURL} { if info, ok := domain.ParseRepositoryURL(raw); ok && strings.EqualFold(info.Project, project) { return r, true diff --git a/internal/httpapi/assistant_workspace_gitlab_mr.go b/internal/httpapi/assistant_workspace_gitlab_mr.go new file mode 100644 index 000000000..2518a00bc --- /dev/null +++ b/internal/httpapi/assistant_workspace_gitlab_mr.go @@ -0,0 +1,229 @@ +package httpapi + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "net/url" + "slices" + "strconv" + "strings" + "time" + + "agentflow/internal/domain" +) + +// turnDelivery 是一次 turn 结束后发现、需要登记为需求交付的 MR。 +// 同时服务 GitHub PR 与 GitLab MR,Project/IID 由发现方直接给出, +// 不再依赖从 URL 反解。 +type turnDelivery struct { + URL string + Title string + Body string + TargetBranch string + Project string // github:/ 或 gitlab:// + IID int +} + +// workspaceGitLabMR 是 GitLab v4 MR 中本流程用到的字段。 +type workspaceGitLabMR struct { + IID int `json:"iid"` + WebURL string `json:"web_url"` + Title string `json:"title"` + Description string `json:"description"` + State string `json:"state"` + MergedAt *time.Time `json:"merged_at"` + CreatedAt time.Time `json:"created_at"` + SHA string `json:"sha"` + TargetBranch string `json:"target_branch"` + DiffRefs struct { + HeadSHA string `json:"head_sha"` + } `json:"diff_refs"` +} + +// gitlabTurnMRs 列出某个 GitLab 项目里 token 用户本人创建、head 仍在工作区、 +// 且在 workspace 创建之后打开/合并的 MR。实例必须由管理员显式声明 +// (AGENTFLOW_GITLAB_ALLOWED_HOSTS),否则在发请求前就拒绝——凭据绝不发往 +// 未声明的 host。 +func gitlabTurnMRs(ctx context.Context, client *http.Client, token, project, base string, heads map[string]bool, since time.Time) ([]turnDelivery, error) { + host, ok := domain.GitLabInstanceHost(project) + if !ok { + return nil, fmt.Errorf("无效的 GitLab 仓库标识 %q", project) + } + if !domain.GitLabHostAllowed(host) { + return nil, fmt.Errorf("GitLab 实例 %s 未在管理员允许列表(%s)中:已拒绝发送凭据", host, domain.GitLabAllowedHostsEnv) + } + rest := strings.TrimPrefix(project, "gitlab:") + path := rest[strings.Index(rest, "/")+1:] + if strings.TrimSpace(path) == "" { + return nil, fmt.Errorf("无效的 GitLab 仓库标识 %q", project) + } + apiURL := base + "/api/v4/projects/" + url.PathEscape(path) + + "/merge_requests?state=all&scope=created_by_me&order_by=created_at&sort=desc&per_page=" + strconv.Itoa(turnDeliveryPullsMax) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", "application/json") + if token != "" { + req.Header.Set("PRIVATE-TOKEN", token) + } + res, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("无法连接 GitLab %s:%v", base, err) + } + defer res.Body.Close() + if res.StatusCode < 200 || res.StatusCode >= 300 { + raw, _ := io.ReadAll(io.LimitReader(res.Body, 512)) + return nil, fmt.Errorf("GitLab 返回 HTTP %d:%s", res.StatusCode, strings.TrimSpace(string(raw))) + } + var list []workspaceGitLabMR + if err := json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(&list); err != nil { + return nil, err + } + out := []turnDelivery{} + for _, mr := range list { + if mr.IID <= 0 || strings.TrimSpace(mr.WebURL) == "" { + continue + } + if mr.CreatedAt.Before(since) { + continue + } + if mr.State != "opened" && mr.State != "merged" { + continue + } + head := strings.TrimSpace(mr.SHA) + if !heads[head] { + head = strings.TrimSpace(mr.DiffRefs.HeadSHA) + if !heads[head] { + continue + } + } + out = append(out, turnDelivery{ + URL: mr.WebURL, + Title: mr.Title, + Body: mr.Description, + TargetBranch: mr.TargetBranch, + Project: project, + IID: mr.IID, + }) + if len(out) >= turnDeliveryPullsMax { + break + } + } + return out, nil +} + +// gitlabWorkspaceDeliveries 解析工作区里的 GitLab 远端,逐个已声明实例查询 +// 本 turn 的 MR。实例 scheme 以仓库记录为准(默认 https)。 +func (h *assistantHandlers) gitlabWorkspaceDeliveries(ctx context.Context, token string, run domain.Run, projects []string, heads map[string]bool) []turnDelivery { + if len(projects) == 0 { + return nil + } + repos := h.repo.Repositories() + client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} + out := []turnDelivery{} + for _, project := range projects { + host, ok := domain.GitLabInstanceHost(project) + if !ok || !domain.GitLabHostAllowed(host) { + continue + } + base := domain.GitLabInstanceScheme(host, repositoryURLsForProject(repos, project)...) + "://" + host + mrs, err := gitlabTurnMRs(ctx, client, token, project, base, heads, run.CreatedAt) + if err != nil { + log.Printf("find conversation workspace %s GitLab merge requests: %v", run.ID, err) + continue + } + out = append(out, mrs...) + if len(out) >= turnDeliveryPullsMax { + break + } + } + return out +} + +func repositoryURLsForProject(repos []domain.Repository, project string) []string { + urls := []string{} + for _, r := range repos { + if r.GongfengProjectID == project { + urls = append(urls, r.WebURL, r.CloneURL) + } + } + return urls +} + +// turnDeliveryLabel 是回复里给用户看的 MR 标签。 +func turnDeliveryLabel(d turnDelivery) string { + if strings.HasPrefix(d.Project, "gitlab:") { + return fmt.Sprintf("MR !%d", d.IID) + } + return fmt.Sprintf("PR #%d", d.IID) +} + +// gitlabBoundProjects 把工作区远端映射到本项目已绑定的 gitlab: 仓库。 +// 远端可能带 token(调用方已剥离)、.git 后缀或 ssh 形态,统一按 +// host+仓库路径比较;只有已绑定且随后通过 allowlist 校验的实例才会被查询。 +func gitlabBoundProjects(remotes []string, repos []domain.Repository, projectID string) []string { + out := []string{} + for _, repo := range repos { + project := strings.TrimSpace(repo.GongfengProjectID) + if !strings.HasPrefix(project, "gitlab:") { + continue + } + if projectID != "" && repo.ProjectID != projectID { + continue + } + for _, remote := range remotes { + if sameGitRemote(remote, repo.CloneURL) || sameGitRemote(remote, repo.WebURL) { + if !slices.Contains(out, project) && len(out) < turnDeliveryRepoMax { + out = append(out, project) + } + break + } + } + } + return out +} + +func sameGitRemote(a, b string) bool { + ah, ap, ok := splitGitRemote(a) + if !ok { + return false + } + bh, bp, ok := splitGitRemote(b) + if !ok { + return false + } + return strings.EqualFold(ah, bh) && strings.EqualFold(ap, bp) +} + +// splitGitRemote 归一化 https / ssh / scp 形态的仓库地址为 host + 仓库路径。 +func splitGitRemote(raw string) (host, path string, ok bool) { + s := strings.TrimSpace(raw) + if s == "" { + return "", "", false + } + if !strings.Contains(s, "://") { + if at := strings.Index(s, "@"); at >= 0 { + rest := s[at+1:] + if colon := strings.Index(rest, ":"); colon > 0 { + host = strings.ToLower(rest[:colon]) + path = strings.TrimSuffix(strings.Trim(rest[colon+1:], "/"), ".git") + return host, path, host != "" && path != "" + } + } + return "", "", false + } + u, err := url.Parse(s) + if err != nil || u.Host == "" { + return "", "", false + } + path = strings.TrimSuffix(strings.Trim(u.Path, "/"), ".git") + if path == "" { + return "", "", false + } + return strings.ToLower(u.Host), path, true +} diff --git a/internal/httpapi/assistant_workspace_gitlab_mr_test.go b/internal/httpapi/assistant_workspace_gitlab_mr_test.go new file mode 100644 index 000000000..cc9629d11 --- /dev/null +++ b/internal/httpapi/assistant_workspace_gitlab_mr_test.go @@ -0,0 +1,171 @@ +package httpapi + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "agentflow/internal/domain" + "agentflow/internal/repo" +) + +// 回归(agent-owned Git 后的 GitLab 等价能力):turn 结束时只登记作者本人、 +// head 仍在工作区、且在 workspace 创建之后打开/合并的 MR。 +func TestGitLabTurnMRsFiltersByAuthorHeadAndTime(t *testing.T) { + since := time.Date(2026, 11, 18, 0, 0, 0, 0, time.UTC) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if got := r.Header.Get("PRIVATE-TOKEN"); got != "gl-token" { + t.Errorf("PRIVATE-TOKEN = %q, want gl-token", got) + } + if !strings.HasSuffix(r.URL.Path, "/api/v4/projects/group/repo/merge_requests") { + t.Errorf("unexpected path %q", r.URL.Path) + } + if q := r.URL.Query(); q.Get("scope") != "created_by_me" || q.Get("state") != "all" { + t.Errorf("query scope=%q state=%q, want created_by_me/all", q.Get("scope"), q.Get("state")) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[ + {"iid":1,"web_url":"https://gl.example.test/group/repo/-/merge_requests/1","title":"keep","description":"d","state":"opened","created_at":"2026-11-18T01:00:00Z","sha":"aaa","target_branch":"main"}, + {"iid":2,"web_url":"https://gl.example.test/group/repo/-/merge_requests/2","title":"head gone","state":"opened","created_at":"2026-11-18T01:00:00Z","sha":"bbb","target_branch":"main"}, + {"iid":3,"web_url":"https://gl.example.test/group/repo/-/merge_requests/3","title":"too old","state":"opened","created_at":"2026-11-17T01:00:00Z","sha":"aaa","target_branch":"main"}, + {"iid":4,"web_url":"https://gl.example.test/group/repo/-/merge_requests/4","title":"closed unmerged","state":"closed","created_at":"2026-11-18T01:00:00Z","sha":"aaa","target_branch":"main"}, + {"iid":5,"web_url":"https://gl.example.test/group/repo/-/merge_requests/5","title":"merged via diff refs","state":"merged","merged_at":"2026-11-18T02:00:00Z","created_at":"2026-11-18T01:00:00Z","sha":"ccc","diff_refs":{"head_sha":"ddd"},"target_branch":"main"} + ]`)) + })) + defer srv.Close() + host := strings.TrimPrefix(srv.URL, "http://") + t.Setenv(domain.GitLabAllowedHostsEnv, host) + project := "gitlab:" + host + "/group/repo" + heads := map[string]bool{"aaa": true, "ddd": true} + + mrs, err := gitlabTurnMRs(context.Background(), srv.Client(), "gl-token", project, srv.URL, heads, since) + if err != nil { + t.Fatal(err) + } + if len(mrs) != 2 || mrs[0].IID != 1 || mrs[1].IID != 5 { + t.Fatalf("deliveries = %+v, want MR !1 and !5", mrs) + } + if mrs[0].Project != project || mrs[0].TargetBranch != "main" || mrs[0].URL == "" { + t.Fatalf("delivery fields = %+v", mrs[0]) + } +} + +// 未在 allowlist 中声明的 GitLab 实例:不发请求、不发凭据。 +func TestGitLabTurnMRsRejectsUnlistedInstance(t *testing.T) { + t.Setenv(domain.GitLabAllowedHostsEnv, "") + var hits int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&hits, 1) + })) + defer srv.Close() + _, err := gitlabTurnMRs(context.Background(), srv.Client(), "gl-token", + "gitlab:gitlab.attacker.example/group/repo", "https://gitlab.attacker.example", + map[string]bool{"aaa": true}, time.Now().Add(-time.Hour)) + if err == nil || !strings.Contains(err.Error(), domain.GitLabAllowedHostsEnv) { + t.Fatalf("unlisted instance must be rejected, got %v", err) + } + if n := atomic.LoadInt32(&hits); n != 0 { + t.Fatalf("unlisted instance received %d requests", n) + } +} + +// 没有用户令牌时不发送认证头(空头也算一次凭证提交)。 +func TestGitLabTurnMRsOmitsTokenWithoutCredential(t *testing.T) { + var tokenHeaders int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if n := len(r.Header.Values("PRIVATE-TOKEN")); n > 0 { + atomic.AddInt32(&tokenHeaders, int32(n)) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`[]`)) + })) + defer srv.Close() + host := strings.TrimPrefix(srv.URL, "http://") + t.Setenv(domain.GitLabAllowedHostsEnv, host) + if _, err := gitlabTurnMRs(context.Background(), srv.Client(), "", + "gitlab:"+host+"/group/repo", srv.URL, map[string]bool{}, time.Now().Add(-time.Hour)); err != nil { + t.Fatal(err) + } + if n := atomic.LoadInt32(&tokenHeaders); n != 0 { + t.Fatalf("PRIVATE-TOKEN must not be sent without a credential, saw %d", n) + } +} + +// 工作区远端可能是 https、ssh 或带 .git 后缀;绑定记录里的 gitlab: 标识 +// 要能按 host+路径匹配上,且不串项目。 +func TestGitlabBoundProjectsMatchesRemoteForms(t *testing.T) { + repos := []domain.Repository{ + {ID: "r1", ProjectID: "p1", GongfengProjectID: "gitlab:gitlab.example.test/group/repo", + CloneURL: "https://gitlab.example.test/group/repo.git", WebURL: "https://gitlab.example.test/group/repo"}, + {ID: "r2", ProjectID: "p2", GongfengProjectID: "gitlab:other.test/x/y", + CloneURL: "https://other.test/x/y.git"}, + } + remotes := []string{ + "https://gitlab.example.test/group/repo.git", + "git@gitlab.example.test:group/repo.git", + } + got := gitlabBoundProjects(remotes, repos, "p1") + if len(got) != 1 || got[0] != "gitlab:gitlab.example.test/group/repo" { + t.Fatalf("bound projects = %v", got) + } + if got := gitlabBoundProjects(remotes, repos, "p2"); len(got) != 0 { + t.Fatalf("other project must not match, got %v", got) + } +} + +func TestSplitGitRemoteForms(t *testing.T) { + cases := map[string][2]string{ + "https://gitlab.example.test/group/repo.git": {"gitlab.example.test", "group/repo"}, + "https://user:token@gitlab.example.test:8443/g/r.git": {"gitlab.example.test:8443", "g/r"}, + "git@gitlab.example.test:group/repo.git": {"gitlab.example.test", "group/repo"}, + "ssh://git@gitlab.example.test:2222/g/r.git": {"gitlab.example.test:2222", "g/r"}, + } + for raw, want := range cases { + host, path, ok := splitGitRemote(raw) + if !ok || host != want[0] || path != want[1] { + t.Fatalf("splitGitRemote(%q) = %q %q %v, want %q %q", raw, host, path, ok, want[0], want[1]) + } + } +} + +// GitLab MR URL 不在 Gongfeng 的 URL 解析规则内:登记时必须使用发现阶段 +// 直接给出的 project/iid,而不是回头从 URL 反解。 +func TestRecordConversationMRsUsesProvidedGitLabIdentity(t *testing.T) { + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + if err := st.PutIssue(domain.Issue{ID: "iss-gl-1", ProjectID: "p1", Title: "gitlab delivery", Status: "open"}); err != nil { + t.Fatal(err) + } + g := &agentToolGateway{deps: &deps{repo: st}} + repos := []domain.Repository{{ID: "repo-gl-1", ProjectID: "p1", GongfengProjectID: "gitlab:gl.test/group/repo"}} + mrs := []deliveredMR{{ + URL: "https://gl.test/group/repo/-/merge_requests/7", + Project: "gitlab:gl.test/group/repo", + IID: 7, + TargetBranch: "main", + }} + if err := g.recordConversationMRs("iss-gl-1", mrs, repos); err != nil { + t.Fatal(err) + } + issue, ok := st.Issue("iss-gl-1") + if !ok { + t.Fatal("issue missing") + } + if len(issue.DeliveryMRs) != 1 || issue.DeliveryMRs[0].Project != "gitlab:gl.test/group/repo" || issue.DeliveryMRs[0].IID != 7 { + t.Fatalf("delivery MRs = %+v", issue.DeliveryMRs) + } + if issue.DeliveryMRs[0].RepositoryID != "repo-gl-1" { + t.Fatalf("repository id = %q, want repo-gl-1", issue.DeliveryMRs[0].RepositoryID) + } + key := domain.MRDeliveryKey{Project: "gitlab:gl.test/group/repo", IID: 7} + if got := st.MRDeliveryStatesMap([]domain.MRDeliveryKey{key})[key]; got.IssueID != "iss-gl-1" { + t.Fatalf("delivery state = %+v, want issue iss-gl-1", got) + } +} diff --git a/internal/httpapi/assistant_workspace_mr.go b/internal/httpapi/assistant_workspace_mr.go index 0e2b2f6ba..f53344d21 100644 --- a/internal/httpapi/assistant_workspace_mr.go +++ b/internal/httpapi/assistant_workspace_mr.go @@ -35,6 +35,10 @@ type deliveredMR struct { Repository string URL string TargetBranch string + // Project 与 IID 由 turn 结束时的发现逻辑直接给出(GitHub PR / GitLab MR), + // 避免只靠 URL 反解——GitLab MR URL 不在 Gongfeng 解析规则内。 + Project string + IID int } func projectRepositories(all []domain.Repository, projectID string) []domain.Repository { @@ -66,14 +70,16 @@ type workspacePull struct { } `json:"base"` } -// registerTurnDeliveries runs when a turn ends. GitHub PRs the speaker opened -// from the conversation workspace are registered as the requirement's -// delivery (the conversation's open requirement, or a new one titled after -// the first PR), so MR polling completes the requirement once they merge. A -// PR counts when the speaker's token authored it after the workspace was -// created, a local branch in the workspace points at its head commit, and no -// requirement tracks it yet; PRs opened elsewhere are left alone. It returns -// a note for the reply, empty when nothing was registered. +// registerTurnDeliveries runs when a turn ends. GitHub PRs and GitLab MRs the +// speaker opened from the conversation workspace are registered as the +// requirement's delivery (the conversation's open requirement, or a new one +// titled after the first MR), so MR polling completes the requirement once +// they merge. An MR counts when the speaker's token authored it after the +// workspace was created, a local branch in the workspace points at its head +// commit, and no requirement tracks it yet; MRs opened elsewhere are left +// alone. GitLab instances must be admin-declared (allowlist), otherwise they +// are skipped without sending any credential. It returns a note for the reply, +// empty when nothing was registered. func (h *assistantHandlers) registerTurnDeliveries(ctx context.Context, s *AgentToolSession) string { if s == nil || s.RunID != "" || h.engine == nil || strings.TrimSpace(s.User.GitToken) == "" { return "" @@ -92,39 +98,57 @@ func (h *assistantHandlers) registerTurnDeliveries(ctx context.Context, s *Agent } heads := map[string]bool{} projects := []string{} + remotes := []string{} for _, checkout := range checkouts { for _, head := range checkout.Heads { heads[head] = true } for _, remote := range checkout.Remotes { - info, ok := domain.ParseRepositoryURL(withoutURLUserinfo(remote)) + clean := withoutURLUserinfo(remote) + remotes = append(remotes, clean) + info, ok := domain.ParseRepositoryURL(clean) if ok && strings.HasPrefix(info.Project, "github:") && !slices.Contains(projects, info.Project) && len(projects) < turnDeliveryRepoMax { projects = append(projects, info.Project) } } } - if len(heads) == 0 || len(projects) == 0 { + // 公网/自建 GitLab 的裸 URL 不在 ParseRepositoryURL 的信任规则内, + // 但工作区仓库已经绑定并过了 allowlist:按仓库记录反查远端属于哪个 + // gitlab: 项目,再逐个实例查询。 + gitlabProjects := gitlabBoundProjects(remotes, h.repo.Repositories(), s.ProjectID) + if len(heads) == 0 || (len(projects) == 0 && len(gitlabProjects) == 0) { return "" } - pulls, err := workspacePulls(ctx, s.User.GitToken, projects, heads, run.CreatedAt) - if err != nil { - log.Printf("find conversation workspace %s pull requests: %v", run.ID, err) + deliveries := []turnDelivery{} + if len(projects) > 0 { + pulls, err := workspacePulls(ctx, s.User.GitToken, projects, heads, run.CreatedAt) + if err != nil { + // GitLab 侧仍可登记,不能因为 GitHub 查询失败就整体放弃。 + log.Printf("find conversation workspace %s pull requests: %v", run.ID, err) + } + for _, p := range pulls { + project, iid, _, ok := domain.ParseGongfengMR(p.URL) + if !ok { + continue + } + deliveries = append(deliveries, turnDelivery{URL: p.URL, Title: p.Title, Body: p.Body, TargetBranch: p.Base.Ref, Project: project, IID: iid}) + } + } + deliveries = append(deliveries, h.gitlabWorkspaceDeliveries(ctx, s.User.GitToken, run, gitlabProjects, heads)...) + if len(deliveries) == 0 { return "" } - keys := []domain.MRDeliveryKey{} - for _, p := range pulls { - if project, iid, _, ok := domain.ParseGongfengMR(p.URL); ok { - keys = append(keys, domain.MRDeliveryKey{Project: project, IID: iid}) - } + keys := make([]domain.MRDeliveryKey, 0, len(deliveries)) + for _, d := range deliveries { + keys = append(keys, domain.MRDeliveryKey{Project: d.Project, IID: d.IID}) } tracked := h.repo.MRDeliveryStatesMap(keys) - fresh := []workspacePull{} - for _, p := range pulls { - project, iid, _, ok := domain.ParseGongfengMR(p.URL) - if !ok || strings.TrimSpace(tracked[domain.MRDeliveryKey{Project: project, IID: iid}].IssueID) != "" { + fresh := make([]turnDelivery, 0, len(deliveries)) + for _, d := range deliveries { + if strings.TrimSpace(tracked[domain.MRDeliveryKey{Project: d.Project, IID: d.IID}].IssueID) != "" { continue } - fresh = append(fresh, p) + fresh = append(fresh, d) } if len(fresh) == 0 { return "" @@ -132,14 +156,14 @@ func (h *assistantHandlers) registerTurnDeliveries(ctx context.Context, s *Agent gateway := &agentToolGateway{deps: h.deps} issue, created, err := gateway.linkConversationRequirement(s, run, conversationRequirement{Title: strings.TrimSpace(fresh[0].Title), Description: strings.TrimSpace(fresh[0].Body)}, true) if err != nil || issue.ID == "" { - log.Printf("link conversation workspace %s requirement for its pull requests: %v", run.ID, err) + log.Printf("link conversation workspace %s requirement for its merge requests: %v", run.ID, err) return "" } mrs := make([]deliveredMR, 0, len(fresh)) links := make([]string, 0, len(fresh)) - for _, p := range fresh { - mrs = append(mrs, deliveredMR{URL: p.URL, TargetBranch: p.Base.Ref}) - links = append(links, fmt.Sprintf("[PR #%d](%s)", p.Number, p.URL)) + for _, d := range fresh { + mrs = append(mrs, deliveredMR{URL: d.URL, TargetBranch: d.TargetBranch, Project: d.Project, IID: d.IID}) + links = append(links, fmt.Sprintf("[%s](%s)", turnDeliveryLabel(d), d.URL)) } if err := gateway.recordConversationMRs(issue.ID, mrs, projectRepositories(h.repo.Repositories(), s.ProjectID)); err != nil { log.Printf("record conversation workspace %s delivery: %v", run.ID, err) From 79b4d48397e875e3116811c7906f80713950a1a5 Mon Sep 17 00:00:00 2001 From: mabo Date: Mon, 23 Nov 2026 16:55:03 +0800 Subject: [PATCH 10/10] Pass GitLab and Git egress settings through Compose The GitLab adapter reads AGENTFLOW_GITLAB_ALLOWED_HOSTS and the control-plane dialer reads AGENTFLOW_GIT_EGRESS_ALLOW_CIDRS, but compose.yaml lists platform environment variables explicitly and never forwarded either one. A container install therefore could not enable self-hosted GitLab at all. Co-Authored-By: Claude Code --- .env.example | 6 ++++++ compose.yaml | 5 +++++ 2 files changed, 11 insertions(+) diff --git a/.env.example b/.env.example index d417f3542..ed54146c4 100644 --- a/.env.example +++ b/.env.example @@ -16,6 +16,12 @@ AGENTFLOW_PLATFORM_MCP_URL= # Optional managed Git and TAPD web hosts, with a port if required. AGENTFLOW_GONGFENG_HOST= AGENTFLOW_TAPD_HOST= +# Optional self-hosted GitLab instances allowed to receive Git HTTPS tokens +# (comma-separated host or host:port). Empty disables GitLab repositories. +AGENTFLOW_GITLAB_ALLOWED_HOSTS= +# Optional private networks the control plane may dial for Git +# (comma-separated CIDRs, for example an internal GitLab on 10.0.0.0/8). +AGENTFLOW_GIT_EGRESS_ALLOW_CIDRS= # Optional deployment-level credential for a configured tracker MCP. AGENTFLOW_MCP_TOKEN= # Optional model IDs available to your CodeBuddy account (comma-separated): diff --git a/compose.yaml b/compose.yaml index 4710f3d2b..0693953b1 100644 --- a/compose.yaml +++ b/compose.yaml @@ -34,6 +34,11 @@ services: AGENTFLOW_GITHUB_CLIENT_ID: ${AGENTFLOW_GITHUB_CLIENT_ID:-} AGENTFLOW_GONGFENG_HOST: ${AGENTFLOW_GONGFENG_HOST:-} AGENTFLOW_TAPD_HOST: ${AGENTFLOW_TAPD_HOST:-} + # Comma-separated self-hosted GitLab instances (host or host:port) allowed + # to receive per-host Git HTTPS tokens. Empty disables GitLab repositories. + AGENTFLOW_GITLAB_ALLOWED_HOSTS: ${AGENTFLOW_GITLAB_ALLOWED_HOSTS:-} + # Private networks the control plane may dial for Git (internal GitLab, etc). + AGENTFLOW_GIT_EGRESS_ALLOW_CIDRS: ${AGENTFLOW_GIT_EGRESS_ALLOW_CIDRS:-} AGENTFLOW_MCP_TOKEN: ${AGENTFLOW_MCP_TOKEN:-} AGENTFLOW_GIT_SSH_KNOWN_HOSTS: ${AGENTFLOW_GIT_SSH_KNOWN_HOSTS:-} AGENTFLOW_ASSISTANT_SESSION_DIR: /data/assistant