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/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsx index 32f89977f..9f1cad907 100644 --- a/chatbot/src/QuickAccessWizard.jsx +++ b/chatbot/src/QuickAccessWizard.jsx @@ -563,8 +563,14 @@ function parseGitHubRepo(raw) { } // Explicit SSH keeps its transport. Managed HTTPS links use the configured host. +/** + * GitLab 自托管主机(gitlab:/ 或内网裸 URL)优先于工蜂与通用 HTTPS, + * 让向导也能绑定与 web 控制台一致的主机级仓库标识。 + * --- @ty.aicoding@1795420649000 --- + */ export function parseGongfengRepo(raw, host = "") { return globalThis.LoopForgeGitSSH(raw) || + globalThis.LoopForgeGitLab?.(raw) || globalThis.LoopForgeGongfengRepository(raw, host) || globalThis.LoopForgeGitHTTPS(raw) || parseGitHubRepo(raw); 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 diff --git a/docs/deployment.md b/docs/deployment.md index 693cb9d66..398579ece 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -138,6 +138,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 per-host Git HTTPS credential is sent to them as `PRIVATE-TOKEN` for MR create/merge and status sync. Bind a repository by pasting its full `http(s)://host/group/repo` URL (bare URLs are accepted for loopback and RFC1918 instances plus `.internal`/`.local` names; public self-hosted instances must use the explicit `gitlab://` identity) or by entering the prefixed identity directly. Users register the token under **Personal settings → Git HTTPS credentials** with platform `gitlab` for that host. 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. When the instance is only reachable on private addresses, also list its networks in `AGENTFLOW_GIT_EGRESS_ALLOW_CIDRS` so the control plane (token verification and MR API calls) may dial it. An empty or unset allowlist 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. GitLab issue import is not supported; MR delivery state is refreshed by the MR sync task instead. + 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/domain/gitlab_repository_test.go b/internal/domain/gitlab_repository_test.go new file mode 100644 index 000000000..46e994da5 --- /dev/null +++ b/internal/domain/gitlab_repository_test.go @@ -0,0 +1,128 @@ +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) + } + // 前缀不带 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 { + 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) { + // 私有/回环网段应受信任(只断言网段类别,不引用真实主机)。 + 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 为文档保留段)。 + // 172.0.0.0/8 内 RFC1918 之外的公网段(172.217/16 Google、172.64/13 Cloudflare) + // 必须拒绝:整段放行等于让公网主机冒充内网实例。link-local(云元数据端点)同样拒绝。 + // 主机名只认 .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) + } + } + // 非常规网段走显式 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) { + 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) + } +} + +// 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 8c63aa808..112514fc2 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,139 @@ 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 + } + // 已是前缀标识,直接规范化。前缀不带 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) + } + 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, 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, ":") + 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 + } + // scp/裸主机形态没有 scheme 信息(scheme 为空),由 gitlabRepoInfo 兜底 https。 + return gitlabRepoInfo(scheme, host, project) +} + +// 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 := 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 的可信主机:裸 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),整段放行会让公网主机冒充内网实例。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() + } + // 内网主机名:只认 .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. // 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:") } @@ -39,6 +167,14 @@ 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:先尝试自托管 GitLab。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 + } + } if !strings.ContainsAny(s, ":@") { host, _, _ := strings.Cut(s, "/") if !IsGongfengHost(host) { diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index d97371f6b..d0f841577 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -197,7 +197,7 @@ func (h *catalogHandlers) repositories(c *gin.Context) { if primary != "" { info, ok := domain.ParseRepositoryURL(primary) if !ok { - c.JSON(400, gin.H{"error": "请填写完整的 GitHub、HTTPS 或 Git SSH 仓库地址"}) + c.JSON(400, gin.H{"error": "请填写完整的 GitHub、GitLab、HTTPS 或 Git SSH 仓库地址"}) return } if body.RepoURL != "" && body.URL != "" { @@ -264,13 +264,42 @@ 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 + } + // 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 } + // 能写 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 454d75b94..fcda182a3 100644 --- a/internal/httpapi/catalog_test.go +++ b/internal/httpapi/catalog_test.go @@ -754,6 +754,89 @@ 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。 + // 实例须由管理员在 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", + }, 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 != "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" { + 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.20.0.10/team/svc.git", + }, http.StatusOK) + 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: 前缀 + // 分发,静默接受只会得到一个指向工蜂却声明为 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) + } +} + +// 回归(评审阻塞项):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) { diff --git a/internal/tracker/gitlab.go b/internal/tracker/gitlab.go new file mode 100644 index 000000000..2676c33ab --- /dev/null +++ b/internal/tracker/gitlab.go @@ -0,0 +1,304 @@ +/** + * 自托管 GitLab(GitLab CE/EE 兼容,14.10+)的 MR 交付适配器。 + * 一个客户端对应一个 "gitlab://" 标识,多实例由 host 区分; + * 认证复用平台的每主机 HTTPS Git 凭据(GitHTTPCredentialForHost), + * 凭据只发往管理员在 AGENTFLOW_GITLAB_ALLOWED_HOSTS 中显式声明的实例。 + * --- @ty.aicoding@1795418206570 --- + */ +package tracker + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "agentflow/internal/domain" + "agentflow/internal/gitegress" +) + +type gitlabClient struct { + id string // "gitlab://" 标识,用于拼交付链接 + base string // 站点根,如 http://gitlab.example.test + project string // URL 编码后的项目路径,如 group%2Frepository + token string + http *http.Client +} + +// gitlabProjectParts 拆分 "gitlab://" 标识。 +// --- @ty.aicoding@1795418206570 --- +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 +} + +// gitlabClient 按仓库绑定记录解析项目 Owner 的每主机 Git 凭据并构造客户端。 +// 凭据只发往管理员显式声明的实例(AGENTFLOW_GITLAB_ALLOWED_HOSTS):成员只要 +// 能写 POST /api/repositories 就能绑定任意 gitlab:,若按"前缀即可信" +// 放行,Owner 的 Git 令牌会被当 PRIVATE-TOKEN 发到攻击者主机。未声明则直接 +// 拒绝构造客户端,不携带任何凭据。 +// --- @ty.aicoding@1795418765976 --- +func (s *Service) gitlabClient(project string) (*gitlabClient, error) { + host, projectPath, ok := gitlabProjectParts(project) + if !ok { + return nil, fmt.Errorf("invalid GitLab repository") + } + if !domain.GitLabHostAllowed(host) { + return nil, fmt.Errorf("GitLab 实例 %s 未在管理员允许列表(%s)中:已拒绝发送凭据,请让管理员在部署配置中声明该实例", host, domain.GitLabAllowedHostsEnv) + } + var token string + var siteURLs []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 credentialStore, ok := s.projectAuth.(GitHTTPCredentialStore); ok { + if cred, found := credentialStore.GitHTTPCredentialForHost(context.Background(), p.OwnerID, host); found && cred.Token != "" { + if cred.Platform != domain.GitPlatformGitLab { + return nil, fmt.Errorf("主机 %s 的凭据平台是 %q,不是 GitLab", host, cred.Platform) + } + token = cred.Token + } + } + } + // 实例 scheme 以仓库记录的 URL 为准(https 默认),不在 ID 里硬编码。 + siteURLs = []string{repo.WebURL, repo.CloneURL} + break + } + } + base := domain.GitLabInstanceScheme(host, siteURLs...) + "://" + host + // gitegress 客户端自带出网地址策略与"不跟随重定向";测试注入 + // gitHostAPIBase 时只替换目标地址,保留重定向拒绝语义,避免 + // PRIVATE-TOKEN 在 302 场景被带到别的 origin。 + client := gitegress.Client() + if s.gitHostAPIBase != "" { + base = s.gitHostAPIBase + client = &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} + } + return &gitlabClient{ + id: project, + base: base, + project: url.PathEscape(projectPath), + token: token, + // 与 GitHub client 一致:不跟随重定向。PRIVATE-TOKEN 是凭证, + // 302 到别的 origin 绝不能把 token 带过去。 + http: client, + }, nil +} + +// request 发起一次 GitLab v4 API 调用,输入输出均为 JSON。 +// --- @ty.aicoding@1795418206570 --- +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(CE/EE)以 PRIVATE-TOKEN 头认证(v4 REST 标准方式)。 + 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"` + SHA string `json:"sha,omitempty"` + DiffRefs struct { + HeadSHA string `json:"head_sha"` + } `json:"diff_refs,omitempty"` +} + +// headSHA 是 MR 源分支的当前提交;列表响应缺 sha 时退回 diff_refs。 +// --- @ty.aicoding@1795419744565 --- +func (m gitlabMergeRequest) headSHA() string { + if sha := strings.TrimSpace(m.SHA); sha != "" { + return sha + } + return strings.TrimSpace(m.DiffRefs.HeadSHA) +} + +// delivery 把 GitLab MR 记录转成交付领域对象,URL 走统一的标识反解规则。 +// --- @ty.aicoding@1795418206570 --- +func (m gitlabMergeRequest) delivery(project string) domain.DeliveryMR { + state := "opened" + if m.State == "merged" { + state = "merged" + } else if m.State == "closed" || m.State == "locked" { + state = "closed" + } + return domain.DeliveryMR{ + Project: project, + IID: m.IID, + URL: domain.GongfengMRURL(project, m.IID), + State: state, + GongfengState: state, + TargetBranch: m.TargetBranch, + } +} + +// mergedAt 解析 GitLab 的 RFC3339 合并时间,零值表示尚未合并。 +// --- @ty.aicoding@1795418206570 --- +func (m gitlabMergeRequest) mergedAt() time.Time { + if m.MergedAt == "" { + return time.Time{} + } + t, _ := time.Parse(time.RFC3339, m.MergedAt) + return t +} + +// findMR 列出项目 MR 并匹配 source 分支(给定时还要匹配 target)。 +// --- @ty.aicoding@1795418206570 --- +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 +} + +// listMRs 返回 source→target 的全部 MR(对齐 github listPulls 语义), +// 供存在性/合并状态判断保留多条记录。 +// --- @ty.aicoding@1795419744565 --- +func (g *gitlabClient) listMRs(source, target string) ([]domain.DeliveryMR, error) { + q := url.Values{"state": {"all"}, "per_page": {"100"}, "order_by": {"updated_at"}, "sort": {"desc"}} + if source != "" { + q.Set("source_branch", source) + } + if target != "" { + q.Set("target_branch", target) + } + var list []gitlabMergeRequest + if err := g.request("GET", "/merge_requests?"+q.Encode(), nil, &list); err != nil { + return nil, err + } + out := make([]domain.DeliveryMR, 0, len(list)) + for _, m := range list { + mr := m.delivery(g.id) + mr.HeadSHA = m.headSHA() + out = append(out, mr) + } + return out, nil +} + +// gitlabFindBranch 解析 source 分支当前的 MR(用于交付物反查)。 +// --- @ty.aicoding@1795418206570 --- +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 语义):调用 merge 端点后校验返回的 MR 状态必须是 +// merged,否则报错——未合并绝不能返回成功,否则交付会虚进。 +// --- @ty.aicoding@1795418206570 --- +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 { + // 并发下另一个实例可能已创建:再查一次,复用胜者继续走合并。 + rematch, ok2, err2 := g.findMR(branch, target) + if err2 != nil || !ok2 { + return "", err + } + m = rematch + } else { + 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..302b7ce09 --- /dev/null +++ b/internal/tracker/gitlab_test.go @@ -0,0 +1,260 @@ +/** + * 自托管 GitLab MR 适配器的回归测试:allowlist 凭据边界、merge 端点 + * 真合并校验、创建后合并、跨域重定向拒绝与 scheme 跟随仓库记录。 + * 认证使用平台的每主机 HTTPS Git 凭据,而非已废弃的单体 GitToken。 + * --- @ty.aicoding@1795418634080 --- + */ +package tracker + +import ( + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/repo" +) + +// gitLabFixture 起一个本地 GitLab(httptest),注册 owner 的每主机凭据与 +// gitlab: 仓库行。凭据按平台规则只能绑定命名主机(不能是 IP),因此标识、 +// allowlist 与凭据统一使用占位名 gitlab.example.test,实际请求经 +// gitHostAPIBase 指向测试服务器。 +func gitLabFixture(t *testing.T, handler http.HandlerFunc) (*Service, string) { + t.Helper() + return gitLabFixtureWithToken(t, handler, "gl-private-token") +} + +const gitLabFixtureHost = "gitlab.example.test" + +func gitLabFixtureWithToken(t *testing.T, handler http.HandlerFunc, token string) (*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"}); 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) + } + t.Setenv(domain.GitLabAllowedHostsEnv, gitLabFixtureHost) + project := "gitlab:" + gitLabFixtureHost + "/group/repo" + if err := st.PutRepository(domain.Repository{ID: "gl-repo", ProjectID: "glproj", Provider: "gitlab", Name: "repo", GongfengProjectID: project, DefaultBranch: "main", WebURL: "https://" + gitLabFixtureHost + "/group/repo"}); err != nil { + t.Fatal(err) + } + if token != "" { + if err := st.SaveGitHTTPCredential(u.ID, "", domain.GitHTTPCredentialSecret{ + GitHTTPCredential: domain.GitHTTPCredential{Name: gitLabFixtureHost, Platform: domain.GitPlatformGitLab, Host: gitLabFixtureHost}, + Token: token, + }); err != nil { + t.Fatal(err) + } + } + s := NewService() + s.ConfigureWithStore(domain.SyncConfig{}, st) + s.gitHostAPIBase = srv.URL + 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) + } +} + +// 未配置主机凭据时,请求里不能出现 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) { + 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):测试注入把请求指向本地 httptest(http), +// GitLabInstanceScheme 在无匹配记录时默认 https——scheme 不再硬编码。 +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("injected test base 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) + } +} + +// 主机凭据声明的平台不是 GitLab 时拒绝构造客户端,避免把令牌以错误的 +// 认证形态发出去。 +func TestGitLabClientRejectsNonGitLabCredential(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(404) + })) + defer srv.Close() + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + if err := st.PutUser(domain.User{LoginName: "owner"}); err != nil { + t.Fatal(err) + } + u, _ := st.UserByLoginName("owner") + if err := st.PutProject(domain.Project{ID: "p", Name: "P", OwnerID: u.ID}); err != nil { + t.Fatal(err) + } + host := gitLabFixtureHost + t.Setenv(domain.GitLabAllowedHostsEnv, host) + project := "gitlab:" + host + "/group/repo" + if err := st.PutRepository(domain.Repository{ID: "r", ProjectID: "p", Provider: "gitlab", Name: "repo", GongfengProjectID: project, WebURL: "https://" + host + "/group/repo"}); err != nil { + t.Fatal(err) + } + if err := st.SaveGitHTTPCredential(u.ID, "", domain.GitHTTPCredentialSecret{ + GitHTTPCredential: domain.GitHTTPCredential{Name: host, Platform: domain.GitPlatformGitHub, Host: host}, + Token: "wrong-platform", + }); err != nil { + t.Fatal(err) + } + s := NewService() + s.ConfigureWithStore(domain.SyncConfig{}, st) + s.gitHostAPIBase = srv.URL + if _, err := s.gitlabClient(project); err == nil || !strings.Contains(err.Error(), "GitLab") { + t.Fatalf("non-GitLab credential must be rejected, got %v", err) + } +} diff --git a/internal/tracker/merge_mr.go b/internal/tracker/merge_mr.go index e5c2593e2..4397082b2 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) @@ -141,6 +144,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 == "" { @@ -201,6 +207,17 @@ func (s *Service) FindBranchMRsInto(q domain.BranchMRQuery) ([]domain.DeliveryMR } return githubPullsInto(pulls, project, src, target), nil } + if strings.HasPrefix(project, "gitlab:") { + g, err := s.gitlabClient(project) + if err != nil { + return nil, err + } + list, err := g.listMRs(src, target) + if err != nil { + return nil, err + } + return list, nil + } client, source, err := s.gongfengClientForRun(project, q) if err != nil { return nil, err diff --git a/internal/tracker/mr_delivery_sync.go b/internal/tracker/mr_delivery_sync.go index e327b1053..f6e5365f8 100644 --- a/internal/tracker/mr_delivery_sync.go +++ b/internal/tracker/mr_delivery_sync.go @@ -163,6 +163,11 @@ func (s *Service) syncMRDeliveryStates(store MRDeliveryStore) { } } +/** + * MR 交付状态同步:按 MR 标识前缀分发到 GitHub / 外部主机(GHE、自托管 + * GitLab)/ 工蜂 MCP 三条刷新与发现路径。 + * --- @ty.aicoding@1795419690999 --- + */ func (s *Service) discoverPromoteMRs(store MRDeliveryStore) { if s == nil || store == nil { return @@ -170,7 +175,8 @@ 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:") { + // github: 与 gitlab: 仓库走各自的 HTTP 适配器,不能落到工蜂 MCP 发现路径。 + 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 8df2c74e8..85fc4cc51 100644 --- a/internal/tracker/service.go +++ b/internal/tracker/service.go @@ -318,6 +318,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 } diff --git a/web/app/git-ssh.js b/web/app/git-ssh.js index 886b0ac29..549a79c98 100644 --- a/web/app/git-ssh.js +++ b/web/app/git-ssh.js @@ -54,6 +54,41 @@ globalThis.LoopForgeGitHTTPS = function parseHTTPSRepository(raw) { }catch{return null} }; +// Self-managed GitLab keeps the host inside the project identity so several +// instances can coexist: "gitlab://". Bare URLs are only +// recognised for private/internal hosts, matching the server's trust rule; +// a public self-hosted instance must paste the explicit prefix. +/** + * --- @ty.aicoding@1795420649000 --- + */ +globalThis.LoopForgeGitLab = function parseGitLabRepository(raw) { + const address = String(raw || '').trim().replace(/^['"]|['"]$/g, '').replace(/^git clone /, '').replace(/^['"]|['"]$/g, '').split(/\s+/)[0]; + if (!address || /[\s"'<>\\?#]/.test(address)) return null; + const build = (scheme, host, path) => { + let clean = path.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, ''); + // Drop a sub-page suffix (merge request, tree view, issue...) before taking the repo path. + for (const marker of ['/-/', '/tree/', '/blob/', '/commit/', '/commits/', '/merge_requests/', '/issues/', '/snippets/', '/wikis/', '/releases/', '/tags/']) { + const at = clean.indexOf(marker); + if (at > 0) clean = clean.slice(0, at); + } + if (!/^[a-z0-9][a-z0-9._-]*(?::[0-9]+)?$/i.test(host)) return null; + const parts = clean.split('/'); + if (parts.length < 2 || parts.some(part => !/^[a-z0-9_.~-]+$/i.test(part) || part === '.' || part === '..')) return null; + const base = `${scheme}://${host.toLowerCase()}/${parts.join('/')}`; + return { provider: 'gitlab', project: `gitlab:${host.toLowerCase()}/${parts.join('/')}`, name: parts.at(-1), webUrl: base, cloneUrl: base + '.git' }; + }; + const prefixed = /^gitlab:([^/]+)\/(.+)$/i.exec(address); + if (prefixed) return build('https', prefixed[1], prefixed[2]); + const url = /^(https?):\/\/([^/]+)\/(.+)$/i.exec(address); + if (!url) return null; + const scheme = url[1].toLowerCase(), host = url[2].toLowerCase(); + if (host.includes('@') || /[\s\\]/.test(host)) return null; + const hostname = host.replace(/:[0-9]+$/, ''); + if (['github.com', 'git.example.com'].includes(hostname)) return null; + const internal = /^(127\.|10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)/.test(hostname) || /\.(internal|local)$/i.test(hostname); + return internal ? build(scheme, host, url[3]) : null; +}; + // The managed host is supplied by the deployment. Explicit old links remain // readable so existing repositories can be opened and edited. globalThis.LoopForgeGongfengRepository = function parseManagedRepository(raw, host = '') { diff --git a/web/app/issues.js b/web/app/issues.js index a42695e0e..5bb7e7cbe 100644 --- a/web/app/issues.js +++ b/web/app/issues.js @@ -543,12 +543,18 @@ function issueFromForm(){ // 将完整的仓库链接和克隆地址解析成统一的仓库信息。 // repoDisplayPath shows host/path for a parsed repository, e.g. github.com/owner/name. function repoDisplayPath(info,fallback=''){return info?.provider==='ssh'?(info.project||info.cloneUrl||fallback):info?.webUrl?String(info.webUrl).replace(/^https?:\/\//,''):String(fallback||'')} +// repoProviderLabel 为解析后的仓库选择展示标签,自托管 GitLab 单独标 GitLab。 +// --- @ty.aicoding@1795420649000 --- function repoProviderLabel(info){ - const labels={ssh:'Git SSH',https:'Git HTTPS',github:'GitHub',gongfeng:'工蜂'}; + const labels={ssh:'Git SSH',https:'Git HTTPS',github:'GitHub',gitlab:'GitLab',gongfeng:'工蜂'}; return labels[info?.provider]||'Git'; } +// parseGongfengRepoURL 按 SSH → GitLab → 工蜂 → 通用 HTTPS → GitHub 的顺序解析, +// 与后端仓储校验的优先级保持一致。 +// --- @ty.aicoding@1795420649000 --- function parseGongfengRepoURL(raw){ const sshInfo=globalThis.LoopForgeGitSSH?.(raw);if(sshInfo)return sshInfo; + const gitlab=globalThis.LoopForgeGitLab?.(raw);if(gitlab)return gitlab; const managed=globalThis.LoopForgeGongfengRepository?.(raw,state.data?.gongfengHost);if(managed)return managed; const httpsInfo=globalThis.LoopForgeGitHTTPS?.(raw);if(httpsInfo)return httpsInfo; let publicURL=String(raw||'').trim().replace(/^git clone /,'').replace(/^github:/,'https://github.com/').replace(/^(?:git@github\.com:|ssh:\/\/git@github\.com(?::22)?\/)/,'https://github.com/'); diff --git a/webtest/tests/projects-repos.test.mjs b/webtest/tests/projects-repos.test.mjs index 1a301a9a0..40ada65cf 100644 --- a/webtest/tests/projects-repos.test.mjs +++ b/webtest/tests/projects-repos.test.mjs @@ -120,6 +120,48 @@ test('repository drawer detects Git SSH URLs and persists a default repository', assert.ok(app.router.calls.some(c => c.method === 'DELETE' && c.path === '/api/repositories')); }); +test('repository drawer saves a self-managed GitLab URL with its host-scoped identity', async (t) => { + const app = await loadApp(); + t.after(app.close); + app.router.post('/api/repositories', (call) => ({ ...call.body, id: 'repo-gl' })); + app.router.put('/api/projects', (call) => call.body); + app.evaluate(` + state.projectAdminDetailId='project-1'; + state.projectDraftFor='project-1'; + state.projectDraft=projectDraftFrom(state.data.projects[0]); + state.projectDraftBase=clone(state.projectDraft); + state.data.repositories=[]; + openRepoDrawer(''); + `); + const form = app.document.querySelector('#repoDrawerForm'); + const input = (value) => { + form.elements.repoUrl.value = value; + form.elements.repoUrl.dispatchEvent(new app.window.Event('input', { bubbles: true })); + }; + // A prefixed identity is the escape hatch for public self-hosted instances. + input('gitlab:gitlab.example.test/group/repo'); + await settle(4); + assert.equal(app.document.querySelector('#repoDrawerDetectPath').textContent, 'gitlab:gitlab.example.test/group/repo'); + assert.equal(form.elements.name.value, 'repo'); + // An internal HTTPS URL is accepted without the prefix and keeps its host. + input('https://172.20.0.10/team/svc.git'); + await settle(4); + assert.equal(app.document.querySelector('#repoDrawerDetectPath').textContent, 'gitlab:172.20.0.10/team/svc'); + form.elements.defaultBranch.value = 'main'; + form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true })); + await settle(8); + const create = app.router.calls.find(c => c.method === 'POST' && c.path === '/api/repositories'); + assert.equal(create.body.provider, 'gitlab'); + assert.equal(create.body.gongfengProjectId, 'gitlab:172.20.0.10/team/svc'); + assert.equal(create.body.webUrl, 'https://172.20.0.10/team/svc'); + assert.equal(create.body.cloneUrl, 'https://172.20.0.10/team/svc.git'); + // A public domain without the prefix stays a plain Git HTTPS remote rather + // than being guessed as GitLab; the prefixed identity is the opt-in. + input('https://gitlab.example.test/group/repo'); + await settle(4); + assert.equal(app.evaluate(`parseGongfengRepoURL('https://gitlab.example.test/group/repo')?.provider`), 'https'); +}); + test('project owner deletes a project from its danger zone and the list moves on', async (t) => { const app = await loadApp(); t.after(app.close);