beads/internal/gitlab/tracker_test.go
Vishnu J a8a6c67413
Beads #6735: prevent duplicate GitLab sync on self-hosted URLs (#6736)
* fix(gitlab): recognize work-item URLs on the configured self-hosted host (GH#6735)

IsExternalRef required the substring "gitlab" in the URL, so self-hosted
instances without it were treated as unlinked and sync created duplicate
issues. Also accept issue/work-item/milestone URLs whose host (and base
path) match the configured gitlab.url; unrelated hosts stay rejected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* docs(gitlab): record the self-hosted ref fix and correct the BaseURL contract

Maintainer review fixups for #6736. The review found no blocker and no major;
these are its two gate-impact minors plus the two nearby nits. No behavior
change: the only non-comment edits are in the test.

- CHANGELOG had no entry for a user-visible change to which external refs the
  GitLab tracker claims (6 of the 8 commits preceding the merge base touch it).
  The bullet names GH#6735 and the two limits a reader actually needs: matching
  is host-scoped, not project-scoped, and the host must be spelled the way
  GitLab emits it in web_url.

- Client.BaseURL was documented as "https://gitlab.com/api/v4". That example was
  already wrong before this PR -- buildURL appends DefaultAPIEndpoint itself, so
  the documented form doubles the suffix -- but onConfiguredHost now makes the
  web-root form load-bearing for ref identity, so a maintainer "fixing" a
  construction site to match the comment would silently restore the duplicate
  sync this PR fixes. WithEndpoint is that construction site: its doc said
  "custom API endpoint" while assigning BaseURL. It has no production caller,
  so both are doc-only corrections.

- onConfiguredHost now states the host-only match scope and the literal host
  comparison. Both reviewers asked for these to be documented rather than
  narrowed: keying the match on gitlab.project_path would drop self-hosted
  recognition exactly where it is least likely to be configured, since that
  key is optional and Init discards its load error.

- tracker_test: the milestone and shorthand rows are satisfied by the
  pre-existing "milestones" substring and glShorthandPattern arms, so they pass
  with onConfiguredHost deleted and overstated the table's coverage of the new
  predicate. They are now grouped and labeled as regression pins for those arms,
  and the two cases that do discriminate are added -- a scheme mismatch (claimed:
  only the host is compared) and a non-default port (not claimed when the ref
  omits it). Deleting `&& !t.onConfiguredHost(ref)` now fails 6 assertions, up
  from 4.

Validation: gofmt, git diff --check, go vet ./internal/gitlab/,
golangci-lint ./internal/gitlab/... (0 issues), go test ./internal/gitlab/...
and go test ./cmd/bd/ -run 'GitLab|Gitlab', plus the counterfactual run above.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Julian Knutsen <julianknutsen@users.noreply.github.com>
2026-09-26 04:15:47 -07:00

281 lines
8.9 KiB
Go

package gitlab
import (
"context"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/tracker"
"github.com/steveyegge/beads/internal/types"
)
func TestRegistered(t *testing.T) {
factory := tracker.Get("gitlab")
if factory == nil {
t.Fatal("gitlab tracker not registered")
}
tr := factory()
if tr.Name() != "gitlab" {
t.Errorf("Name() = %q, want %q", tr.Name(), "gitlab")
}
if tr.DisplayName() != "GitLab" {
t.Errorf("DisplayName() = %q, want %q", tr.DisplayName(), "GitLab")
}
if tr.ConfigPrefix() != "gitlab" {
t.Errorf("ConfigPrefix() = %q, want %q", tr.ConfigPrefix(), "gitlab")
}
}
func TestIsExternalRef(t *testing.T) {
tr := &Tracker{}
tests := []struct {
ref string
want bool
}{
{"https://gitlab.com/group/project/-/issues/42", true},
{"https://my-gitlab.example.com/team/repo/-/issues/123", true},
{"https://gitlab.com/group/project/-/work_items/42", true},
{"https://linear.app/team/issue/PROJ-123", false},
{"https://github.com/org/repo/issues/1", false},
{"", false},
// Shorthand format produced by BuildExternalRef
{"gitlab:681509", true},
{"gitlab:1", true},
{"gitlab:abc", false},
{"gitlab:123/extra", false},
{"gitlab:0", false},
}
for _, tt := range tests {
if got := tr.IsExternalRef(tt.ref); got != tt.want {
t.Errorf("IsExternalRef(%q) = %v, want %v", tt.ref, got, tt.want)
}
}
}
func TestIsExternalRefSelfHostedURL(t *testing.T) {
tr := &Tracker{client: NewClient("tok", "https://nova.teachx.ai", "42")}
tests := []struct {
ref string
want bool
}{
{"https://nova.teachx.ai/group/project/-/work_items/24", true},
{"https://nova.teachx.ai/group/project/-/issues/24", true},
{"https://NOVA.teachx.ai/group/project/-/issues/24", true},
// Scheme is not compared, only host: an http:// ref on an https://
// instance is claimed.
{"http://nova.teachx.ai/group/project/-/issues/24", true},
{"https://other.example.com/group/project/-/work_items/24", false},
{"https://github.com/org/repo/issues/1", false},
{"https://nova.teachx.ai/group/project/-/merge_requests/24", false},
{"", false},
// Regression pins for the pre-existing arms, not the host check: the
// milestone row is claimed by the "milestones" substring and the
// shorthand returns at glShorthandPattern, both before the host check
// runs. They still pass if onConfiguredHost is deleted.
{"https://nova.teachx.ai/group/project/-/milestones/5", true},
{"gitlab:24", true},
}
for _, tt := range tests {
if got := tr.IsExternalRef(tt.ref); got != tt.want {
t.Errorf("IsExternalRef(%q) = %v, want %v", tt.ref, got, tt.want)
}
}
// A GitLab served from a sub-path only claims URLs under that path.
sub := &Tracker{client: NewClient("tok", "https://corp.example.com/git", "42")}
if !sub.IsExternalRef("https://corp.example.com/git/g/p/-/issues/3") {
t.Error("sub-path host URL should be recognized")
}
if sub.IsExternalRef("https://corp.example.com/wiki/g/p/-/issues/3") {
t.Error("URL outside the configured sub-path should be rejected")
}
// Port is part of the host comparison, so gitlab.url has to name the host
// the way GitLab spells it in web_url. A non-default port must be present
// in the ref; conversely, a base that spells a port the web URLs omit
// matches nothing and the ref falls through to the legacy arms.
port := &Tracker{client: NewClient("tok", "https://gl.corp:8443", "42")}
if !port.IsExternalRef("https://gl.corp:8443/g/p/-/issues/3") {
t.Error("URL on the configured host:port should be recognized")
}
if port.IsExternalRef("https://gl.corp/g/p/-/issues/3") {
t.Error("URL omitting the configured non-default port should be rejected")
}
}
func TestExtractIdentifier(t *testing.T) {
tr := &Tracker{}
tests := []struct {
ref string
want string
}{
{"https://gitlab.com/group/project/-/issues/42", "42"},
{"https://gitlab.example.com/team/repo/-/issues/123", "123"},
{"https://gitlab.com/group/project/-/work_items/42", "42"},
{"https://gitlab.com/group/project/-/milestones/4", "milestone:4"},
{"not-a-url", ""},
// Shorthand format
{"gitlab:681509", "681509"},
{"gitlab:1", "1"},
{"gitlab:abc", ""},
}
for _, tt := range tests {
if got := tr.ExtractIdentifier(tt.ref); got != tt.want {
t.Errorf("ExtractIdentifier(%q) = %q, want %q", tt.ref, got, tt.want)
}
}
}
func TestBuildExternalRef(t *testing.T) {
tr := &Tracker{}
ti := &tracker.TrackerIssue{
URL: "https://gitlab.com/group/project/-/issues/42",
Identifier: "42",
}
ref := tr.BuildExternalRef(ti)
if ref != ti.URL {
t.Errorf("BuildExternalRef() = %q, want %q", ref, ti.URL)
}
}
func TestFieldMapperStatus(t *testing.T) {
m := &gitlabFieldMapper{config: DefaultMappingConfig()}
if got := m.StatusToBeads("opened"); got != types.StatusOpen {
t.Errorf("StatusToBeads(opened) = %q, want %q", got, types.StatusOpen)
}
if got := m.StatusToBeads("closed"); got != types.StatusClosed {
t.Errorf("StatusToBeads(closed) = %q, want %q", got, types.StatusClosed)
}
if got := m.StatusToBeads("reopened"); got != types.StatusOpen {
t.Errorf("StatusToBeads(reopened) = %q, want %q", got, types.StatusOpen)
}
}
func TestFieldMapperPriority(t *testing.T) {
m := &gitlabFieldMapper{config: DefaultMappingConfig()}
if got := m.PriorityToBeads("critical"); got != 0 {
t.Errorf("PriorityToBeads(critical) = %d, want 0", got)
}
if got := m.PriorityToBeads("high"); got != 1 {
t.Errorf("PriorityToBeads(high) = %d, want 1", got)
}
if got := m.PriorityToBeads("low"); got != 3 {
t.Errorf("PriorityToBeads(low) = %d, want 3", got)
}
}
func TestGitLabToTrackerIssue(t *testing.T) {
now := time.Now()
gl := &Issue{
ID: 100,
IID: 42,
Title: "Fix pipeline",
Description: "CI is broken",
State: "opened",
WebURL: "https://gitlab.com/group/project/-/issues/42",
Labels: []string{"bug", "priority::high"},
CreatedAt: &now,
UpdatedAt: &now,
Assignee: &User{ID: 5, Username: "bob"},
}
ti := gitlabToTrackerIssue(gl)
if ti.ID != "100" {
t.Errorf("ID = %q, want %q", ti.ID, "100")
}
if ti.Identifier != "42" {
t.Errorf("Identifier = %q, want %q", ti.Identifier, "42")
}
if ti.Assignee != "bob" {
t.Errorf("Assignee = %q, want %q", ti.Assignee, "bob")
}
if ti.AssigneeID != strconv.Itoa(5) {
t.Errorf("AssigneeID = %q, want %q", ti.AssigneeID, "5")
}
if ti.Raw != gl {
t.Error("Raw should reference original gitlab.Issue")
}
if len(ti.Labels) != 2 {
t.Errorf("Labels count = %d, want 2", len(ti.Labels))
}
}
// TestGetConfig_YamlOnlyKeyBypassesStore verifies that yaml-only keys
// (e.g. gitlab.token) bypass the Dolt store entirely. A nil store proves
// the store is never dereferenced; before the fix this would panic.
func TestGetConfig_YamlOnlyKeyBypassesStore(t *testing.T) {
ctx := context.Background()
tr := &Tracker{store: nil}
t.Run("falls back to env var", func(t *testing.T) {
t.Setenv("GITLAB_TOKEN", "env-token-value")
got, err := tr.getConfig(ctx, "gitlab.token", "GITLAB_TOKEN")
if err != nil {
t.Fatalf("getConfig returned error: %v", err)
}
if got != "env-token-value" {
t.Errorf("getConfig(gitlab.token) = %q, want %q", got, "env-token-value")
}
})
t.Run("returns empty when no value is set", func(t *testing.T) {
t.Setenv("GITLAB_TOKEN", "")
got, err := tr.getConfig(ctx, "gitlab.token", "GITLAB_TOKEN")
if err != nil {
t.Fatalf("getConfig returned error: %v", err)
}
if got != "" {
t.Errorf("getConfig(gitlab.token) = %q, want empty", got)
}
})
}
// TestGetConfig_YamlOnlyKeyReadsFromYaml verifies that gitlab.token is
// read from .beads/config.yaml when set there, without depending on the
// GITLAB_TOKEN env var.
func TestGetConfig_YamlOnlyKeyReadsFromYaml(t *testing.T) {
const wantToken = "yaml-config-token-value"
tmpDir := t.TempDir()
beadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(beadsDir, 0o750); err != nil {
t.Fatalf("mkdir .beads: %v", err)
}
yamlBody := "gitlab.token: \"" + wantToken + "\"\n"
if err := os.WriteFile(filepath.Join(beadsDir, "config.yaml"), []byte(yamlBody), 0o600); err != nil {
t.Fatalf("write config.yaml: %v", err)
}
t.Setenv("GITLAB_TOKEN", "")
t.Setenv("BEADS_DIR", "")
t.Setenv("BEADS_TEST_IGNORE_REPO_CONFIG", "1")
t.Setenv("HOME", filepath.Join(tmpDir, "home"))
t.Setenv("XDG_CONFIG_HOME", filepath.Join(tmpDir, "xdg"))
t.Chdir(tmpDir)
config.ResetForTesting()
t.Cleanup(config.ResetForTesting)
if err := config.Initialize(); err != nil {
t.Fatalf("config.Initialize: %v", err)
}
if got := config.GetString("gitlab.token"); got != wantToken {
t.Fatalf("config.GetString(gitlab.token) = %q, want %q (yaml not loaded?)", got, wantToken)
}
tr := &Tracker{store: nil}
got, err := tr.getConfig(context.Background(), "gitlab.token", "GITLAB_TOKEN")
if err != nil {
t.Fatalf("getConfig returned error: %v", err)
}
if got != wantToken {
t.Errorf("getConfig(gitlab.token) = %q, want %q (yaml value)", got, wantToken)
}
}