feat: add agentgh github app token tool
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
// 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"
|
||||
|
||||
"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["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())
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 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 !strings.HasPrefix(kv, "GH_TOKEN=") && !strings.HasPrefix(kv, "GITHUB_TOKEN=") {
|
||||
c.Env = append(c.Env, kv)
|
||||
}
|
||||
}
|
||||
c.Env = append(c.Env, "GH_TOKEN="+tok)
|
||||
err = c.Run()
|
||||
var ee *exec.ExitError
|
||||
if errors.As(err, &ee) {
|
||||
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) },
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.unkin.net/unkin/agent-tools/internal/agent"
|
||||
)
|
||||
|
||||
func TestCredentialGetHostFiltering(t *testing.T) {
|
||||
calls := 0
|
||||
load := func() (*agent.GitHubApp, error) {
|
||||
calls++
|
||||
return nil, errors.New("no vault in this test")
|
||||
}
|
||||
for _, in := range []string{
|
||||
"protocol=https\nhost=git.unkin.net\n\n",
|
||||
"protocol=https\nhost=github.com.evil.example\n\n",
|
||||
"protocol=https\nhost=api.github.com\n\n",
|
||||
"protocol=https\n\n",
|
||||
} {
|
||||
var out bytes.Buffer
|
||||
if err := credentialGet(strings.NewReader(in), &out, load); err != nil || out.Len() != 0 {
|
||||
t.Errorf("%q: out=%q err=%v, want silent", in, out.String(), err)
|
||||
}
|
||||
}
|
||||
if calls != 0 {
|
||||
t.Errorf("loaded app creds %d times for foreign hosts", calls)
|
||||
}
|
||||
if err := credentialGet(strings.NewReader("protocol=https\nhost=github.com\n\n"), &bytes.Buffer{}, load); err == nil {
|
||||
t.Error("github.com request did not reach the loader")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialStoreEraseAndUnknown(t *testing.T) {
|
||||
for args, wantErr := range map[string]bool{"store": false, "erase": false, "bogus": true} {
|
||||
cmd := newRootCmd()
|
||||
cmd.SetArgs([]string{"credential", args})
|
||||
cmd.SetIn(strings.NewReader("host=github.com\npassword=x\n\n"))
|
||||
var out bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
if err := cmd.Execute(); (err != nil) != wantErr || out.Len() != 0 {
|
||||
t.Errorf("%s: err=%v out=%q", args, err, out.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// fakeStack wires a fake Vault holding both apps and a fake GitHub minting a
|
||||
// per-app token, so the full CLI path runs without network access.
|
||||
func fakeStack(t *testing.T) {
|
||||
t.Helper()
|
||||
key, _ := rsa.GenerateKey(rand.Reader, 2048)
|
||||
pemKey := string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)}))
|
||||
vault := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/v1/auth/approle/login" {
|
||||
_, _ = w.Write([]byte(`{"auth":{"client_token":"vt"}}`))
|
||||
return
|
||||
}
|
||||
inst := map[string]string{"/v1/kv/data/service/github/iuclabs/coder": "1", "/v1/kv/data/service/github/iuclabs/reviewer": "2"}[r.URL.Path]
|
||||
if inst == "" {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"data": map[string]any{
|
||||
"app_id": "9", "installation_id": inst, "private_key": pemKey,
|
||||
}}})
|
||||
}))
|
||||
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
inst := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/app/installations/"), "/access_tokens")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = w.Write([]byte(`{"token":"ghs_inst` + inst + `"}`))
|
||||
}))
|
||||
t.Cleanup(vault.Close)
|
||||
t.Cleanup(gh.Close)
|
||||
t.Setenv("VAULT_ADDR", vault.URL)
|
||||
t.Setenv("GITHUB_API_URL", gh.URL)
|
||||
t.Setenv("AGENTGH_KV_PATH", "")
|
||||
}
|
||||
|
||||
func run(t *testing.T, stdin string, args ...string) (string, error) {
|
||||
t.Helper()
|
||||
cmd := newRootCmd()
|
||||
cmd.SetArgs(args)
|
||||
cmd.SetIn(strings.NewReader(stdin))
|
||||
var out bytes.Buffer
|
||||
cmd.SetOut(&out)
|
||||
cmd.SetErr(&out)
|
||||
err := cmd.Execute()
|
||||
return out.String(), err
|
||||
}
|
||||
|
||||
func TestAppSelection(t *testing.T) {
|
||||
fakeStack(t)
|
||||
t.Setenv("AGENTGH_APP", "")
|
||||
if out, err := run(t, "", "token"); err != nil || out != "ghs_inst1\n" {
|
||||
t.Errorf("default app: %q %v", out, err)
|
||||
}
|
||||
if out, err := run(t, "", "--app", "reviewer", "token"); err != nil || out != "ghs_inst2\n" {
|
||||
t.Errorf("--app reviewer: %q %v", out, err)
|
||||
}
|
||||
t.Setenv("AGENTGH_APP", "reviewer")
|
||||
out, err := run(t, "protocol=https\nhost=github.com\n\n", "credential", "get")
|
||||
if err != nil || out != "username=x-access-token\npassword=ghs_inst2\n" {
|
||||
t.Errorf("AGENTGH_APP=reviewer credential: %q %v", out, err)
|
||||
}
|
||||
if out, err := run(t, "", "--app", "coder", "token"); err != nil || out != "ghs_inst1\n" {
|
||||
t.Errorf("--app beats AGENTGH_APP: %q %v", out, err)
|
||||
}
|
||||
if _, err := run(t, "", "--app", "nope", "token"); err == nil {
|
||||
t.Error("unknown app accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func fakeGH(t *testing.T, script string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "gh"), []byte("#!/bin/sh\n"+script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
return dir
|
||||
}
|
||||
|
||||
func TestRunGHPassesTokenInEnvOnly(t *testing.T) {
|
||||
dir := fakeGH(t, `printf '%s\n' "$@" > "$(dirname "$0")/argv"; echo "GH_TOKEN=$GH_TOKEN GITHUB_TOKEN=$GITHUB_TOKEN"; cat; exit 7`)
|
||||
t.Setenv("GH_TOKEN", "stale")
|
||||
t.Setenv("GITHUB_TOKEN", "stale")
|
||||
var out bytes.Buffer
|
||||
err := runGH([]string{"pr", "list", "--repo", "o/r"}, "ghs_secret", strings.NewReader("piped\n"), &out, &out)
|
||||
var code exitCode
|
||||
if !errors.As(err, &code) || code != 7 {
|
||||
t.Errorf("err = %v, want exit code 7", err)
|
||||
}
|
||||
if out.String() != "GH_TOKEN=ghs_secret GITHUB_TOKEN=\npiped\n" {
|
||||
t.Errorf("child saw %q", out.String())
|
||||
}
|
||||
argv, _ := os.ReadFile(filepath.Join(dir, "argv"))
|
||||
if string(argv) != "pr\nlist\n--repo\no/r\n" {
|
||||
t.Errorf("argv = %q", argv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGHCommandPassesFlagsThroughWithApp(t *testing.T) {
|
||||
fakeStack(t)
|
||||
fakeGH(t, `echo "$GH_TOKEN $*"`)
|
||||
out, err := run(t, "", "--app", "reviewer", "gh", "api", "--paginate", "/user")
|
||||
if err != nil || out != "ghs_inst2 api --paginate /user\n" {
|
||||
t.Errorf("out=%q err=%v", out, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user