Files
agent-tools/internal/agent/github.go
T
unkin-agent 161a33c2ed
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline failed
ci/woodpecker/pr/test Pipeline was successful
feat(watchpr): poll GitHub PRs alongside Gitea
2026-11-22 01:51:26 +11:00

308 lines
9.0 KiB
Go

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+<name>.
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
expires time.Time
}
// tokenRefreshMargin is how long before expiry a cached installation token is
// re-minted, so a request never goes out with one about to lapse.
const tokenRefreshMargin = 5 * time.Minute
// 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 until it is within tokenRefreshMargin of expiry.
func (a *GitHubApp) InstallationToken() (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.token != "" && time.Now().Before(a.expires.Add(-tokenRefreshMargin)) {
return a.token, nil
}
return a.mint()
}
// RefreshInstallationToken discards the cached token and mints a new one.
func (a *GitHubApp) RefreshInstallationToken() (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
return a.mint()
}
func (a *GitHubApp) mint() (string, error) {
jwt, err := a.JWT(time.Now())
if err != nil {
return "", err
}
var out struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
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)
}
if out.ExpiresAt.IsZero() {
out.ExpiresAt = time.Now().Add(time.Hour)
}
a.token, a.expires = out.Token, out.ExpiresAt
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 <mount>/<path>", 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
}