Files
agent-tools/cmd/agentgh/main.go
T
unkin-agent 2faf4eff59
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
agentgh: pin origin URLs against insteadOf and bake a stable quoted helper
2026-11-21 23:47:53 +11:00

355 lines
9.8 KiB
Go

// Command agentgh lets agents use gh and git against GitHub as an iuclabs
// GitHub App. App creds are read from Vault with the agent AppRole and an
// installation token is minted per process; nothing long-lived touches disk.
//
// agentgh token # print a fresh installation token
// 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
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"os/exec"
"strings"
"syscall"
"git.unkin.net/unkin/agent-tools/internal/agent"
"github.com/spf13/cobra"
)
var version = "dev"
const githubHost = "github.com"
type exitCode int
func (e exitCode) Error() string { return fmt.Sprintf("exit status %d", int(e)) }
func main() {
err := newRootCmd().Execute()
var code exitCode
switch {
case errors.As(err, &code):
os.Exit(int(code))
case err != nil:
_, _ = fmt.Fprintln(os.Stderr, "Error:", err)
os.Exit(1)
}
}
func defaultApp() string {
if v := os.Getenv("AGENTGH_APP"); v != "" {
return v
}
return agent.DefaultGitHubApp
}
func newRootCmd() *cobra.Command {
var app string
root := &cobra.Command{
Use: "agentgh",
Short: "Use gh and git against GitHub as an iuclabs GitHub App.",
Version: version,
SilenceUsage: true,
SilenceErrors: true,
TraverseChildren: true,
}
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) { 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) {
a, err := load()
if err != nil {
return "", err
}
return a.InstallationToken()
}
func newTokenCmd(load loader) *cobra.Command {
return &cobra.Command{
Use: "token",
Short: "Print a fresh installation token",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
tok, err := token(load)
if err != nil {
return err
}
_, _ = fmt.Fprintln(cmd.OutOrStdout(), tok)
return nil
},
}
}
func newCredentialCmd(load loader) *cobra.Command {
return &cobra.Command{
Use: "credential <get|store|erase>",
Short: "git credential-helper: emit app creds for github.com",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
switch args[0] {
case "get":
return credentialGet(cmd.InOrStdin(), cmd.OutOrStdout(), load)
case "store", "erase":
return nil
default:
return fmt.Errorf("unknown credential action %q", args[0])
}
},
}
}
func credentialGet(stdin io.Reader, stdout io.Writer, load loader) error {
req := map[string]string{}
sc := bufio.NewScanner(stdin)
for sc.Scan() {
line := sc.Text()
if line == "" {
break
}
if k, v, ok := strings.Cut(line, "="); ok {
req[k] = v
}
}
if err := sc.Err(); err != nil {
return err
}
if req["protocol"] != "https" || req["host"] != githubHost {
return nil
}
tok, err := token(load)
if err != nil {
return err
}
_, _ = fmt.Fprintf(stdout, "username=x-access-token\npassword=%s\n", tok)
return nil
}
func newWhoamiCmd(load loader) *cobra.Command {
return &cobra.Command{
Use: "whoami",
Short: "Print the app's bot login and commit email",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
a, err := load()
if err != nil {
return err
}
login, email, err := a.Identity()
if err != nil {
return err
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "login: %s\nemail: %s\n", login, email)
return nil
},
}
}
func newGHCmd(load loader) *cobra.Command {
return &cobra.Command{
Use: "gh [args...]",
Short: "Run gh with GH_TOKEN set to an installation token",
DisableFlagParsing: true,
RunE: func(cmd *cobra.Command, args []string) error {
tok, err := token(load)
if err != nil {
return err
}
return runGH(args, tok, cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr())
},
}
}
var strippedEnv = map[string]bool{
"GH_TOKEN": true, "GITHUB_TOKEN": true, "GH_HOST": true,
"GH_ENTERPRISE_TOKEN": true, "GITHUB_ENTERPRISE_TOKEN": true,
}
// runGH passes the token through the child env only, never argv.
func runGH(args []string, tok string, stdin io.Reader, stdout, stderr io.Writer) error {
bin, err := exec.LookPath("gh")
if err != nil {
return fmt.Errorf("gh not found on PATH: %w", err)
}
c := exec.Command(bin, args...)
c.Stdin, c.Stdout, c.Stderr = stdin, stdout, stderr
for _, kv := range os.Environ() {
if k, _, _ := strings.Cut(kv, "="); !strippedEnv[k] {
c.Env = append(c.Env, kv)
}
}
c.Env = append(c.Env, "GH_TOKEN="+tok, "GH_HOST="+githubHost)
err = c.Run()
var ee *exec.ExitError
if errors.As(err, &ee) {
if ws, ok := ee.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
return exitCode(128 + int(ws.Signal()))
}
return exitCode(ee.ExitCode())
}
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",
Short: "Print the version",
Run: func(cmd *cobra.Command, args []string) { _, _ = fmt.Fprintln(cmd.OutOrStdout(), version) },
}
}