Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon/repocache): make bare repo cache keys collision-resistant
L.Amar9c177562e216
diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex d1c91ce2fe..44749473d7 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -5,6 +5,7 @@ package repocacheimport ("fmt""log/slog"+ "net/url""os""os/exec""path/filepath"@@ -125,30 +126,79 @@ func (c *Cache) Fetch(barePath string) error {return gitFetch(barePath)}-// bareDirName derives a directory name from a repo URL.-// e.g. "https://github.com/org/my-repo.git" → "my-repo.git"-func bareDirName(url string) string {- url = strings.TrimRight(url, "/")- name := url- if i := strings.LastIndex(url, "/"); i >= 0 {- name = url[i+1:]- }- // Handle SSH-style "host:org/repo".- if i := strings.LastIndex(name, ":"); i >= 0 {- name = name[i+1:]- if j := strings.LastIndex(name, "/"); j >= 0 {- name = name[j+1:]+// bareDirName returns a filesystem-safe, collision-free directory name for+// the bare clone of rawURL. The name is built from the host plus each+// path segment, joined by '+'. '+' is disallowed in GitHub and GitLab+// path segments, so two URLs produce the same name only if they point at+// the same repository on the same host.+//+// Examples:+//+// https://github.com/org/my-repo.git -> github.com+org+my-repo.git+// [email protected]:org/my-repo -> github.com+org+my-repo.git+// [email protected]:foo/bar-baz.git -> github.com+foo+bar-baz.git+// [email protected]:foo-bar/baz.git -> github.com+foo-bar+baz.git+// [email protected]:org/repo.git -> github.com+org+repo.git+// [email protected]:org/repo.git -> gitlab.example.com+org+repo.git+// ssh://[email protected]:22/g/s/r.git -> gitlab.example.com%3A22+g+s+r.git+// [email protected]:org/repo.git -> gitlab.example.com-22+org+repo.git+// my-repo -> my-repo.git (bare name fallback)+func bareDirName(rawURL string) string {+ rawURL = strings.TrimRight(rawURL, "/")++ host, path := splitHostAndPath(rawURL)+ host = strings.ToLower(strings.TrimSpace(host))+ // Encode ':' as '%3A' so host:port is lossless. A naive ':'->'-' rewrite+ // would collapse `gitlab.example.com:22` onto a literal hostname+ // `gitlab.example.com-22`, reintroducing the silent wrong-remote class+ // this function exists to prevent. '%' is forbidden in valid hostnames+ // (RFC 952 / RFC 1123), and in GitHub/GitLab path segments, so the+ // encoded marker can never come from a legal input.+ host = strings.ReplaceAll(host, ":", "%3A")++ var parts []string+ if host != "" {+ parts = append(parts, host)+ }+ for _, seg := range strings.Split(path, "/") {+ if seg != "" {+ parts = append(parts, seg)}}++ name := strings.Join(parts, "+")if !strings.HasSuffix(name, ".git") {name += ".git"}- if name == ".git" {+ if name == "" || name == ".git" {name = "repo.git"}return name}+// splitHostAndPath extracts the host and path-with-namespace from the+// supported git URL forms:+//+// - URL form (ssh://user@host[:port]/path, https://host/path) — returns+// u.Host verbatim (may include :port) and u.Path without the leading slash.+// - scp-style ([user@]host:path) — splits on the first ':' after the+// optional 'user@'.+// - Anything else (bare repo names, absolute filesystem paths) — returns+// an empty host and the raw input as the path.+func splitHostAndPath(rawURL string) (host, path string) {+ if u, err := url.Parse(rawURL); err == nil && u.Scheme != "" && u.Host != "" {+ return u.Host, strings.TrimPrefix(u.Path, "/")+ }+ s := rawURL+ if i := strings.Index(s, "@"); i >= 0 {+ s = s[i+1:]+ }+ if i := strings.Index(s, ":"); i >= 0 {+ return s[:i], s[i+1:]+ }+ return "", s+}+// isBareRepo checks if a path looks like a bare git repository.func isBareRepo(path string) bool {// A bare repo has a HEAD file at the root.diff --git a/server/internal/daemon/repocache/cache_test.go b/server/internal/daemon/repocache/cache_test.goindex 59e09cf6ca..9b16e48a88 100644--- a/server/internal/daemon/repocache/cache_test.go+++ b/server/internal/daemon/repocache/cache_test.go@@ -51,11 +51,16 @@ func TestBareDirName(t *testing.T) {tests := []struct {input, want string}{- {"https://github.com/org/my-repo.git", "my-repo.git"},- {"https://github.com/org/my-repo", "my-repo.git"},- {"[email protected]:org/my-repo.git", "my-repo.git"},- {"[email protected]:org/my-repo", "my-repo.git"},- {"https://github.com/org/repo/", "repo.git"},+ {"https://github.com/org/my-repo.git", "github.com+org+my-repo.git"},+ {"https://github.com/org/my-repo", "github.com+org+my-repo.git"},+ {"[email protected]:org/my-repo.git", "github.com+org+my-repo.git"},+ {"[email protected]:org/my-repo", "github.com+org+my-repo.git"},+ {"https://github.com/org/repo/", "github.com+org+repo.git"},+ {"ssh://[email protected]:22/group/sub/repo.git", "gitlab.example.com%3A22+group+sub+repo.git"},+ // Basename collision: two repos sharing the basename must produce+ // distinct dirs (the original bug).+ {"ssh://[email protected]:22/relisty/app.git", "gitlab.example.com%3A22+relisty+app.git"},+ {"ssh://[email protected]:22/listbridge/app.git", "gitlab.example.com%3A22+listbridge+app.git"},{"my-repo", "my-repo.git"},{"", "repo.git"},}@@ -66,6 +71,67 @@ func TestBareDirName(t *testing.T) {}}+// TestBareDirNameDistinctsSegmentBoundaryColliders covers the collision class+// that a naive path-flattening-with-dashes scheme would miss: two repos whose+// path segments differ only at a segment boundary flatten to the same string+// once slashes become dashes. The '+' separator can't appear inside a+// GitHub/GitLab path segment, so the boundary stays visible in the output.+func TestBareDirNameDistinctsSegmentBoundaryColliders(t *testing.T) {+ t.Parallel()+ pairs := [][2]string{+ {"[email protected]:foo/bar-baz.git", "[email protected]:foo-bar/baz.git"},+ {"https://github.com/foo/bar-baz.git", "https://github.com/foo-bar/baz.git"},+ }+ for _, p := range pairs {+ a, b := bareDirName(p[0]), bareDirName(p[1])+ if a == b {+ t.Errorf("bareDirName collision: %q and %q both → %q", p[0], p[1], a)+ }+ }+}++// TestBareDirNameDistinctsSameRepoNameAcrossHosts covers the cross-host+// collision class: the same path-with-namespace on different hosts must+// produce distinct cache dirs so an agent configured for host A can't be+// served the clone from host B.+func TestBareDirNameDistinctsSameRepoNameAcrossHosts(t *testing.T) {+ t.Parallel()+ pairs := [][2]string{+ {"[email protected]:org/repo.git", "[email protected]:org/repo.git"},+ {"https://github.com/org/repo.git", "https://gitlab.example.com/org/repo.git"},+ {"ssh://[email protected]/org/repo.git", "ssh://[email protected]/org/repo.git"},+ }+ for _, p := range pairs {+ a, b := bareDirName(p[0]), bareDirName(p[1])+ if a == b {+ t.Errorf("bareDirName collision across hosts: %q and %q both → %q", p[0], p[1], a)+ }+ }+}++// TestBareDirNameDistinctsHostPortFromDashedHostname covers the lossy-port+// encoding regression: a naive ':' -> '-' rewrite would collapse+// `host:port` onto a hostname that literally contains the same dash pattern,+// silently reintroducing the wrong-remote bug. We URL-encode ':' to '%3A'+// so host+port is lossless — and '%' is forbidden in valid hostnames so the+// marker can never come from a legal literal hostname.+func TestBareDirNameDistinctsHostPortFromDashedHostname(t *testing.T) {+ t.Parallel()+ pairs := [][2]string{+ // Host-with-port vs a literal hostname that looks like `host-port`.+ {"ssh://[email protected]:22/org/repo.git", "[email protected]:org/repo.git"},+ // Same again but across the URL and scp-style forms, explicit ports+ // swapped to ensure we don't rely on order.+ {"ssh://[email protected]:443/a/b.git", "[email protected]:a/b.git"},+ }+ for _, p := range pairs {+ a, b := bareDirName(p[0]), bareDirName(p[1])+ if a == b {+ t.Errorf("bareDirName collision between host:port and host-port: %q and %q both → %q", p[0], p[1], a)+ }+ }+}+func TestIsBareRepo(t *testing.T) {t.Parallel()@@ -86,7 +152,14 @@ func TestIsBareRepo(t *testing.T) {// createTestRepo creates a local git repo with an initial commit and returns its path.func createTestRepo(t *testing.T) string {t.Helper()- dir := t.TempDir()+ return createTestRepoAt(t, t.TempDir())+}++// createTestRepoAt initializes a git repo at the given directory (which+// must already exist). Used to craft repo URLs at paths chosen by the test+// — e.g. to reproduce collision classes in name derivation.+func createTestRepoAt(t *testing.T, dir string) string {+ t.Helper()for _, args := range [][]string{{"init", dir},{"-C", dir, "commit", "--allow-empty", "-m", "initial"},@@ -138,6 +211,110 @@ func TestSyncAndLookup(t *testing.T) {}}+// TestSyncKeepsDistinctCachesForSegmentBoundaryColliders proves that two+// URLs differing only at a path-segment boundary don't share a bare cache+// and don't silently reuse each other's origin. Both conditions would have+// failed under a plain slashes-to-dashes flattening scheme: the two URLs+// in this test produce the same dash-joined key even though they point at+// different source repositories.+func TestSyncKeepsDistinctCachesForSegmentBoundaryColliders(t *testing.T) {+ t.Parallel()++ // Build two real source repos under a shared parent. Their filesystem+ // paths are used directly as URLs (git accepts local paths as remote+ // URLs). The path pair ".../foo/bar-baz" and ".../foo-bar/baz" would+ // flatten to the same string under slashes-to-dashes — that's the+ // class of collision we want to rule out.+ parent := t.TempDir()+ srcA := filepath.Join(parent, "foo", "bar-baz")+ srcB := filepath.Join(parent, "foo-bar", "baz")+ if err := os.MkdirAll(srcA, 0o755); err != nil {+ t.Fatalf("mkdir srcA: %v", err)+ }+ if err := os.MkdirAll(srcB, 0o755); err != nil {+ t.Fatalf("mkdir srcB: %v", err)+ }+ createTestRepoAt(t, srcA)+ createTestRepoAt(t, srcB)+ // Distinct content so a silent-reuse bug would produce the wrong file+ // in the wrong cache.+ if err := os.WriteFile(filepath.Join(srcA, "A.txt"), []byte("A\n"), 0o644); err != nil {+ t.Fatalf("write A: %v", err)+ }+ if err := os.WriteFile(filepath.Join(srcB, "B.txt"), []byte("B\n"), 0o644); err != nil {+ t.Fatalf("write B: %v", err)+ }+ runGitAuthored(t, srcA, "add", ".")+ runGitAuthored(t, srcA, "commit", "-m", "A-content")+ runGitAuthored(t, srcB, "add", ".")+ runGitAuthored(t, srcB, "commit", "-m", "B-content")++ cache := New(t.TempDir(), testLogger())+ if err := cache.Sync("ws-1", []RepoInfo{{URL: srcA}, {URL: srcB}}); err != nil {+ t.Fatalf("Sync failed: %v", err)+ }++ pathA := cache.Lookup("ws-1", srcA)+ pathB := cache.Lookup("ws-1", srcB)+ if pathA == "" || pathB == "" {+ t.Fatalf("missing cache entry: A=%q B=%q", pathA, pathB)+ }+ if pathA == pathB {+ t.Fatalf("collider URLs share a bare cache path: %s", pathA)+ }++ // Each bare cache must carry the origin URL of the repo it was+ // cloned from — not the other one's. A silent-reuse bug would have+ // both caches pointing at whichever URL won the race in Sync.+ if got := gitConfigGet(t, pathA, "remote.origin.url"); got != srcA {+ t.Errorf("cacheA origin.url = %q, want %q", got, srcA)+ }+ if got := gitConfigGet(t, pathB, "remote.origin.url"); got != srcB {+ t.Errorf("cacheB origin.url = %q, want %q", got, srcB)+ }++ // And each cache's content must reflect the right source.+ if !cachedRepoHasFile(t, pathA, "A.txt") {+ t.Errorf("cacheA (%s) should contain A.txt from srcA", pathA)+ }+ if !cachedRepoHasFile(t, pathB, "B.txt") {+ t.Errorf("cacheB (%s) should contain B.txt from srcB", pathB)+ }+}++// gitConfigGet reads a git config value from repoPath. Fails the test if+// the key is missing or the command errors.+func gitConfigGet(t *testing.T, repoPath, key string) string {+ t.Helper()+ out, err := exec.Command("git", "-C", repoPath, "config", "--get", key).Output()+ if err != nil {+ t.Fatalf("git config --get %s in %s: %v", key, repoPath, err)+ }+ return strings.TrimSpace(string(out))+}++// cachedRepoHasFile returns true if the bare cache at barePath exposes a+// file named filename anywhere in its remote-tracking default branch.+// Walks refs/remotes/origin/* since a bare clone stores fetched heads+// there under the modern refspec.+func cachedRepoHasFile(t *testing.T, barePath, filename string) bool {+ t.Helper()+ ref := getRemoteDefaultBranch(barePath)+ if ref == "" {+ return false+ }+ out, err := exec.Command("git", "-C", barePath, "ls-tree", "-r", "--name-only", ref).Output()+ if err != nil {+ t.Fatalf("git ls-tree %s in %s: %v", ref, barePath, err)+ }+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {+ if strings.TrimSpace(line) == filename {+ return true+ }+ }+ return false+}+func TestSyncFetchesExisting(t *testing.T) {t.Parallel()sourceRepo := createTestRepo(t)