agentgh: add clone and setup for app-attributed pushes #31
@@ -29,7 +29,7 @@ like repospawner can run these tools as itself.
|
||||
Vault, so it does not touch `internal/agent`.
|
||||
- **`agentgh`** — `gh`/git against GitHub as an iuclabs GitHub App (`--app
|
||||
coder|reviewer`), via an installation token minted from Vault-held app creds.
|
||||
Subcommands: `token`, `credential`, `whoami`, `gh`.
|
||||
Subcommands: `token`, `credential`, `whoami`, `gh`, `clone`, `setup`.
|
||||
|
||||
All tools are separate `main` packages under `cmd/` and share the
|
||||
`internal/agent` package (Vault AppRole login, Gitea REST client, PR-ref
|
||||
@@ -45,7 +45,7 @@ cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe o
|
||||
cmd/agentvault/main.go # agentvault CLI (seed-outpost / seed-oauth)
|
||||
cmd/agentreview/main.go # agentreview serve (webhook HMAC, event filter, semaphore + per-PR dedupe)
|
||||
cmd/agentreview/review.go # review flow (diff, shallow clone, claude argv/env, post review)
|
||||
cmd/agentgh/main.go # agentgh CLI (token / credential / whoami / gh, persistent --app)
|
||||
cmd/agentgh/main.go # agentgh CLI (token / credential / whoami / gh / clone / setup, persistent --app)
|
||||
internal/agent/ # shared plumbing:
|
||||
token.go # env config + in-process Gitea-token cache
|
||||
vault.go # AppRole login + read the gitea creds path
|
||||
@@ -203,6 +203,14 @@ from `GET /users/<slug>[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 (after `rev-parse --git-dir`): an
|
||||
explicit pushurl, an identity `url.<origin>.insteadOf <origin>` 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 '<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
|
||||
|
||||
|
||||
@@ -449,10 +449,18 @@ agentgh token # print a fresh installation token
|
||||
agentgh gh pr list --repo iuclabs/x # run gh with GH_TOKEN set in its env only
|
||||
agentgh --app reviewer gh pr view 1 # act as iuclabs-reviewer (or AGENTGH_APP=reviewer)
|
||||
|
||||
# git over https as the app
|
||||
git config credential.https://github.com.helper '!agentgh credential'
|
||||
agentgh clone iuclabs/x [dir] [--branch b] # clone over https, then setup
|
||||
agentgh setup [dir] # make an existing https clone push as the app
|
||||
```
|
||||
|
||||
`setup` (and `clone`) pin `remote.origin.pushurl` to the https origin URL so a
|
||||
global `pushInsteadOf` cannot rewrite pushes to SSH, reset the inherited
|
||||
`credential.https://github.com.helper` chain (e.g. `gh auth git-credential`) to
|
||||
just `agentgh --app <app> credential`, and set `user.name`/`user.email` to the
|
||||
app bot's noreply identity. All writes go to the repo's local config. Check with
|
||||
`printf 'protocol=https\nhost=github.com\n\n' | git credential fill`
|
||||
(`username=x-access-token`).
|
||||
|
||||
`--app` (`coder`|`reviewer`, env `AGENTGH_APP`, default `coder`) selects the app
|
||||
for every subcommand; `AGENTGH_KV_PATH` overrides the KV path outright.
|
||||
`credential get` answers only for `https://github.com` (`username=x-access-token`);
|
||||
|
||||
+143
-1
@@ -6,6 +6,8 @@
|
||||
// agentgh credential get # git credential helper for github.com
|
||||
// agentgh whoami # bot login + commit email
|
||||
// agentgh gh <args...> # run gh with GH_TOKEN set
|
||||
// agentgh clone <owner/repo> [dir] # clone + setup
|
||||
// agentgh setup [dir] # make an existing clone push as the app
|
||||
// agentgh --app reviewer <cmd> # act as another app (env AGENTGH_APP)
|
||||
package main
|
||||
|
||||
@@ -64,10 +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) }
|
||||
root.AddCommand(newTokenCmd(load), newCredentialCmd(load), newWhoamiCmd(load), newGHCmd(load), newVersionCmd())
|
||||
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) {
|
||||
@@ -203,6 +227,124 @@ func runGH(args []string, tok string, stdin io.Reader, stdout, stderr io.Writer)
|
||||
return err
|
||||
}
|
||||
|
||||
const helperKey = "credential.https://" + githubHost + ".helper"
|
||||
|
||||
// gitAuth resets inherited github.com helpers (e.g. a global `gh auth
|
||||
// git-credential`) so only helper answers.
|
||||
func gitAuth(helper string) []string {
|
||||
return []string{"-c", helperKey + "=", "-c", helperKey + "=" + helper}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
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", "--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
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type helperFunc func() (string, error)
|
||||
|
||||
func identityAndHelper(load loader, helper helperFunc) (name, email, h string, err error) {
|
||||
if h, err = helper(); err != nil {
|
||||
return
|
||||
}
|
||||
a, err := load()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
name, email, err = a.Identity()
|
||||
return
|
||||
}
|
||||
|
||||
func newSetupCmd(load loader, helper helperFunc) *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "setup [dir]",
|
||||
Short: "Make an existing github.com clone push as the app",
|
||||
Args: cobra.MaximumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
dir := "."
|
||||
if len(args) == 1 {
|
||||
dir = args[0]
|
||||
}
|
||||
name, email, h, err := identityAndHelper(load, helper)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := configure(dir, h, name, email); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s: pushing as %s\n", dir, name)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func newCloneCmd(load loader, helper helperFunc) *cobra.Command {
|
||||
var branch string
|
||||
cmd := &cobra.Command{
|
||||
Use: "clone <owner/repo> [dir]",
|
||||
Short: "Clone a github.com repo over https and set it up to push as the app",
|
||||
Args: cobra.RangeArgs(1, 2),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
owner, repo, err := agent.ParseRepo(args[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dir := repo
|
||||
if len(args) == 2 {
|
||||
dir = args[1]
|
||||
}
|
||||
name, email, h, err := identityAndHelper(load, helper)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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, "--", u, dir)
|
||||
if _, err := agent.Git("", gitArgs...); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := configure(dir, h, name, email); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s: pushing as %s\n", dir, name)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&branch, "branch", "", "branch to check out")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func newVersionCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "version",
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -79,6 +80,14 @@ func fakeStack(t *testing.T) {
|
||||
}}})
|
||||
}))
|
||||
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/app":
|
||||
_, _ = w.Write([]byte(`{"slug":"iuclabs-coder"}`))
|
||||
return
|
||||
case strings.HasPrefix(r.URL.Path, "/users/"):
|
||||
_, _ = w.Write([]byte(`{"id":42}`))
|
||||
return
|
||||
}
|
||||
inst := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/app/installations/"), "/access_tokens")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"token":"ghs_inst` + inst + `"}`))
|
||||
@@ -172,3 +181,127 @@ func TestRunGHSignalExitCode(t *testing.T) {
|
||||
t.Errorf("err = %v, want exit code 143", err)
|
||||
}
|
||||
}
|
||||
|
||||
func git(t *testing.T, dir string, args ...string) string {
|
||||
t.Helper()
|
||||
out, err := agent.Git(dir, args...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// 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()
|
||||
cfg := filepath.Join(t.TempDir(), "gitconfig")
|
||||
body := "[url \"git@github.com:\"]\n\tpushInsteadOf = https://github.com/\n" +
|
||||
"[credential \"https://github.com\"]\n\thelper = \"!f() { echo username=neoloc; echo password=hijack; }; f\"\n" +
|
||||
"[credential]\n\thelper = \"!f() { echo username=generic; echo password=hijack; }; f\"\n" + extra
|
||||
if err := os.WriteFile(cfg, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("GIT_CONFIG_GLOBAL", cfg)
|
||||
t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
|
||||
}
|
||||
|
||||
func TestConfigureBeatsGlobalHijacks(t *testing.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", "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 {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 2 {
|
||||
if err := configure(dir, helper, "iuclabs-coder[bot]", "42+iuclabs-coder[bot]@users.noreply.github.com"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
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
|
||||
c.Stdin = strings.NewReader("protocol=https\nhost=github.com\n\n")
|
||||
out, err := c.Output()
|
||||
if err != nil || !strings.Contains(string(out), "username=x-access-token\npassword=app\n") {
|
||||
t.Errorf("credential fill = %q %v", out, err)
|
||||
}
|
||||
if got := git(t, dir, "config", "user.email"); got != "42+iuclabs-coder[bot]@users.noreply.github.com" {
|
||||
t.Errorf("user.email = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
git(t, dir, "init", "-q")
|
||||
git(t, dir, "remote", "add", "origin", "git@github.com:o/r.git")
|
||||
if err := configure(dir, "h", "n", "e"); err == nil {
|
||||
t.Error("ssh origin accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloneCommand(t *testing.T) {
|
||||
fakeStack(t)
|
||||
src := t.TempDir()
|
||||
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[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]") {
|
||||
t.Fatalf("clone: %q %v", out, err)
|
||||
}
|
||||
if got := git(t, dst, "rev-parse", "--abbrev-ref", "HEAD"); got != "feat" {
|
||||
t.Errorf("branch = %q", got)
|
||||
}
|
||||
if got := git(t, dst, "config", "remote.origin.pushurl"); got != "https://github.com/o/r.git" {
|
||||
t.Errorf("pushurl = %q", got)
|
||||
}
|
||||
exe, _ := os.Executable()
|
||||
got := git(t, dst, "config", "--local", "--get-all", "--null", helperKey)
|
||||
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 {
|
||||
t.Error("bad repo accepted")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,6 +53,9 @@ func runGit(dir string, args ...string) (string, error) {
|
||||
return strings.TrimSpace(stdout.String()), nil
|
||||
}
|
||||
|
||||
// Git runs git with args in dir and returns trimmed stdout.
|
||||
func Git(dir string, args ...string) (string, error) { return runGit(dir, args...) }
|
||||
|
||||
// GitClone clones url into dir. Any globalArgs (e.g. "-c",
|
||||
// "credential.helper=...") are passed before the clone subcommand so auth can be
|
||||
// supplied without persisting it in the resulting checkout's config.
|
||||
|
||||
Reference in New Issue
Block a user