feat: add agentgh github app token tool
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful

This commit is contained in:
2026-11-21 18:02:18 +11:00
parent e21f41f35c
commit 79a269ebe0
9 changed files with 997 additions and 8 deletions
+265
View File
@@ -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 "<mount>/data/<path>" 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)
}
}
}