agentgh: pin origin URLs against insteadOf and bake a stable quoted helper
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful

This commit is contained in:
2026-11-21 23:47:53 +11:00
parent 6c6044c6a0
commit 2faf4eff59
3 changed files with 86 additions and 28 deletions
+40 -15
View File
@@ -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
}
+38 -8
View File
@@ -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 {