From 79a269ebe0a351dbf2de592dcc44af3375501417 Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sat, 21 Nov 2026 18:02:18 +1100 Subject: [PATCH] feat: add agentgh github app token tool --- AGENTS.md | 26 ++- Makefile | 7 +- README.md | 32 +++- cmd/agentgh/main.go | 203 ++++++++++++++++++++++++ cmd/agentgh/main_test.go | 161 +++++++++++++++++++ internal/agent/github.go | 287 ++++++++++++++++++++++++++++++++++ internal/agent/github_test.go | 265 +++++++++++++++++++++++++++++++ packaging/nfpm.yaml | 18 +++ scripts/build-rpm.sh | 6 +- 9 files changed, 997 insertions(+), 8 deletions(-) create mode 100644 cmd/agentgh/main.go create mode 100644 cmd/agentgh/main_test.go create mode 100644 internal/agent/github.go create mode 100644 internal/agent/github_test.go diff --git a/AGENTS.md b/AGENTS.md index fabfb1c..03b9300 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,6 +27,9 @@ like repospawner can run these tools as itself. review it runs `claude -p` with read-only tools over a shallow clone of the head and posts the result as a `COMMENT` review. Uses GitHub, not Gitea or 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`. All tools are separate `main` packages under `cmd/` and share the `internal/agent` package (Vault AppRole login, Gitea REST client, PR-ref @@ -42,6 +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) internal/agent/ # shared plumbing: token.go # env config + in-process Gitea-token cache vault.go # AppRole login + read the gitea creds path @@ -53,6 +57,7 @@ internal/agent/ # shared plumbing: authentik.go # Authentik REST client (outpost search, token view_key) seedoutpost.go # seed-outpost flow (Authentik token -> Vault KV) seedoauth.go # seed-oauth flow (oauth2-proxy credential set in Vault KV) + github.go # GitHub App: KV creds, RS256 JWT (stdlib), installation token, bot identity go.mod # module git.unkin.net/unkin/agent-tools Makefile # build / test / lint / completions / rpm / version-bump packaging/nfpm.yaml # nfpm spec (envsubst-templated) for the RPM (all binaries) @@ -87,6 +92,9 @@ Config via env (all have defaults): | `AGENTWS_ROOT` | `~/.cache/agentws` | agentws worktree root | | `AGENTWS_OWNER` | `unkin` | Gitea org that owns agentws-managed repos | | `AUTHENTIK_URL` | `https://identity.k8s.syd1.au.unkin.net` | Authentik base URL (`agentvault`) | +| `AGENTGH_APP` | `coder` | GitHub App `agentgh` acts as (`coder`/`reviewer`; `--app` wins) | +| `AGENTGH_KV_PATH` | `kv/service/github/iuclabs/` | KV-v2 path (mount first) of the app creds | +| `GITHUB_API_URL` | `https://api.github.com` | GitHub API base for `agentgh` (https, or http on loopback) | ### agentws git auth (ephemeral credential helper) @@ -106,7 +114,7 @@ to keep the default branch current. ## Build ```bash -make build # -> dist/agentpr, dist/watchpr, dist/agentws, dist/agentvault, dist/agentreview (CGO disabled, static) +make build # -> dist/agentpr, dist/watchpr, dist/agentws, dist/agentvault, dist/agentreview, dist/agentgh (CGO disabled, static) ``` Requires Go 1.21+. Dependency: `github.com/spf13/cobra` (CLI). @@ -119,7 +127,8 @@ make rpm # build all binaries + package into dist/*.rpm via nfpm `scripts/build-rpm.sh` generates bash/zsh/fish completions from the built binaries and bundles them alongside `/usr/bin/agentpr`, `/usr/bin/watchpr`, -`/usr/bin/agentws`, `/usr/bin/agentvault` and `/usr/bin/agentreview`. +`/usr/bin/agentws`, `/usr/bin/agentvault`, `/usr/bin/agentreview` and +`/usr/bin/agentgh`. On a `v*` tag the release pipeline builds the RPM and `PUT`s it to the artifactapi `rpm-internal` repo, then cuts a Gitea release. @@ -182,6 +191,19 @@ hold a complete oauth2-proxy credential set, in-process: Only key names, per-key actions and the new KV version are printed. Errors are wrapped per stage (login / read denied / write denied) via `ErrVaultDenied`. +## agentgh + +`agent.GitHubAppFor(app)` resolves the KV path (`AGENTGH_KV_PATH`, else +`kv/service/github/iuclabs/` for an allowlisted app name), does the shared +AppRole login + `ReadKV`, and caches the loaded `GitHubApp` per Vault address, +KV path and API URL; each app caches its own installation token. The app JWT is +RS256 via `crypto/rsa` (iat now-60s, exp now+9m, iss app_id) — no JWT +dependency. `whoami` reads the slug from `GET /app` (JWT) and the bot user id +from `GET /users/[bot]` (installation token). `agentgh gh` runs `gh` via +`os/exec` with `GH_TOKEN` added to (and `GH_TOKEN`/`GITHUB_TOKEN` stripped from) +the child env, and propagates its exit code; `DisableFlagParsing` plus +`TraverseChildren` lets `--app` precede `gh` while gh's flags pass untouched. + ## Gotchas - `agentreview` treats PR content as hostile: Claude gets `--tools Read,Grep,Glob`, diff --git a/Makefile b/Makefile index ea663e3..6c7c8b1 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # All shipped binaries and the package path each is built from. Both tools live # under cmd/; the module root ships no binary of its own. -BINARIES := agentpr watchpr agentws agentvault agentreview +BINARIES := agentpr watchpr agentws agentvault agentreview agentgh DIST := dist VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) GOFLAGS := -ldflags="-s -w -X main.version=$(VERSION)" @@ -11,7 +11,7 @@ ARCH ?= $(shell go env GOARCH) # shell for-loop over $(BINARIES). pkgpath = ./cmd/$$b -.PHONY: all build test lint fmt clean install completions rpm rpm-package patch minor major _tag +.PHONY: all build test lint pre-commit fmt clean install completions rpm rpm-package patch minor major _tag all: build @@ -30,6 +30,9 @@ test: lint: golangci-lint run ./... +pre-commit: + pre-commit run --all-files + fmt: gofmt -w . diff --git a/README.md b/README.md index 2c3dbf7..c75b169 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,8 @@ different agent identity. never plumb secret material through a shell. - **`agentreview`** — a GitHub webhook server that reviews newly opened pull requests with Claude Code and posts the result as a PR review. +- **`agentgh`** — run `gh` and git against GitHub as an iuclabs GitHub App + (`iuclabs-coder` or `iuclabs-reviewer`) with a per-process installation token. ## How it gets a token @@ -37,6 +39,9 @@ Everything is configured by environment variables, all with defaults: | `AGENTWS_ROOT` | `~/.cache/agentws` | worktree root (`agentws`) | | `AGENTWS_OWNER` | `unkin` | Gitea org that owns the repos (`agentws`) | | `AUTHENTIK_URL` | `https://identity.k8s.syd1.au.unkin.net` | Authentik base URL (`agentvault`) | +| `AGENTGH_APP` | `coder` | GitHub App `agentgh` acts as: `coder` or `reviewer` (`--app` wins) | +| `AGENTGH_KV_PATH` | `kv/service/github/iuclabs/` | KV-v2 path of the app creds (wins over the app name) | +| `GITHUB_API_URL` | `https://api.github.com` | GitHub API base (`agentgh`; https only) | ## agentpr @@ -430,10 +435,35 @@ Every flag also reads an env var: `AGENTREVIEW_ALLOW`, `AGENTREVIEW_LISTEN`, `AG `AGENTREVIEW_CLAUDE` (binary path), `GITHUB_SERVER_URL` (`--github-url`) and `GITHUB_API_URL` (`--github-api`). +## agentgh + +Act on GitHub as an iuclabs GitHub App. `agentgh` reads `app_id`, +`installation_id` and `private_key` (PKCS#1 or PKCS#8 PEM) from +`kv/service/github/iuclabs/` with the agent AppRole, signs a short-lived +RS256 app JWT and exchanges it for an installation token, cached in-process. No +token is written to disk, put in argv or logged. + +```bash +agentgh whoami # login: iuclabs-coder[bot] + noreply commit email +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' +``` + +`--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 host `github.com` (`username=x-access-token`); +`store`/`erase` are no-ops. `agentgh gh` exits with gh's exit code. Errors name +the failing stage: AppRole login, KV read denied, private key parse, JWT sign or +token mint. + ## Build & package ```bash -make build # -> dist/agentpr, dist/watchpr, dist/agentws, dist/agentvault, dist/agentreview +make build # -> dist/agentpr, dist/watchpr, dist/agentws, dist/agentvault, dist/agentreview, dist/agentgh make test # go test -race ./... make rpm # build + package dist/agent-tools--1.x86_64.rpm ``` diff --git a/cmd/agentgh/main.go b/cmd/agentgh/main.go new file mode 100644 index 0000000..6f34d5b --- /dev/null +++ b/cmd/agentgh/main.go @@ -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 # run gh with GH_TOKEN set +// agentgh --app reviewer # 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 ", + 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) }, + } +} diff --git a/cmd/agentgh/main_test.go b/cmd/agentgh/main_test.go new file mode 100644 index 0000000..35ad467 --- /dev/null +++ b/cmd/agentgh/main_test.go @@ -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) + } +} diff --git a/internal/agent/github.go b/internal/agent/github.go new file mode 100644 index 0000000..0a4de0c --- /dev/null +++ b/internal/agent/github.go @@ -0,0 +1,287 @@ +package agent + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "sync" + "time" +) + +const ( + // DefaultGitHubAPIURL is the GitHub REST API base used when GITHUB_API_URL is unset. + DefaultGitHubAPIURL = "https://api.github.com" + // DefaultGitHubApp is the GitHub App agentgh acts as when neither --app nor AGENTGH_APP is set. + DefaultGitHubApp = "coder" + // GitHubAppKVPrefix is the KV-v2 path (mount included) under which each app's creds live. + GitHubAppKVPrefix = "kv/service/github/iuclabs/" +) + +// GitHubApps are the app names agentgh accepts; each maps to GitHubAppKVPrefix+. +var GitHubApps = []string{"coder", "reviewer"} + +// GitHubAppKVPath returns the KV-v2 path (mount first) holding the app's creds: +// AGENTGH_KV_PATH when set, otherwise GitHubAppKVPrefix+app. +func GitHubAppKVPath(app string) (string, error) { + if v := strings.Trim(strings.TrimSpace(os.Getenv("AGENTGH_KV_PATH")), "/"); v != "" { + return v, nil + } + for _, a := range GitHubApps { + if a == app { + return GitHubAppKVPrefix + app, nil + } + } + return "", fmt.Errorf("unknown github app %q (want one of %s)", app, strings.Join(GitHubApps, ", ")) +} + +// GitHubAPIURL returns GITHUB_API_URL or the default. Only https is accepted +// (plain http only for loopback), since the app JWT and tokens travel on it. +func GitHubAPIURL() (string, error) { + raw := os.Getenv("GITHUB_API_URL") + if raw == "" { + raw = DefaultGitHubAPIURL + } + u, err := url.Parse(raw) + if err != nil || u.Host == "" { + return "", fmt.Errorf("GITHUB_API_URL %q is not a URL", raw) + } + if u.Scheme != "https" && (u.Scheme != "http" || !isLoopback(u.Hostname())) { + return "", fmt.Errorf("GITHUB_API_URL must be https:// (got %q)", raw) + } + return strings.TrimRight(raw, "/"), nil +} + +func isLoopback(host string) bool { + if host == "localhost" { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +// GitHubApp mints installation tokens for one GitHub App installation. +type GitHubApp struct { + AppID string + InstallationID string + Key *rsa.PrivateKey + APIURL string + HTTP *http.Client + + mu sync.Mutex + token string +} + +// ParseRSAPrivateKey decodes a PEM RSA key in PKCS#1 or PKCS#8 form. Errors +// never include key material. +func ParseRSAPrivateKey(pemData string) (*rsa.PrivateKey, error) { + block, _ := pem.Decode([]byte(pemData)) + if block == nil { + return nil, errors.New("private key is not PEM") + } + if k, err := x509.ParsePKCS1PrivateKey(block.Bytes); err == nil { + return k, nil + } + k, err := x509.ParsePKCS8PrivateKey(block.Bytes) + if err != nil { + return nil, errors.New("private key is neither PKCS#1 nor PKCS#8") + } + rk, ok := k.(*rsa.PrivateKey) + if !ok { + return nil, errors.New("private key is not RSA") + } + return rk, nil +} + +// JWT signs the RS256 app JWT GitHub requires for /app endpoints. +func (a *GitHubApp) JWT(now time.Time) (string, error) { + header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","typ":"JWT"}`)) + claims, err := json.Marshal(map[string]any{ + "iat": now.Add(-60 * time.Second).Unix(), + "exp": now.Add(9 * time.Minute).Unix(), + "iss": a.AppID, + }) + if err != nil { + return "", err + } + signing := header + "." + base64.RawURLEncoding.EncodeToString(claims) + sum := sha256.Sum256([]byte(signing)) + sig, err := rsa.SignPKCS1v15(rand.Reader, a.Key, crypto.SHA256, sum[:]) + if err != nil { + return "", fmt.Errorf("github app jwt sign: %w", err) + } + return signing + "." + base64.RawURLEncoding.EncodeToString(sig), nil +} + +func (a *GitHubApp) do(method, path, bearer string, out any) error { + req, err := http.NewRequest(method, a.APIURL+path, nil) + if err != nil { + return err + } + req.Header.Set("Accept", "application/vnd.github+json") + req.Header.Set("X-GitHub-Api-Version", "2022-11-28") + req.Header.Set("Authorization", "Bearer "+bearer) + resp, err := a.HTTP.Do(req) + if err != nil { + return err + } + defer func() { _ = resp.Body.Close() }() + data, _ := io.ReadAll(resp.Body) + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + var e struct { + Message string `json:"message"` + } + _ = json.Unmarshal(data, &e) + return fmt.Errorf("HTTP %d: %s", resp.StatusCode, e.Message) + } + // Token responses carry secrets, so decode failures never echo the body. + if err := json.Unmarshal(data, out); err != nil { + return errors.New("decoding response failed") + } + return nil +} + +// InstallationToken returns an installation access token, minted on first call +// and cached for the life of the process. +func (a *GitHubApp) InstallationToken() (string, error) { + a.mu.Lock() + defer a.mu.Unlock() + if a.token != "" { + return a.token, nil + } + jwt, err := a.JWT(time.Now()) + if err != nil { + return "", err + } + var out struct { + Token string `json:"token"` + } + path := "/app/installations/" + url.PathEscape(a.InstallationID) + "/access_tokens" + if err := a.do(http.MethodPost, path, jwt, &out); err != nil { + return "", fmt.Errorf("github token mint for installation %s: %w", a.InstallationID, err) + } + if out.Token == "" { + return "", fmt.Errorf("github token mint for installation %s: no token in response", a.InstallationID) + } + a.token = out.Token + return a.token, nil +} + +// Identity returns the app's bot login and its noreply commit email. +func (a *GitHubApp) Identity() (login, email string, err error) { + jwt, err := a.JWT(time.Now()) + if err != nil { + return "", "", err + } + var app struct { + Slug string `json:"slug"` + } + if err := a.do(http.MethodGet, "/app", jwt, &app); err != nil { + return "", "", fmt.Errorf("github get app: %w", err) + } + if app.Slug == "" { + return "", "", errors.New("github get app: no slug in response") + } + tok, err := a.InstallationToken() + if err != nil { + return "", "", err + } + login = app.Slug + "[bot]" + var user struct { + ID int64 `json:"id"` + } + if err := a.do(http.MethodGet, "/users/"+url.PathEscape(login), tok, &user); err != nil { + return "", "", fmt.Errorf("github get user %s: %w", login, err) + } + return login, fmt.Sprintf("%d+%s@users.noreply.github.com", user.ID, login), nil +} + +// kvString reads a field Vault may hand back as a JSON string or number. +func kvString(data map[string]any, key string) string { + switch v := data[key].(type) { + case string: + return strings.TrimSpace(v) + case float64: + return strconv.FormatFloat(v, 'f', -1, 64) + } + return "" +} + +// LoadGitHubApp logs in with the agent AppRole and reads the app creds +// (app_id, installation_id, private_key) from the KV-v2 path (mount first). +func LoadGitHubApp(vaultAddr, roleID, kvPath, apiURL string) (*GitHubApp, error) { + mount, path, ok := strings.Cut(kvPath, "/") + if !ok || path == "" { + return nil, fmt.Errorf("kv path %q must be /", kvPath) + } + vc, err := NewVaultClient(vaultAddr, roleID) + if err != nil { + return nil, fmt.Errorf("vault approle login failed against %s (check VAULT_ADDR and AGENT_APPROLE_ROLE_ID): %w", vaultAddr, err) + } + secret, err := vc.ReadKV(mount, path) + if err != nil { + if errors.Is(err, ErrVaultDenied) { + return nil, fmt.Errorf("kv read %s denied: the agent AppRole policy does not grant read on this path: %w", kvPath, err) + } + return nil, fmt.Errorf("kv read %s: %w", kvPath, err) + } + app := &GitHubApp{ + AppID: kvString(secret, "app_id"), + InstallationID: kvString(secret, "installation_id"), + APIURL: apiURL, + HTTP: httpClient, + } + for k, v := range map[string]string{"app_id": app.AppID, "installation_id": app.InstallationID} { + if v == "" { + return nil, fmt.Errorf("kv read %s: missing %s", kvPath, k) + } + } + pemKey, _ := secret["private_key"].(string) + if app.Key, err = ParseRSAPrivateKey(pemKey); err != nil { + return nil, fmt.Errorf("kv read %s: private_key: %w", kvPath, err) + } + return app, nil +} + +var ( + ghMu sync.Mutex + ghApps = map[string]*GitHubApp{} +) + +// GitHubAppFor returns the configured app by name, loading its creds from +// Vault once per process (cached per Vault address, KV path and API URL). +func GitHubAppFor(name string) (*GitHubApp, error) { + kvPath, err := GitHubAppKVPath(name) + if err != nil { + return nil, err + } + apiURL, err := GitHubAPIURL() + if err != nil { + return nil, err + } + key := VaultAddr() + "|" + kvPath + "|" + apiURL + ghMu.Lock() + defer ghMu.Unlock() + if a := ghApps[key]; a != nil { + return a, nil + } + a, err := LoadGitHubApp(VaultAddr(), RoleID(), kvPath, apiURL) + if err != nil { + return nil, err + } + ghApps[key] = a + return a, nil +} diff --git a/internal/agent/github_test.go b/internal/agent/github_test.go new file mode 100644 index 0000000..5ec44bc --- /dev/null +++ b/internal/agent/github_test.go @@ -0,0 +1,265 @@ +package agent + +import ( + "crypto" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/x509" + "encoding/base64" + "encoding/json" + "encoding/pem" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +var testKey = func() *rsa.PrivateKey { + k, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + panic(err) + } + return k +}() + +func pkcs1PEM(k *rsa.PrivateKey) string { + return string(pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)})) +} + +func pkcs8PEM(t *testing.T, k any) string { + der, err := x509.MarshalPKCS8PrivateKey(k) + if err != nil { + t.Fatal(err) + } + return string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: der})) +} + +func TestParseRSAPrivateKey(t *testing.T) { + for name, p := range map[string]string{"pkcs1": pkcs1PEM(testKey), "pkcs8": pkcs8PEM(t, testKey)} { + k, err := ParseRSAPrivateKey(p) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + if !k.Equal(testKey) { + t.Errorf("%s: parsed key differs from original", name) + } + } + ec, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + for name, p := range map[string]string{"not pem": "garbage", "ec": pkcs8PEM(t, ec), "bad der": "-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----\n"} { + if _, err := ParseRSAPrivateKey(p); err == nil { + t.Errorf("%s: want error", name) + } + } +} + +// verifyJWT checks the RS256 signature against pub and returns the claims. +func verifyJWT(t *testing.T, tok string, pub *rsa.PublicKey) map[string]any { + t.Helper() + parts := strings.Split(tok, ".") + if len(parts) != 3 { + t.Fatalf("jwt has %d parts", len(parts)) + } + var hdr map[string]string + hb, _ := base64.RawURLEncoding.DecodeString(parts[0]) + if err := json.Unmarshal(hb, &hdr); err != nil || hdr["alg"] != "RS256" { + t.Fatalf("header = %s", hb) + } + sig, _ := base64.RawURLEncoding.DecodeString(parts[2]) + sum := sha256.Sum256([]byte(parts[0] + "." + parts[1])) + if err := rsa.VerifyPKCS1v15(pub, crypto.SHA256, sum[:], sig); err != nil { + t.Fatalf("signature: %v", err) + } + cb, _ := base64.RawURLEncoding.DecodeString(parts[1]) + var claims map[string]any + if err := json.Unmarshal(cb, &claims); err != nil { + t.Fatal(err) + } + return claims +} + +func TestJWTClaims(t *testing.T) { + a := &GitHubApp{AppID: "12345", Key: testKey} + now := time.Unix(1_700_000_000, 0) + tok, err := a.JWT(now) + if err != nil { + t.Fatal(err) + } + c := verifyJWT(t, tok, &testKey.PublicKey) + if c["iss"] != "12345" { + t.Errorf("iss = %v", c["iss"]) + } + iat, exp := int64(c["iat"].(float64)), int64(c["exp"].(float64)) + if iat != now.Unix()-60 { + t.Errorf("iat = %d, want now-60", iat) + } + if exp <= now.Unix() || exp-iat > 600 { + t.Errorf("exp = %d: must be in the future and ≤10m after iat", exp) + } + other, _ := rsa.GenerateKey(rand.Reader, 2048) + parts := strings.Split(tok, ".") + sig, _ := base64.RawURLEncoding.DecodeString(parts[2]) + sum := sha256.Sum256([]byte(parts[0] + "." + parts[1])) + if rsa.VerifyPKCS1v15(&other.PublicKey, crypto.SHA256, sum[:], sig) == nil { + t.Error("signature verified with an unrelated key") + } +} + +func fakeGitHub(t *testing.T, appID, token string, mints *atomic.Int32) *httptest.Server { + t.Helper() + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + auth := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + switch { + case r.Method == http.MethodPost && r.URL.Path == "/app/installations/777/access_tokens": + if c := verifyJWT(t, auth, &testKey.PublicKey); c["iss"] != appID { + t.Errorf("mint iss = %v, want %s", c["iss"], appID) + } + mints.Add(1) + w.WriteHeader(http.StatusCreated) + _, _ = w.Write([]byte(`{"token":"` + token + `","expires_at":"2030-01-01T00:00:00Z"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/app": + verifyJWT(t, auth, &testKey.PublicKey) + _, _ = w.Write([]byte(`{"slug":"iuclabs-coder"}`)) + case r.Method == http.MethodGet && r.URL.Path == "/users/iuclabs-coder[bot]": + if auth != token { + t.Errorf("users lookup auth = %q, want installation token", auth) + } + _, _ = w.Write([]byte(`{"login":"iuclabs-coder[bot]","id":4242}`)) + default: + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"message":"Not Found"}`)) + } + })) +} + +func TestInstallationTokenMintsOnceAndCaches(t *testing.T) { + var mints atomic.Int32 + gh := fakeGitHub(t, "12345", "ghs_test", &mints) + defer gh.Close() + a := &GitHubApp{AppID: "12345", InstallationID: "777", Key: testKey, APIURL: gh.URL, HTTP: gh.Client()} + for i := 0; i < 2; i++ { + tok, err := a.InstallationToken() + if err != nil || tok != "ghs_test" { + t.Fatalf("token = %q, %v", tok, err) + } + } + if mints.Load() != 1 { + t.Errorf("minted %d times, want 1", mints.Load()) + } + + bad := &GitHubApp{AppID: "12345", InstallationID: "999", Key: testKey, APIURL: gh.URL, HTTP: gh.Client()} + if _, err := bad.InstallationToken(); err == nil || !strings.Contains(err.Error(), "token mint") || !strings.Contains(err.Error(), "404") { + t.Errorf("err = %v, want token mint stage with HTTP 404", err) + } +} + +func TestIdentity(t *testing.T) { + var mints atomic.Int32 + gh := fakeGitHub(t, "12345", "ghs_test", &mints) + defer gh.Close() + a := &GitHubApp{AppID: "12345", InstallationID: "777", Key: testKey, APIURL: gh.URL, HTTP: gh.Client()} + login, email, err := a.Identity() + if err != nil { + t.Fatal(err) + } + if login != "iuclabs-coder[bot]" || email != "4242+iuclabs-coder[bot]@users.noreply.github.com" { + t.Errorf("identity = %q %q", login, email) + } +} + +// fakeKVVault serves AppRole login plus KV-v2 reads; secrets maps "/data/" to data. +func fakeKVVault(t *testing.T, secrets map[string]map[string]any) *httptest.Server { + t.Helper() + return 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 + } + if r.Header.Get("X-Vault-Token") != "vt" { + w.WriteHeader(http.StatusForbidden) + return + } + data, ok := secrets[strings.TrimPrefix(r.URL.Path, "/v1/")] + if !ok { + w.WriteHeader(http.StatusForbidden) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"data": data}}) + })) +} + +func TestGitHubAppForSelectsApp(t *testing.T) { + vault := fakeKVVault(t, map[string]map[string]any{ + "kv/data/service/github/iuclabs/coder": {"app_id": "111", "installation_id": "777", "private_key": pkcs1PEM(testKey)}, + "kv/data/service/github/iuclabs/reviewer": {"app_id": float64(222), "installation_id": float64(888), "private_key": pkcs8PEM(t, testKey)}, + "kv/data/custom/app": {"app_id": "333", "installation_id": "999", "private_key": pkcs1PEM(testKey)}, + }) + defer vault.Close() + t.Setenv("VAULT_ADDR", vault.URL) + t.Setenv("GITHUB_API_URL", "http://127.0.0.1:1") + + for app, want := range map[string]string{"coder": "111", "reviewer": "222"} { + a, err := GitHubAppFor(app) + if err != nil { + t.Fatalf("%s: %v", app, err) + } + if a.AppID != want { + t.Errorf("%s: app_id = %s, want %s", app, a.AppID, want) + } + if again, _ := GitHubAppFor(app); again != a { + t.Errorf("%s: not cached", app) + } + } + if a, _ := GitHubAppFor("reviewer"); a.InstallationID != "888" { + t.Errorf("numeric installation_id = %q", a.InstallationID) + } + if _, err := GitHubAppFor("../coder"); err == nil { + t.Error("unknown app accepted") + } + + t.Setenv("AGENTGH_KV_PATH", "kv/custom/app") + if a, err := GitHubAppFor("coder"); err != nil || a.AppID != "333" { + t.Errorf("override: %v %v", a, err) + } + t.Setenv("AGENTGH_KV_PATH", "kv/denied/app") + if _, err := GitHubAppFor("coder"); err == nil || !strings.Contains(err.Error(), "denied") { + t.Errorf("err = %v, want kv read denied", err) + } +} + +func TestLoadGitHubAppErrorsNameStage(t *testing.T) { + login := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusBadRequest) + })) + defer login.Close() + if _, err := LoadGitHubApp(login.URL, "r", "kv/x", "https://api.github.com"); err == nil || !strings.Contains(err.Error(), "approle login") { + t.Errorf("err = %v, want approle login stage", err) + } + + vault := fakeKVVault(t, map[string]map[string]any{"kv/data/x": {"app_id": "1", "installation_id": "2", "private_key": "nope"}}) + defer vault.Close() + _, err := LoadGitHubApp(vault.URL, "r", "kv/x", "https://api.github.com") + if err == nil || !strings.Contains(err.Error(), "private_key") || strings.Contains(err.Error(), "nope") { + t.Errorf("err = %v, want private_key stage without key material", err) + } +} + +func TestGitHubAPIURL(t *testing.T) { + for raw, ok := range map[string]bool{ + "": true, + "https://ghe.example/api": true, + "http://127.0.0.1:8080": true, + "http://localhost:1": true, + "http://api.github.com": false, + "ftp://api.github.com": false, + } { + t.Setenv("GITHUB_API_URL", raw) + if _, err := GitHubAPIURL(); (err == nil) != ok { + t.Errorf("%q: err = %v, want ok=%v", raw, err, ok) + } + } +} diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml index 003be2f..727a992 100644 --- a/packaging/nfpm.yaml +++ b/packaging/nfpm.yaml @@ -54,6 +54,12 @@ contents: mode: 0755 owner: root group: root + - src: dist/agentgh + dst: /usr/bin/agentgh + file_info: + mode: 0755 + owner: root + group: root # Shell completions (generated by scripts/build-rpm.sh before packaging). - src: dist/completions/agentpr.bash @@ -116,3 +122,15 @@ contents: dst: /usr/share/fish/vendor_completions.d/agentreview.fish file_info: mode: 0644 + - src: dist/completions/agentgh.bash + dst: /usr/share/bash-completion/completions/agentgh + file_info: + mode: 0644 + - src: dist/completions/_agentgh + dst: /usr/share/zsh/site-functions/_agentgh + file_info: + mode: 0644 + - src: dist/completions/agentgh.fish + dst: /usr/share/fish/vendor_completions.d/agentgh.fish + file_info: + mode: 0644 diff --git a/scripts/build-rpm.sh b/scripts/build-rpm.sh index df702e5..7e1d873 100755 --- a/scripts/build-rpm.sh +++ b/scripts/build-rpm.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # -# Package the (already built) agentpr, watchpr, agentws, agentvault and agentreview binaries into an RPM +# Package the (already built) agentpr, watchpr, agentws, agentvault, agentreview and agentgh binaries into an RPM # with nfpm, bundling generated bash/zsh/fish shell completions. # Usage: scripts/build-rpm.sh [version] (version defaults to $CI_COMMIT_TAG) # @@ -12,7 +12,7 @@ cd "${ROOT_DIR}" VERSION="${1:-${CI_COMMIT_TAG:-0.0.0-dev}}" VERSION="${VERSION#v}" # strip a leading v PACKAGE="agent-tools" -BINARIES=(agentpr watchpr agentws agentvault agentreview) +BINARIES=(agentpr watchpr agentws agentvault agentreview agentgh) DIST="dist" for b in "${BINARIES[@]}"; do @@ -37,7 +37,7 @@ export PACKAGE_VERSION="${VERSION}" export PACKAGE_RELEASE="1" export PACKAGE_ARCH="amd64" export PACKAGE_PLATFORM="linux" -export PACKAGE_DESCRIPTION="CLI tools for automation as the unkin-agent user: agentpr (create PRs/comments), watchpr (poll PRs and alert on meaningful change), agentws (manage per-branch git worktrees), agentvault (deterministic Vault flows) and agentreview (GitHub webhook PR reviewer)" +export PACKAGE_DESCRIPTION="CLI tools for automation as the unkin-agent user: agentpr (create PRs/comments), watchpr (poll PRs and alert on meaningful change), agentws (manage per-branch git worktrees), agentvault (deterministic Vault flows), agentreview (GitHub webhook PR reviewer) and agentgh (gh/git as a GitHub App)" export PACKAGE_MAINTAINER="Ben Vincent " export PACKAGE_HOMEPAGE="https://git.unkin.net/unkin/agent-tools" export PACKAGE_LICENSE="MIT"