From 2faf4eff59f0c67337cca3792ed0b8686d3cf3a5 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sat, 21 Nov 2026 23:47:53 +1100 Subject: [PATCH] agentgh: pin origin URLs against insteadOf and bake a stable quoted helper --- AGENTS.md | 13 ++++++---- cmd/agentgh/main.go | 55 +++++++++++++++++++++++++++++----------- cmd/agentgh/main_test.go | 46 +++++++++++++++++++++++++++------ 3 files changed, 86 insertions(+), 28 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a22607d..1608d10 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -203,11 +203,14 @@ from `GET /users/[bot]` (installation token). `agentgh gh` runs `gh` via `os/exec` with `GH_TOKEN` and `GH_HOST=github.com` set in the child env (other GitHub token/host vars stripped), and propagates its exit code (128+signal); `DisableFlagParsing` plus `TraverseChildren` lets `--app` precede `gh` while gh's flags pass untouched. -`setup`/`clone` write repo-local config only: an explicit pushurl (which -`pushInsteadOf` never rewrites), an empty `credential.https://github.com.helper` -reset followed by `! --app credential` (a URL-scoped global helper -outranks a plain `credential.helper`, so the reset must use the same key), and -the bot identity from `Identity()`. `clone` passes the same reset via `-c`. +`setup`/`clone` write repo-local config only (after `rev-parse --git-dir`): an +explicit pushurl, an identity `url..insteadOf ` rule (git uses +the longest matching prefix, so it beats any inherited `insteadOf`/`pushInsteadOf` +for github.com), an empty `credential.https://github.com.helper` reset followed by +`!agentgh --app '' credential` (helpers run in config-file order and the empty +value clears the whole inherited list; the bare name is used when PATH resolves +to the running binary, else its shell-quoted absolute path), and the bot identity +from `Identity()`. `clone` passes the same reset and rewrite via `-c`. ## Gotchas diff --git a/cmd/agentgh/main.go b/cmd/agentgh/main.go index 6406c15..8693b2a 100644 --- a/cmd/agentgh/main.go +++ b/cmd/agentgh/main.go @@ -66,18 +66,32 @@ func newRootCmd() *cobra.Command { root.SetVersionTemplate("{{.Version}}\n") root.PersistentFlags().StringVar(&app, "app", defaultApp(), "GitHub App to act as: "+strings.Join(agent.GitHubApps, "|")+" (env AGENTGH_APP)") load := func() (*agent.GitHubApp, error) { return agent.GitHubAppFor(app) } - helper := func() (string, error) { - exe, err := os.Executable() - if err != nil { - return "", err - } - return "!" + exe + " --app " + app + " credential", nil - } + helper := func() (string, error) { return credentialHelper(app) } root.AddCommand(newTokenCmd(load), newCredentialCmd(load), newWhoamiCmd(load), newGHCmd(load), newCloneCmd(load, helper), newSetupCmd(load, helper), newVersionCmd()) return root } +// credentialHelper bakes the bare name when PATH resolves to this binary, so a +// temp or versioned executable path never lands in .git/config. +func credentialHelper(app string) (string, error) { + exe, err := os.Executable() + if err != nil { + return "", err + } + bin := shellQuote(exe) + if p, err := exec.LookPath("agentgh"); err == nil { + a, errA := os.Stat(p) + b, errB := os.Stat(exe) + if errA == nil && errB == nil && os.SameFile(a, b) { + bin = "agentgh" + } + } + return "!" + bin + " --app " + shellQuote(app) + " credential", nil +} + +func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" } + type loader func() (*agent.GitHubApp, error) func token(load loader) (string, error) { @@ -221,9 +235,16 @@ func gitAuth(helper string) []string { return []string{"-c", helperKey + "=", "-c", helperKey + "=" + helper} } -// configure pins origin's pushurl (pushInsteadOf skips an explicit pushurl), -// replaces the inherited helper chain with helper and sets the commit identity. +// identityRewrite is the longest possible insteadOf match for u, so it beats any +// inherited insteadOf/pushInsteadOf prefix rule for github.com. +func identityRewrite(u string) (key, val string) { return "url." + u + ".insteadOf", u } + +// configure pins origin's pushurl and fetch/push URLs, replaces the inherited +// helper chain with helper and sets the commit identity. func configure(dir, helper, name, email string) error { + if _, err := agent.Git(dir, "rev-parse", "--git-dir"); err != nil { + return fmt.Errorf("%s is not a git repository: %w", dir, err) + } u, err := agent.Git(dir, "config", "--get", "remote.origin.url") if err != nil { return err @@ -231,12 +252,14 @@ func configure(dir, helper, name, email string) error { if !strings.HasPrefix(u, "https://"+githubHost+"/") { return fmt.Errorf("origin %q is not an https://%s/ URL", u, githubHost) } + rk, rv := identityRewrite(u) for _, args := range [][]string{ {"remote", "set-url", "--push", "origin", u}, - {"config", "--replace-all", helperKey, ""}, - {"config", "--add", helperKey, helper}, - {"config", "user.name", name}, - {"config", "user.email", email}, + {"config", "--local", rk, rv}, + {"config", "--local", "--replace-all", helperKey, ""}, + {"config", "--local", "--add", helperKey, helper}, + {"config", "--local", "user.name", name}, + {"config", "--local", "user.email", email}, } { if _, err := agent.Git(dir, args...); err != nil { return err @@ -301,11 +324,13 @@ func newCloneCmd(load loader, helper helperFunc) *cobra.Command { if err != nil { return err } - gitArgs := append(gitAuth(h), "clone") + u := "https://" + githubHost + "/" + owner + "/" + repo + ".git" + rk, rv := identityRewrite(u) + gitArgs := append(gitAuth(h), "-c", rk+"="+rv, "clone") if branch != "" { gitArgs = append(gitArgs, "--branch", branch) } - gitArgs = append(gitArgs, "https://"+githubHost+"/"+owner+"/"+repo+".git", dir) + gitArgs = append(gitArgs, "--", u, dir) if _, err := agent.Git("", gitArgs...); err != nil { return err } diff --git a/cmd/agentgh/main_test.go b/cmd/agentgh/main_test.go index 2c40860..8eb3db9 100644 --- a/cmd/agentgh/main_test.go +++ b/cmd/agentgh/main_test.go @@ -191,7 +191,7 @@ func git(t *testing.T, dir string, args ...string) string { return out } -// hijackedGlobal points git at a global config carrying both ways a user's +// hijackedGlobal points git at a global config carrying the ways a user's // config steals github.com pushes: SSH pushInsteadOf and a URL-scoped helper. func hijackedGlobal(t *testing.T, extra string) { t.Helper() @@ -207,12 +207,12 @@ func hijackedGlobal(t *testing.T, extra string) { } func TestConfigureBeatsGlobalHijacks(t *testing.T) { - hijackedGlobal(t, "") + hijackedGlobal(t, "[url \"git@github.com:\"]\n\tinsteadOf = https://github.com/\n") dir := t.TempDir() git(t, dir, "init", "-q") git(t, dir, "remote", "add", "origin", "https://github.com/o/r.git") - if got := git(t, dir, "remote", "get-url", "--push", "origin"); got != "git@github.com:o/r.git" { - t.Fatalf("precondition: pushInsteadOf not active, push url %q", got) + if got := git(t, dir, "remote", "get-url", "origin"); got != "git@github.com:o/r.git" { + t.Fatalf("precondition: insteadOf not active, url %q", got) } helper := filepath.Join(t.TempDir(), "helper") if err := os.WriteFile(helper, []byte("#!/bin/sh\necho username=x-access-token\necho password=app\n"), 0o755); err != nil { @@ -223,8 +223,10 @@ func TestConfigureBeatsGlobalHijacks(t *testing.T) { t.Fatal(err) } } - if got := git(t, dir, "remote", "get-url", "--push", "origin"); got != "https://github.com/o/r.git" { - t.Errorf("push url = %q", got) + for _, args := range [][]string{{"remote", "get-url", "origin"}, {"remote", "get-url", "--push", "origin"}} { + if got := git(t, dir, args...); got != "https://github.com/o/r.git" { + t.Errorf("%v = %q", args, got) + } } c := exec.Command("git", "credential", "fill") c.Dir = dir @@ -238,6 +240,34 @@ func TestConfigureBeatsGlobalHijacks(t *testing.T) { } } +func TestConfigureRejectsNonRepo(t *testing.T) { + hijackedGlobal(t, "") + t.Setenv("GIT_CEILING_DIRECTORIES", os.TempDir()) + if err := configure(t.TempDir(), "h", "n", "e"); err == nil || !strings.Contains(err.Error(), "not a git repository") { + t.Errorf("err = %v", err) + } +} + +func TestCredentialHelper(t *testing.T) { + exe, _ := os.Executable() + t.Setenv("PATH", t.TempDir()) + if got, _ := credentialHelper("it's"); got != "!"+shellQuote(exe)+` --app 'it'\''s' credential` { + t.Errorf("off PATH: %q", got) + } + dir := t.TempDir() + if err := os.Symlink(exe, filepath.Join(dir, "agentgh")); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) + if got, _ := credentialHelper("coder"); got != "!agentgh --app 'coder' credential" { + t.Errorf("on PATH: %q", got) + } + out, err := exec.Command("/bin/sh", "-c", "printf %s "+shellQuote("a b'c\"$d")).Output() + if err != nil || string(out) != "a b'c\"$d" { + t.Errorf("shellQuote round-trip = %q %v", out, err) + } +} + func TestConfigureRejectsNonHTTPSOrigin(t *testing.T) { hijackedGlobal(t, "") dir := t.TempDir() @@ -254,7 +284,7 @@ func TestCloneCommand(t *testing.T) { git(t, src, "init", "-q", "-b", "main") git(t, src, "-c", "user.name=x", "-c", "user.email=x@x", "commit", "-q", "--allow-empty", "-m", "init") git(t, src, "branch", "feat") - hijackedGlobal(t, "[url \""+src+"\"]\n\tinsteadOf = https://github.com/o/r.git\n") + hijackedGlobal(t, "[url \""+src+"\"]\n\tinsteadOf = https://github.com/o/r.git\n[url \"git@github.com:\"]\n\tinsteadOf = https://github.com/\n") dst := filepath.Join(t.TempDir(), "r") out, err := run(t, "", "--app", "reviewer", "clone", "o/r", dst, "--branch", "feat") if err != nil || !strings.Contains(out, "pushing as iuclabs-coder[bot]") { @@ -268,7 +298,7 @@ func TestCloneCommand(t *testing.T) { } exe, _ := os.Executable() got := git(t, dst, "config", "--local", "--get-all", "--null", helperKey) - if got != "\x00!"+exe+" --app reviewer credential\x00" { + if got != "\x00!"+shellQuote(exe)+" --app 'reviewer' credential\x00" { t.Errorf("helper chain = %q", got) } if _, err := run(t, "", "clone", "not-a-repo"); err == nil {