Skip to content

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

Go

MUL-9150 fix(daemon): allow repo checkout across URL forms of a registered repo (#10490)

nickend13fd90a357a
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 150e84e6db..9d214774d4 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -11,9 +11,11 @@ import (
"math/rand"
"net"
"net/http"
+ "net/url"
"os"
"os/exec"
"path/filepath"
+ "regexp"
"runtime"
"sort"
"strconv"
@@ -3277,20 +3279,95 @@ func repoAllowlist(repos []RepoData) map[string]struct{} {
return allowed
}
-func (d *Daemon) workspaceRepoAllowed(workspaceID, repoURL string) bool {
+// defaultGitPorts are the ports implied when a URL form omits one. A port
+// that differs from the scheme default can name a different server, so it
+// stays part of the identity.
+var defaultGitPorts = map[string]string{
+ "http": "80", "https": "443", "ssh": "22", "git": "9418",
+}
+
+// repoIdentity is the protocol-agnostic host+path identity of a clone URL,
+// so http, ssh, and scp-shorthand forms of the same repository compare
+// equal. Hosts are case-insensitive; repository paths are not guaranteed to
+// be, so path casing is preserved. It mirrors repositoryIdentity in
+// packages/views/settings/components/repositories-section.tsx — the two must
+// not drift, or a repo the UI refuses to add as a duplicate could still
+// bypass (or be rejected by) the daemon allowlist. An unparseable URL keeps
+// no identity and only ever matches by exact string.
+func repoIdentity(rawURL string) string {
+ value := strings.TrimSpace(rawURL)
+ if value == "" {
+ return ""
+ }
+
+ host := ""
+ path := ""
+ if !strings.Contains(value, "://") {
+ if m := scpLikeURL.FindStringSubmatch(value); m != nil {
+ host = m[1]
+ path = m[2]
+ }
+ }
+ if host == "" {
+ parsed, err := url.Parse(value)
+ if err != nil || parsed.Hostname() == "" {
+ return ""
+ }
+ host = parsed.Hostname()
+ if port := parsed.Port(); port != "" && port != defaultGitPorts[parsed.Scheme] {
+ host = host + ":" + port
+ }
+ path = parsed.Path
+ }
+
+ normalizedPath := strings.Trim(path, "/")
+ if len(normalizedPath) > 4 && strings.EqualFold(normalizedPath[len(normalizedPath)-4:], ".git") {
+ normalizedPath = normalizedPath[:len(normalizedPath)-4]
+ }
+ if normalizedPath == "" {
+ return ""
+ }
+ return strings.ToLower(host) + "/" + normalizedPath
+}
+
+var scpLikeURL = regexp.MustCompile(`^(?:[^@\s/]+@)?([^:\s/]+):(.+)$`)
+
+// resolveWorkspaceRepoURL returns the registered URL to use for cache and
+// checkout operations. Exact matches take precedence across both sources;
+// aliases prefer workspace bindings, then task repositories.
+func (d *Daemon) resolveWorkspaceRepoURL(workspaceID, repoURL string) string {
d.mu.Lock()
defer d.mu.Unlock()
ws, ok := d.workspaces[workspaceID]
if !ok {
- return false
+ return ""
}
if _, allowed := ws.allowedRepoURLs[repoURL]; allowed {
- return true
+ return repoURL
}
if _, allowed := ws.taskRepoURLs[repoURL]; allowed {
- return true
+ return repoURL
}
- return false
+ identity := repoIdentity(repoURL)
+ if registeredURL := repoURLForIdentity(ws.allowedRepoURLs, identity); registeredURL != "" {
+ return registeredURL
+ }
+ return repoURLForIdentity(ws.taskRepoURLs, identity)
+}
+
+// Legacy bindings and task repositories can contain equivalent URLs. Choose
+// lexically within a source so map iteration cannot change the remote or ref.
+func repoURLForIdentity[V any](repos map[string]V, identity string) string {
+ if identity == "" {
+ return ""
+ }
+ match := ""
+ for url := range repos {
+ if repoIdentity(url) == identity && (match == "" || url < match) {
+ match = url
+ }
+ }
+ return match
}
// repoBarePathIsLive reports whether some watched workspace still claims the
@@ -3301,7 +3378,7 @@ func (d *Daemon) workspaceRepoAllowed(workspaceID, repoURL string) bool {
// stale while the caller runs git and filesystem work on each repo in turn,
// which is exactly the window in which a workspace can re-attach one.
//
-// It mirrors workspaceRepoAllowed by unioning both sources: allowedRepoURLs
+// It mirrors resolveWorkspaceRepoURL by unioning both sources: allowedRepoURLs
// (workspace-level bindings) and taskRepoURLs (project repos the server
// surfaced through a task claim, which never appear in GetWorkspaceRepos).
// Missing the second set would make the GC evict repos that tasks actively
@@ -3452,7 +3529,13 @@ func (d *Daemon) taskRepoDefaultRef(workspaceID, taskID, repoURL string) string
if !ok || ws.taskRepoRefs == nil {
return ""
}
- return strings.TrimSpace(ws.taskRepoRefs[taskID][repoURL])
+ refs := ws.taskRepoRefs[taskID]
+ if ref, ok := refs[repoURL]; ok {
+ return strings.TrimSpace(ref)
+ }
+ // A workspace binding and the current task can name the same repository
+ // differently. Resolving the cache URL must not lose the task's ref.
+ return strings.TrimSpace(refs[repoURLForIdentity(refs, repoIdentity(repoURL))])
}
func (d *Daemon) clearTaskRepoRefs(workspaceID, taskID string) {
@@ -3946,9 +4029,11 @@ func (d *Daemon) convergeWorkspaceRuntimesToZero(ctx context.Context, workspaceI
return nil
}
-func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL string) error {
+// ensureRepoReady returns the registered URL after refreshing authorization
+// and preparing its cache. Callers must carry that URL through the checkout.
+func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL string) (string, error) {
if d.repoCache == nil {
- return fmt.Errorf("repo cache not initialized")
+ return "", fmt.Errorf("repo cache not initialized")
}
repoURL = strings.TrimSpace(repoURL)
@@ -3957,7 +4042,7 @@ func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL strin
ws, ok := d.workspaces[workspaceID]
d.mu.Unlock()
if !ok {
- return fmt.Errorf("workspace is not watched by this daemon: %s", workspaceID)
+ return "", fmt.Errorf("workspace is not watched by this daemon: %s", workspaceID)
}
// Record whether the cache already had this repo before we took the
@@ -3974,44 +4059,47 @@ func (d *Daemon) ensureRepoReady(ctx context.Context, workspaceID, repoURL strin
// a sibling goroutine on a concurrent cold-miss already refreshed
// and populated the cache. We can skip the duplicate refresh — the
// sibling's refresh is fresh enough for our gate read.
- cacheHitOnEntry := d.workspaceRepoAllowed(workspaceID, repoURL) && d.repoCache.Lookup(workspaceID, repoURL) != ""
+ registeredURL := d.resolveWorkspaceRepoURL(workspaceID, repoURL)
+ cacheHitOnEntry := registeredURL != "" && d.repoCache.Lookup(workspaceID, registeredURL) != ""
if err := ws.repoRefreshMu.Lock(ctx); err != nil {
- return err
+ return "", err
}
defer ws.repoRefreshMu.Unlock()
- if !cacheHitOnEntry && d.workspaceRepoAllowed(workspaceID, repoURL) && d.repoCache.Lookup(workspaceID, repoURL) != "" {
- return nil
+ registeredURL = d.resolveWorkspaceRepoURL(workspaceID, repoURL)
+ if !cacheHitOnEntry && registeredURL != "" && d.repoCache.Lookup(workspaceID, registeredURL) != "" {
+ return registeredURL, nil
}
resp, err := d.refreshWorkspaceRepos(ctx, workspaceID)
if err != nil {
- return fmt.Errorf("refresh workspace repos: %w", err)
+ return "", fmt.Errorf("refresh workspace repos: %w", err)
}
- if !d.workspaceRepoAllowed(workspaceID, repoURL) {
- return ErrRepoNotConfigured
+ registeredURL = d.resolveWorkspaceRepoURL(workspaceID, repoURL)
+ if registeredURL == "" {
+ return "", ErrRepoNotConfigured
}
- if d.repoCache.Lookup(workspaceID, repoURL) != "" {
- return nil
+ if d.repoCache.Lookup(workspaceID, registeredURL) != "" {
+ return registeredURL, nil
}
syncErr := d.syncWorkspaceReposContext(ctx, workspaceID, resp.Repos)
if err := ctx.Err(); err != nil {
- return context.Cause(ctx)
+ return "", context.Cause(ctx)
}
- if d.repoCache.Lookup(workspaceID, repoURL) != "" {
- return nil
+ if d.repoCache.Lookup(workspaceID, registeredURL) != "" {
+ return registeredURL, nil
}
if syncErr != nil {
- return fmt.Errorf("repo is configured but not synced: %w", syncErr)
+ return "", fmt.Errorf("repo is configured but not synced: %w", syncErr)
}
- return fmt.Errorf("repo is configured but not synced")
+ return "", fmt.Errorf("repo is configured but not synced")
}
// DefaultTokenRenewalInterval is how often the daemon asks the server to
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index e0f57cf1c4..ef67a2ef67 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -4946,7 +4946,7 @@ func TestEnsureRepoReadyCachedRepoStillRefreshesSettings(t *testing.T) {
t.Fatalf("precondition: expected co-author hook enabled before checkout")
}
- if err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {
+ if _, err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {
t.Fatalf("ensureRepoReady: %v", err)
}
if got := refreshCalls.Load(); got != 1 {
@@ -4980,7 +4980,7 @@ func TestEnsureRepoReadyTrimsURL(t *testing.T) {
d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "v1", []RepoData{{URL: sourceRepo}}, nil)
// URL with trailing whitespace should still resolve to the cached repo.
- if err := d.ensureRepoReady(context.Background(), "ws-1", " "+sourceRepo+" "); err != nil {
+ if _, err := d.ensureRepoReady(context.Background(), "ws-1", " "+sourceRepo+" "); err != nil {
t.Fatalf("ensureRepoReady with padded URL: %v", err)
}
// Even on cache hit we refresh settings once so toggle flips feel live.
@@ -5008,7 +5008,7 @@ func TestEnsureRepoReadyRefreshesOnMiss(t *testing.T) {
})
d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)
- if err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {
+ if _, err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {
t.Fatalf("ensureRepoReady: %v", err)
}
if got := refreshCalls.Load(); got != 1 {
@@ -5057,11 +5057,11 @@ func TestRegisterTaskReposAllowsProjectOnlyURL(t *testing.T) {
t.Fatalf("expected repo to be cached after registerTaskRepos, but Lookup returned empty")
}
- if !d.workspaceRepoAllowed("ws-1", sourceRepo) {
- t.Fatal("expected project repo to pass workspaceRepoAllowed")
+ if d.resolveWorkspaceRepoURL("ws-1", sourceRepo) != sourceRepo {
+ t.Fatal("expected project repo to resolve to its registered URL")
}
- if err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {
+ if _, err := d.ensureRepoReady(context.Background(), "ws-1", sourceRepo); err != nil {
t.Fatalf("ensureRepoReady: %v", err)
}
// ensureRepoReady refreshes settings on every call (RFC MUL-2414 §4.8; PR
@@ -5101,7 +5101,7 @@ func TestRegisterTaskReposSurvivesWorkspaceRefresh(t *testing.T) {
t.Fatalf("refreshWorkspaceRepos: %v", err)
}
- if !d.workspaceRepoAllowed("ws-1", sourceRepo) {
+ if d.resolveWorkspaceRepoURL("ws-1", sourceRepo) != sourceRepo {
t.Fatal("project repo URL was wiped by workspace refresh")
}
}
@@ -5151,7 +5151,7 @@ func TestEnsureRepoReadyReturnsNotConfigured(t *testing.T) {
})
d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)
- err := d.ensureRepoReady(context.Background(), "ws-1", "[email protected]:team/api.git")
+ _, err := d.ensureRepoReady(context.Background(), "ws-1", "[email protected]:team/api.git")
if !errors.Is(err, ErrRepoNotConfigured) {
t.Fatalf("expected ErrRepoNotConfigured, got %v", err)
}
@@ -5170,7 +5170,7 @@ func TestEnsureRepoReadyReportsSyncFailure(t *testing.T) {
})
d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)
- err := d.ensureRepoReady(context.Background(), "ws-1", missingRepo)
+ _, err := d.ensureRepoReady(context.Background(), "ws-1", missingRepo)
if err == nil || !strings.Contains(err.Error(), "repo is configured but not synced: git clone --bare:") {
t.Fatalf("expected sync failure error with git's output, got %v", err)
}
@@ -5229,7 +5229,7 @@ func TestEnsureRepoReadyKeepsSyncFailureDespiteConcurrentSuccess(t *testing.T) {
d.repoCache = cache
d.workspaces["ws-1"] = newWorkspaceState("ws-1", nil, "", nil, nil)
- err := d.ensureRepoReady(context.Background(), "ws-1", repoURL)
+ _, err := d.ensureRepoReady(context.Background(), "ws-1", repoURL)
if !cache.raced {
t.Fatal("test did not exercise the concurrent sync")
}
@@ -5294,7 +5294,8 @@ func TestEnsureRepoReadyConcurrentMissRefreshesOnce(t *testing.T) {
go func() {
defer wg.Done()
waitCtx := &repoRefreshWaitContext{Context: ctx, waiting: waiting}
- errCh <- d.ensureRepoReady(waitCtx, "ws-1", sourceRepo)
+ _, err := d.ensureRepoReady(waitCtx, "ws-1", sourceRepo)
+ errCh <- err
}()
}
for range concurrency {
diff --git a/server/internal/daemon/health.go b/server/internal/daemon/health.go
index 43b6abf691..2b33c1543f 100644
--- a/server/internal/daemon/health.go
+++ b/server/internal/daemon/health.go
@@ -534,7 +534,8 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {
return
}
- if err := d.ensureRepoReady(r.Context(), req.WorkspaceID, req.URL); err != nil {
+ registeredURL, err := d.ensureRepoReady(r.Context(), req.WorkspaceID, req.URL)
+ if err != nil {
if r.Context().Err() != nil {
d.logger.Debug("repo checkout readiness cancelled", "url", req.URL, "error", err)
return
@@ -547,6 +548,7 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {
http.Error(w, err.Error(), statusCode)
return
}
+ req.URL = registeredURL
req.WorkDir = checkoutWorkDirOutsideOwnCheckout(r.Context(), taskRoot, authorizedWorkDir, d.repoCache.Lookup(req.WorkspaceID, req.URL))
if req.WorkDir != authorizedWorkDir {
@@ -577,7 +579,6 @@ func (d *Daemon) repoCheckoutHandler() http.HandlerFunc {
params.LockWaitTimeout = repoCheckoutLockWaitTimeout
}
var result *repocache.WorktreeResult
- var err error
if cache, ok := d.repoCache.(interface {
CreateWorktreeContext(context.Context, repocache.WorktreeParams) (*repocache.WorktreeResult, error)
}); ok {
diff --git a/server/internal/daemon/repo_checkout_url_test.go b/server/internal/daemon/repo_checkout_url_test.go
new file mode 100644
index 0000000000..6330bc939a
--- /dev/null
+++ b/server/internal/daemon/repo_checkout_url_test.go
@@ -0,0 +1,116 @@
+package daemon
+
+import (
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/daemon/repocache"
+)
+
+func TestRepoCheckoutEquivalentURLsUseRegisteredRepo(t *testing.T) {
+ const scpURL = "[email protected]:group/project.git"
+ const httpURL = "http://gitlab.example.com/group/project.git"
+ const httpsURL = "https://gitlab.example.com/group/project.git"
+ const sshPortURL = "ssh://[email protected]:22/group/project.git"
+ const httpsPortURL = "https://gitlab.example.com:443/group/project.git"
+ const wsID = "ws-checkout"
+
+ // Keep the reported URLs in the request and cache, but direct Git to a
+ // local fixture so these tests require neither network nor credentials.
+ config := filepath.Join(t.TempDir(), "gitconfig")
+ if err := os.WriteFile(config, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("GIT_CONFIG_GLOBAL", config)
+ t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
+ t.Setenv("GIT_TERMINAL_PROMPT", "0")
+ source := createDaemonTestRepo(t)
+ git := func(args ...string) string {
+ t.Helper()
+ out, err := exec.Command("git", args...).CombinedOutput()
+ if err != nil {
+ t.Fatalf("git %v: %s: %v", args, out, err)
+ }
+ return strings.TrimSpace(string(out))
+ }
+ git("-C", source, "branch", "-M", "main")
+ git("-C", source, "checkout", "-b", "release/v2")
+ git("-C", source, "-c", "user.name=test", "-c", "[email protected]", "commit", "--allow-empty", "-m", "release-only commit")
+ releaseSHA := git("-C", source, "rev-parse", "HEAD")
+ git("-C", source, "checkout", "main")
+ mainSHA := git("-C", source, "rev-parse", "HEAD")
+ for _, raw := range []string{scpURL, httpURL, httpsURL, sshPortURL, httpsPortURL} {
+ git("config", "--file", config, "--add", "url."+source+".insteadOf", raw)
+ }
+
+ for _, tc := range []struct {
+ name, registered, requested, projectURL, explicitRef string
+ cold, isolated bool
+ }{
+ {name: "reported HTTP input", registered: scpURL, requested: httpURL},
+ {name: "HTTPS input", registered: scpURL, requested: httpsURL, cold: true},
+ {name: "project ref through HTTP alias", registered: scpURL, requested: httpURL, projectURL: scpURL},
+ {name: "explicit ref overrides project", registered: scpURL, requested: httpURL, projectURL: scpURL, explicitRef: "main"},
+ {name: "registered default port with cold cache", registered: sshPortURL, requested: httpsURL, cold: true},
+ {name: "requested default port with cold cache", registered: scpURL, requested: httpsPortURL, cold: true},
+ {name: "registered HTTPS port with warm cache", registered: httpsPortURL, requested: scpURL},
+ {name: "workspace and project use different forms", registered: httpsURL, requested: httpsURL, projectURL: scpURL},
+ {name: "isolated checkout retains registered origin", registered: scpURL, requested: httpURL, projectURL: scpURL, isolated: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cache := repocache.New(t.TempDir(), slog.Default())
+ workDir := t.TempDir()
+ d := newRepoCheckoutTestDaemon(t, wsID, tc.registered, workDir, cache)
+ t.Cleanup(d.waitBackgroundSyncs)
+ if !tc.cold {
+ if err := cache.Sync(wsID, []repocache.RepoInfo{{URL: tc.registered}}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if tc.projectURL != "" {
+ d.registerTaskRepos(wsID, "task-1", []RepoData{{URL: tc.projectURL, Ref: "release/v2"}})
+ d.waitBackgroundSyncs()
+ }
+ mode := ""
+ if tc.isolated {
+ mode = repoCheckoutModeIsolated
+ }
+ body, err := json.Marshal(repoCheckoutRequest{
+ URL: tc.requested, WorkspaceID: wsID, WorkDir: workDir,
+ TaskID: "task-1", Ref: tc.explicitRef, CheckoutMode: mode,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec := httptest.NewRecorder()
+ d.repoCheckoutHandler().ServeHTTP(rec, authorizedRepoCheckoutRequest(strings.NewReader(string(body))))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("checkout HTTP %d: %s", rec.Code, rec.Body.String())
+ }
+ var result repocache.WorktreeResult
+ if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
+ t.Fatal(err)
+ }
+ wantSHA := mainSHA
+ if tc.projectURL != "" && tc.explicitRef == "" {
+ wantSHA = releaseSHA
+ }
+ if got := git("-C", result.Path, "rev-parse", "HEAD"); got != wantSHA {
+ t.Errorf("checkout HEAD = %s, want %s", got, wantSHA)
+ }
+ if got := git("-C", result.Path, "config", "--get", "remote.origin.url"); got != tc.registered {
+ t.Errorf("checkout origin = %q, want registered URL %q", got, tc.registered)
+ }
+ if !d.repoBarePathIsLive(cache.BarePath(wsID, tc.registered)) {
+ t.Error("registered cache must remain live for GC")
+ }
+ })
+ }
+}
diff --git a/server/internal/daemon/workspace_repo_allowlist_test.go b/server/internal/daemon/workspace_repo_allowlist_test.go
new file mode 100644
index 0000000000..07c47c5aaa
--- /dev/null
+++ b/server/internal/daemon/workspace_repo_allowlist_test.go
@@ -0,0 +1,116 @@
+package daemon
+
+import (
+ "testing"
+)
+
+// TestResolveWorkspaceRepoURLMatchesAcrossURLForms pins the normalization that
+// lets a checkout request in one URL form match a repo registered in another
+// (http vs ssh vs scp shorthand). Agents routinely paste the HTTP address
+// from the Git host's web UI while the workspace registers the SSH form.
+func TestResolveWorkspaceRepoURLMatchesAcrossURLForms(t *testing.T) {
+ d := newGCTestDaemon(t, nil)
+
+ const wsID = "11111111-1111-1111-1111-111111111111"
+ const registered = "[email protected]:group/project.git"
+ const taskURL = "ssh://[email protected]:2222/group/task-only.git"
+ d.mu.Lock()
+ d.workspaces[wsID] = &workspaceState{
+ workspaceID: wsID,
+ allowedRepoURLs: map[string]struct{}{
+ registered: {},
+ "/local/repo": {},
+ "https://bad%host/repo": {},
+ },
+ taskRepoURLs: map[string]struct{}{
+ taskURL: {},
+ },
+ }
+ d.mu.Unlock()
+
+ for _, tc := range []struct {
+ name string
+ url string
+ want string
+ }{
+ {"exact registered form", registered, registered},
+ {"https form of registered ssh repo", "https://gitlab.example.com/group/project.git", registered},
+ {"http form of registered ssh repo", "http://gitlab.example.com/group/project.git", registered},
+ {"ssh form of registered scp shorthand", "ssh://[email protected]/group/project.git", registered},
+ {"trailing slash and .git differences", "https://gitlab.example.com/group/project/", registered},
+ {"host and suffix case", "https://GITLAB.EXAMPLE.COM/group/project.GIT", registered},
+ {"default http port", "http://gitlab.example.com:80/group/project.git", registered},
+ {"default https port", "https://gitlab.example.com:443/group/project.git", registered},
+ {"default ssh port", "ssh://[email protected]:22/group/project.git", registered},
+ {"default git port", "git://gitlab.example.com:9418/group/project.git", registered},
+ {"exact task repo form", taskURL, taskURL},
+ {"https form of task repo keeps non-default port", "https://gitlab.example.com:2222/group/task-only.git", taskURL},
+ {"same host path without the task repo's port", "https://gitlab.example.com/group/task-only.git", ""},
+ {"non-default https port", "https://gitlab.example.com:8443/group/project.git", ""},
+ {"http using https port is not default", "http://gitlab.example.com:443/group/project.git", ""},
+ {"different repo on the same host", "https://gitlab.example.com/group/other.git", ""},
+ {"different host", "https://other.example.com/group/project.git", ""},
+ {"different path case", "https://gitlab.example.com/group/Project.git", ""},
+ {"local path exact match", "/local/repo", "/local/repo"},
+ {"local path stays exact only", "/local/repo.git", ""},
+ {"malformed URL exact match", "https://bad%host/repo", "https://bad%host/repo"},
+ {"malformed URL stays exact only", "https://bad%host/repo.git", ""},
+ {"empty URL", "", ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got := d.resolveWorkspaceRepoURL(wsID, tc.url)
+ if got != tc.want {
+ t.Errorf("resolveWorkspaceRepoURL(%q) = %q, want %q", tc.url, got, tc.want)
+ }
+ })
+ }
+
+ if d.resolveWorkspaceRepoURL("22222222-2222-2222-2222-222222222222", registered) != "" {
+ t.Error("an unwatched workspace must not allow the repo")
+ }
+}
+
+func TestResolveWorkspaceRepoURLPrefersExactThenStableSource(t *testing.T) {
+ d := newGCTestDaemon(t, nil)
+ const workspaceURL = "https://gitlab.example.com/group/project.git"
+ const taskURL = "[email protected]:group/project.git"
+ ws := newWorkspaceState("ws-1", nil, "", []RepoData{{URL: workspaceURL}}, nil)
+ ws.taskRepoURLs = map[string]struct{}{taskURL: {}}
+ d.workspaces["ws-1"] = ws
+ if got := d.resolveWorkspaceRepoURL("ws-1", taskURL); got != taskURL {
+ t.Fatalf("exact task URL = %q, want %q", got, taskURL)
+ }
+ const alias = "ssh://[email protected]/group/project.git"
+ if got := d.resolveWorkspaceRepoURL("ws-1", alias); got != workspaceURL {
+ t.Fatalf("alias = %q, want workspace binding %q", got, workspaceURL)
+ }
+ // Old workspace data can contain aliases that the settings UI now dedupes.
+ ws.allowedRepoURLs[taskURL] = struct{}{}
+ for range 50 {
+ if got := d.resolveWorkspaceRepoURL("ws-1", alias); got != taskURL {
+ t.Fatalf("ambiguous alias = %q, want lexically first URL %q", got, taskURL)
+ }
+ }
+}
+
+func TestTaskRepoDefaultRefMatchesOnlyCurrentTaskAliases(t *testing.T) {
+ d := newGCTestDaemon(t, nil)
+ const scpURL = "[email protected]:group/project.git"
+ const httpsURL = "https://gitlab.example.com/group/project.git"
+ const alias = "ssh://[email protected]:22/group/project.git"
+ d.workspaces["ws-1"] = &workspaceState{taskRepoRefs: map[string]map[string]string{
+ "task-a": {scpURL: "release/a", httpsURL: "release/https"},
+ "task-b": {scpURL: "release/b"},
+ }}
+ for _, tc := range []struct{ task, url, want string }{
+ {"task-a", httpsURL, "release/https"},
+ {"task-a", alias, "release/a"},
+ {"task-b", httpsURL, "release/b"},
+ {"task-c", httpsURL, ""},
+ {"task-a", "https://gitlab.example.com:8443/group/project.git", ""},
+ } {
+ if got := d.taskRepoDefaultRef("ws-1", tc.task, tc.url); got != tc.want {
+ t.Errorf("taskRepoDefaultRef(%q, %q) = %q, want %q", tc.task, tc.url, got, tc.want)
+ }
+ }
+}