Files
agent-tools/cmd/agentgh/main.go
T
unkin-agent fa615d1733
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
fix(agentgh): require https for creds, pin gh to github.com, map signal exits
2026-11-21 18:05:15 +11:00

213 lines
5.4 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 --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) }
root.AddCommand(newTokenCmd(load), newCredentialCmd(load), newWhoamiCmd(load), newGHCmd(load), newVersionCmd())
return root
}
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
}
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) },
}
}