Files
agent-tools/cmd/agentreview/main.go
T
unkin-agent be7801a6ed
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
fix(agentreview): require repo allowlist, pin clone host, block symlinks and secret leaks
2026-11-16 23:11:22 +11:00

360 lines
10 KiB
Go

// Command agentreview receives GitHub pull_request webhooks and posts a Claude
// Code review on each opened PR. Claude runs with read-only tools because PR
// content is untrusted.
//
// agentreview serve --listen :8080 --allow acme
package main
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"slices"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/spf13/cobra"
)
var version = "dev"
const maxPayload = 25 << 20
func main() {
if err := newRootCmd().Execute(); err != nil {
os.Exit(1)
}
}
func newRootCmd() *cobra.Command {
root := &cobra.Command{
Use: "agentreview",
Short: "Review GitHub pull requests with Claude Code from webhooks.",
Version: version,
SilenceUsage: true,
}
root.SetVersionTemplate("{{.Version}}\n")
root.AddCommand(newServeCmd(), &cobra.Command{
Use: "version",
Short: "Print the version",
Run: func(cmd *cobra.Command, args []string) { fmt.Println(version) },
SilenceUsage: true,
})
return root
}
func newServeCmd() *cobra.Command {
var listen string
var allow []string
var cfg config
cmd := &cobra.Command{
Use: "serve",
Short: "Serve the GitHub webhook endpoint",
Long: "Serve POST /webhook and GET /healthz. Secrets come from the environment only:\n" +
"GITHUB_WEBHOOK_SECRET, GITHUB_TOKEN, and either CLAUDE_CODE_OAUTH_TOKEN or\n" +
"ANTHROPIC_AUTH_TOKEN/ANTHROPIC_API_KEY (with optional ANTHROPIC_BASE_URL).\n" +
"Only repos matching --allow are reviewed.",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
secret := os.Getenv("GITHUB_WEBHOOK_SECRET")
if secret == "" {
return errors.New("GITHUB_WEBHOOK_SECRET is not set")
}
cfg.githubToken = os.Getenv("GITHUB_TOKEN")
if cfg.githubToken == "" {
return errors.New("GITHUB_TOKEN is not set")
}
authEnv, err := claudeAuthEnv(os.Getenv)
if err != nil {
return err
}
cfg.authEnv = authEnv
cfg.secrets = []string{secret, cfg.githubToken}
for _, k := range []string{"CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"} {
cfg.secrets = append(cfg.secrets, os.Getenv(k))
}
if err := validateAllow(allow); err != nil {
return err
}
if cfg.maxConcurrent < 1 {
return errors.New("--max-concurrent must be at least 1")
}
if cfg.systemPromptFile != "" {
if _, err := os.Stat(cfg.systemPromptFile); err != nil {
return fmt.Errorf("--system-prompt: %w", err)
}
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return serve(ctx, listen, newServer(ctx, []byte(secret), allow, newReviewer(cfg), cfg.maxConcurrent))
},
}
f := cmd.Flags()
f.StringVar(&listen, "listen", envOr("AGENTREVIEW_LISTEN", ":8080"), "Listen address (env AGENTREVIEW_LISTEN)")
f.IntVar(&cfg.maxConcurrent, "max-concurrent", envInt("AGENTREVIEW_MAX_CONCURRENT", 2), "Maximum concurrent reviews (env AGENTREVIEW_MAX_CONCURRENT)")
f.DurationVar(&cfg.timeout, "timeout", envDuration("AGENTREVIEW_TIMEOUT", 15*time.Minute), "Per-review timeout (env AGENTREVIEW_TIMEOUT)")
f.StringVar(&cfg.systemPromptFile, "system-prompt", os.Getenv("AGENTREVIEW_SYSTEM_PROMPT"), "File appended to Claude's system prompt; empty uses a built-in prompt (env AGENTREVIEW_SYSTEM_PROMPT)")
f.StringVar(&cfg.model, "model", os.Getenv("AGENTREVIEW_MODEL"), "Claude model; empty uses the CLI default (env AGENTREVIEW_MODEL)")
f.StringVar(&cfg.claudeBin, "claude", envOr("AGENTREVIEW_CLAUDE", "claude"), "Claude Code binary (env AGENTREVIEW_CLAUDE)")
f.StringSliceVar(&allow, "allow", envList("AGENTREVIEW_ALLOW"), "Repos to review as owner or owner/repo, comma-separated; required (env AGENTREVIEW_ALLOW)")
f.StringVar(&cfg.githubWeb, "github-url", envOr("GITHUB_SERVER_URL", "https://github.com"), "GitHub web base URL that repos are cloned from (env GITHUB_SERVER_URL)")
f.StringVar(&cfg.githubAPI, "github-api", envOr("GITHUB_API_URL", "https://api.github.com"), "GitHub REST API base URL (env GITHUB_API_URL)")
return cmd
}
func envOr(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func envList(key string) []string {
if v := os.Getenv(key); v != "" {
return strings.Split(v, ",")
}
return nil
}
func validateAllow(allow []string) error {
if len(allow) == 0 {
return errors.New("--allow is empty: set at least one owner or owner/repo")
}
for _, a := range allow {
parts := strings.Split(a, "/")
if len(parts) > 2 || slices.Contains(parts, "") {
return fmt.Errorf("--allow %q: want owner or owner/repo", a)
}
}
return nil
}
func allowed(allow []string, owner, repo string) bool {
for _, a := range allow {
o, r, hasRepo := strings.Cut(a, "/")
if strings.EqualFold(o, owner) && (!hasRepo || strings.EqualFold(r, repo)) {
return true
}
}
return false
}
func envInt(key string, def int) int {
if n, err := strconv.Atoi(os.Getenv(key)); err == nil {
return n
}
return def
}
func envDuration(key string, def time.Duration) time.Duration {
if d, err := time.ParseDuration(os.Getenv(key)); err == nil {
return d
}
return def
}
// claudeAuthEnv picks one auth backend so a subscription token is never sent to
// a gateway.
func claudeAuthEnv(getenv func(string) string) ([]string, error) {
if getenv("ANTHROPIC_AUTH_TOKEN") != "" || getenv("ANTHROPIC_API_KEY") != "" {
var env []string
for _, k := range []string{"ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"} {
if v := getenv(k); v != "" {
env = append(env, k+"="+v)
}
}
return env, nil
}
if v := getenv("CLAUDE_CODE_OAUTH_TOKEN"); v != "" {
return []string{"CLAUDE_CODE_OAUTH_TOKEN=" + v}, nil
}
return nil, errors.New("no Claude auth: set CLAUDE_CODE_OAUTH_TOKEN, or ANTHROPIC_AUTH_TOKEN/ANTHROPIC_API_KEY")
}
func serve(ctx context.Context, listen string, s *server) error {
srv := &http.Server{Addr: listen, Handler: s.routes(), ReadHeaderTimeout: 10 * time.Second}
errc := make(chan error, 1)
go func() { errc <- srv.ListenAndServe() }()
log.Printf("agentreview %s listening on %s", version, listen)
select {
case err := <-errc:
return err
case <-ctx.Done():
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err := srv.Shutdown(shutdownCtx)
s.wg.Wait()
return err
}
type pullRequest struct {
Owner, Repo string
Number int
Title, Body string
BaseRef string
HeadRef string
HeadSHA string
}
func (p pullRequest) key() string { return fmt.Sprintf("%s/%s#%d", p.Owner, p.Repo, p.Number) }
type reviewFunc func(ctx context.Context, pr pullRequest) error
type server struct {
ctx context.Context
secret []byte
allow []string
review reviewFunc
sem chan struct{}
wg sync.WaitGroup
mu sync.Mutex
inflight map[string]bool
}
func newServer(ctx context.Context, secret []byte, allow []string, review reviewFunc, maxConcurrent int) *server {
return &server{ctx: ctx, secret: secret, allow: allow, review: review, sem: make(chan struct{}, maxConcurrent), inflight: map[string]bool{}}
}
func (s *server) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, "ok\n") })
mux.HandleFunc("POST /webhook", s.handleWebhook)
return mux
}
func validSignature(secret, body []byte, header string) bool {
got, err := hex.DecodeString(strings.TrimPrefix(header, "sha256="))
if err != nil || !strings.HasPrefix(header, "sha256=") {
return false
}
mac := hmac.New(sha256.New, secret)
mac.Write(body)
return hmac.Equal(got, mac.Sum(nil))
}
type webhookEvent struct {
Action string `json:"action"`
Number int `json:"number"`
PullRequest struct {
Title string `json:"title"`
Body string `json:"body"`
Draft bool `json:"draft"`
Head struct {
Ref string `json:"ref"`
SHA string `json:"sha"`
} `json:"head"`
Base struct {
Ref string `json:"ref"`
} `json:"base"`
} `json:"pull_request"`
Repository struct {
FullName string `json:"full_name"`
} `json:"repository"`
}
// reviewable returns the PR to review, or a reason to skip the event.
func reviewable(event string, body []byte) (pullRequest, string) {
if event != "pull_request" {
return pullRequest{}, "event " + event
}
var ev webhookEvent
if err := json.Unmarshal(body, &ev); err != nil {
return pullRequest{}, "malformed payload"
}
switch ev.Action {
case "opened", "reopened", "ready_for_review":
default:
return pullRequest{}, "action " + ev.Action
}
if ev.PullRequest.Draft {
return pullRequest{}, "draft"
}
owner, repo, _ := strings.Cut(ev.Repository.FullName, "/")
pr := pullRequest{
Owner: owner,
Repo: repo,
Number: ev.Number,
Title: ev.PullRequest.Title,
Body: ev.PullRequest.Body,
BaseRef: ev.PullRequest.Base.Ref,
HeadRef: ev.PullRequest.Head.Ref,
HeadSHA: ev.PullRequest.Head.SHA,
}
if pr.Owner == "" || pr.Repo == "" || strings.Contains(pr.Repo, "/") || pr.Number == 0 || pr.HeadSHA == "" {
return pullRequest{}, "incomplete payload"
}
return pr, ""
}
func (s *server) handleWebhook(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxPayload))
if err != nil {
http.Error(w, "payload too large", http.StatusRequestEntityTooLarge)
return
}
if !validSignature(s.secret, body, r.Header.Get("X-Hub-Signature-256")) {
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
pr, skip := reviewable(r.Header.Get("X-GitHub-Event"), body)
if skip == "" && !allowed(s.allow, pr.Owner, pr.Repo) {
log.Printf("%s: repo not in --allow, ignoring", pr.key())
skip = "not allowed"
}
if skip != "" {
w.WriteHeader(http.StatusNoContent)
return
}
if !s.start(pr) {
log.Printf("%s: review already running, skipping", pr.key())
}
w.WriteHeader(http.StatusAccepted)
}
// start queues a review unless one for the same PR is already queued or running.
func (s *server) start(pr pullRequest) bool {
s.mu.Lock()
defer s.mu.Unlock()
if s.inflight[pr.key()] {
return false
}
s.inflight[pr.key()] = true
s.wg.Add(1)
go func() {
defer s.wg.Done()
defer s.finish(pr.key())
select {
case s.sem <- struct{}{}:
case <-s.ctx.Done():
return
}
defer func() { <-s.sem }()
log.Printf("%s: reviewing %s", pr.key(), pr.HeadSHA)
if err := s.review(s.ctx, pr); err != nil {
log.Printf("%s: review failed: %v", pr.key(), err)
return
}
log.Printf("%s: review posted", pr.key())
}()
return true
}
func (s *server) finish(key string) {
s.mu.Lock()
delete(s.inflight, key)
s.mu.Unlock()
}