fix(agentreview): require repo allowlist, pin clone host, block symlinks and secret leaks
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-16 23:11:22 +11:00
parent 37125a0bdd
commit be7801a6ed
5 changed files with 225 additions and 61 deletions
+63 -21
View File
@@ -2,7 +2,7 @@
// Code review on each opened PR. Claude runs with read-only tools because PR
// content is untrusted.
//
// agentreview serve --listen :8080
// agentreview serve --listen :8080 --allow acme
package main
import (
@@ -18,6 +18,7 @@ import (
"net/http"
"os"
"os/signal"
"slices"
"strconv"
"strings"
"sync"
@@ -56,13 +57,15 @@ func newRootCmd() *cobra.Command {
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).",
"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")
@@ -78,6 +81,13 @@ func newServeCmd() *cobra.Command {
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")
}
@@ -88,7 +98,7 @@ func newServeCmd() *cobra.Command {
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
return serve(ctx, listen, newServer(ctx, []byte(secret), newReviewer(cfg), cfg.maxConcurrent))
return serve(ctx, listen, newServer(ctx, []byte(secret), allow, newReviewer(cfg), cfg.maxConcurrent))
},
}
f := cmd.Flags()
@@ -98,6 +108,8 @@ func newServeCmd() *cobra.Command {
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
}
@@ -109,6 +121,36 @@ func envOr(key, def string) string {
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
@@ -165,7 +207,6 @@ type pullRequest struct {
BaseRef string
HeadRef string
HeadSHA string
CloneURL string
}
func (p pullRequest) key() string { return fmt.Sprintf("%s/%s#%d", p.Owner, p.Repo, p.Number) }
@@ -175,6 +216,7 @@ 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
@@ -182,8 +224,8 @@ type server struct {
inflight map[string]bool
}
func newServer(ctx context.Context, secret []byte, review reviewFunc, maxConcurrent int) *server {
return &server{ctx: ctx, secret: secret, review: review, sem: make(chan struct{}, maxConcurrent), 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 {
@@ -219,11 +261,7 @@ type webhookEvent struct {
} `json:"base"`
} `json:"pull_request"`
Repository struct {
Name string `json:"name"`
CloneURL string `json:"clone_url"`
Owner struct {
Login string `json:"login"`
} `json:"owner"`
FullName string `json:"full_name"`
} `json:"repository"`
}
@@ -244,18 +282,18 @@ func reviewable(event string, body []byte) (pullRequest, string) {
if ev.PullRequest.Draft {
return pullRequest{}, "draft"
}
owner, repo, _ := strings.Cut(ev.Repository.FullName, "/")
pr := pullRequest{
Owner: ev.Repository.Owner.Login,
Repo: ev.Repository.Name,
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,
CloneURL: ev.Repository.CloneURL,
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 == "" || pr.Number == 0 || pr.HeadSHA == "" || pr.CloneURL == "" {
if pr.Owner == "" || pr.Repo == "" || strings.Contains(pr.Repo, "/") || pr.Number == 0 || pr.HeadSHA == "" {
return pullRequest{}, "incomplete payload"
}
return pr, ""
@@ -272,6 +310,10 @@ func (s *server) handleWebhook(w http.ResponseWriter, r *http.Request) {
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
+99 -7
View File
@@ -33,7 +33,9 @@ func sign(secret string, body []byte) string {
return "sha256=" + hex.EncodeToString(mac.Sum(nil))
}
func prPayload(action string, draft bool) []byte {
func prPayload(action string, draft bool) []byte { return repoPayload("acme/repo", action, draft) }
func repoPayload(fullName, action string, draft bool) []byte {
b, _ := json.Marshal(map[string]any{
"action": action,
"number": 7,
@@ -43,8 +45,7 @@ func prPayload(action string, draft bool) []byte {
"base": map[string]any{"ref": "main"},
},
"repository": map[string]any{
"name": "repo", "clone_url": "https://github.com/acme/repo.git",
"owner": map[string]any{"login": "acme"},
"full_name": fullName, "clone_url": "https://evil.example/acme/repo.git",
},
})
return b
@@ -99,12 +100,13 @@ func TestReviewable(t *testing.T) {
func TestWebhookHandler(t *testing.T) {
var calls atomic.Int32
s := newServer(context.Background(), []byte(testSecret), func(context.Context, pullRequest) error {
s := newServer(context.Background(), []byte(testSecret), []string{"acme"}, func(context.Context, pullRequest) error {
calls.Add(1)
return nil
}, 2)
h := s.routes()
body := prPayload("opened", false)
other := repoPayload("evil/repo", "opened", false)
cases := []struct {
name, event, sig string
body []byte
@@ -114,6 +116,7 @@ func TestWebhookHandler(t *testing.T) {
{"bad signature", "pull_request", sign("other", body), body, http.StatusUnauthorized},
{"ignored event", "issues", sign(testSecret, body), body, http.StatusNoContent},
{"draft", "pull_request", sign(testSecret, prPayload("opened", true)), prPayload("opened", true), http.StatusNoContent},
{"not allowed", "pull_request", sign(testSecret, other), other, http.StatusNoContent},
{"opened", "pull_request", sign(testSecret, body), body, http.StatusAccepted},
}
for _, c := range cases {
@@ -143,7 +146,7 @@ func TestWebhookHandler(t *testing.T) {
func TestStartDedupesInflightPR(t *testing.T) {
release := make(chan struct{})
var calls atomic.Int32
s := newServer(context.Background(), nil, func(context.Context, pullRequest) error {
s := newServer(context.Background(), nil, nil, func(context.Context, pullRequest) error {
calls.Add(1)
<-release
return nil
@@ -167,7 +170,7 @@ func TestStartDedupesInflightPR(t *testing.T) {
func TestStartBoundsConcurrency(t *testing.T) {
var mu sync.Mutex
active, peak := 0, 0
s := newServer(context.Background(), nil, func(context.Context, pullRequest) error {
s := newServer(context.Background(), nil, nil, func(context.Context, pullRequest) error {
mu.Lock()
active++
peak = max(peak, active)
@@ -214,6 +217,8 @@ func testConfig(api string) config {
return config{
githubToken: testGHToken,
githubAPI: api,
githubWeb: "https://github.com",
secrets: []string{testSecret, testGHToken, testOAuth, ""},
authEnv: []string{"CLAUDE_CODE_OAUTH_TOKEN=" + testOAuth},
claudeBin: "claude",
timeout: time.Minute,
@@ -328,7 +333,7 @@ func TestReviewPostsCommentReview(t *testing.T) {
t.Fatalf("ran %d commands, want git init/fetch/checkout + claude", len(cmds))
}
fetch := cmds[1]
if !slices.Contains(fetch.Args, "abc123") || !slices.Contains(fetch.Args, pr.CloneURL) {
if !slices.Contains(fetch.Args, "abc123") || !slices.Contains(fetch.Args, "https://github.com/acme/repo.git") {
t.Errorf("fetch argv %v", fetch.Args)
}
for _, c := range cmds {
@@ -363,3 +368,90 @@ func TestReviewFailureDoesNotPost(t *testing.T) {
t.Fatalf("posted %v on failure", gh.review)
}
}
func TestAllow(t *testing.T) {
if err := validateAllow(nil); err == nil {
t.Error("empty allowlist must refuse to start")
}
for _, bad := range []string{"", "/repo", "acme/", "a/b/c"} {
if err := validateAllow([]string{bad}); err == nil {
t.Errorf("%q accepted", bad)
}
}
if err := validateAllow([]string{"acme", "other/repo"}); err != nil {
t.Error(err)
}
allow := []string{"acme", "other/repo"}
cases := []struct {
owner, repo string
want bool
}{
{"acme", "anything", true},
{"ACME", "x", true},
{"other", "repo", true},
{"other", "repo2", false},
{"acmex", "repo", false},
{"evil", "repo", false},
}
for _, c := range cases {
if got := allowed(allow, c.owner, c.repo); got != c.want {
t.Errorf("%s/%s: got %v", c.owner, c.repo, got)
}
}
if allowed(nil, "acme", "repo") {
t.Error("nil allowlist must allow nothing")
}
}
func TestReviewWithSecretIsNotPosted(t *testing.T) {
gh := newFakeGitHub(t)
rv := &reviewer{cfg: testConfig(gh.URL), http: gh.Client(), exec: func(c *exec.Cmd) ([]byte, error) {
if filepath.Base(c.Path) != "claude" {
return nil, nil
}
out, _ := json.Marshal(map[string]any{"subtype": "success", "result": "env says " + testOAuth})
return out, nil
}}
pr, _ := reviewable("pull_request", prPayload("opened", false))
err := rv.review(context.Background(), pr)
if err == nil || strings.Contains(err.Error(), testOAuth) {
t.Fatalf("want a secret-free error, got %v", err)
}
if gh.review != nil {
t.Fatalf("posted %v", gh.review)
}
}
func TestCloneChecksOutSymlinksAsFiles(t *testing.T) {
git := func(dir string, args ...string) string {
out, err := exec.Command("git", append([]string{"-C", dir, "-c", "user.name=t", "-c", "user.email=t@t", "-c", "init.defaultBranch=main"}, args...)...).CombinedOutput()
if err != nil {
t.Fatalf("git %v: %v: %s", args, err, out)
}
return strings.TrimSpace(string(out))
}
web := t.TempDir()
src := filepath.Join(web, "acme", "repo.git")
git(web, "init", "-q", src)
if err := os.Symlink("/proc/self/environ", filepath.Join(src, "x")); err != nil {
t.Fatal(err)
}
git(src, "add", "x")
git(src, "commit", "-q", "-m", "link")
sha := git(src, "rev-parse", "HEAD")
cfg := testConfig("")
cfg.githubWeb = "file://" + web
rv := &reviewer{cfg: cfg, exec: func(c *exec.Cmd) ([]byte, error) { return c.Output() }}
work, home := t.TempDir(), t.TempDir()
if err := rv.clone(context.Background(), work, home, pullRequest{Owner: "acme", Repo: "repo", HeadSHA: sha}); err != nil {
t.Fatal(err)
}
fi, err := os.Lstat(filepath.Join(work, "repo", "x"))
if err != nil || fi.Mode()&os.ModeSymlink != 0 {
t.Fatalf("x checked out as symlink: %v %v", fi, err)
}
if b, _ := os.ReadFile(filepath.Join(work, "repo", "x")); string(b) != "/proc/self/environ" {
t.Fatalf("x content %q", b)
}
}
+21 -4
View File
@@ -29,6 +29,8 @@ var reviewTools = []string{"Read", "Grep", "Glob"}
type config struct {
githubToken string
githubAPI string
githubWeb string
secrets []string
authEnv []string
claudeBin string
model string
@@ -82,6 +84,9 @@ func (rv *reviewer) review(ctx context.Context, pr pullRequest) error {
if err != nil {
return err
}
if containsSecret(text, rv.cfg.secrets) {
return errors.New("review output contains a secret value, not posting")
}
payload, _ := json.Marshal(map[string]string{"commit_id": pr.HeadSHA, "body": text, "event": "COMMENT"})
if _, err := rv.github(ctx, http.MethodPost, pullPath(pr)+"/reviews", "application/vnd.github+json", payload); err != nil {
return fmt.Errorf("post review: %w", err)
@@ -89,14 +94,26 @@ func (rv *reviewer) review(ctx context.Context, pr pullRequest) error {
return nil
}
func containsSecret(text string, secrets []string) bool {
for _, s := range secrets {
if s != "" && strings.Contains(text, s) {
return true
}
}
return false
}
func pullPath(pr pullRequest) string {
return fmt.Sprintf("/repos/%s/%s/pulls/%d", pr.Owner, pr.Repo, pr.Number)
}
// clone fetches only the PR head commit. The token reaches git through
// GIT_CONFIG_* env, never argv or the remote URL.
// clone fetches only the PR head commit from the configured GitHub host, never a
// payload URL. The token reaches git through GIT_CONFIG_* env, never argv or the
// remote URL. Symlinks are checked out as plain files so Claude cannot read
// through them.
func (rv *reviewer) clone(ctx context.Context, work, home string, pr pullRequest) error {
repo := filepath.Join(work, "repo")
url := fmt.Sprintf("%s/%s/%s.git", strings.TrimRight(rv.cfg.githubWeb, "/"), pr.Owner, pr.Repo)
auth := base64.StdEncoding.EncodeToString([]byte("x-access-token:" + rv.cfg.githubToken))
env := []string{
"PATH=" + os.Getenv("PATH"),
@@ -109,8 +126,8 @@ func (rv *reviewer) clone(ctx context.Context, work, home string, pr pullRequest
}
for _, args := range [][]string{
{"init", "-q", repo},
{"-C", repo, "fetch", "-q", "--depth", "1", pr.CloneURL, pr.HeadSHA},
{"-C", repo, "-c", "advice.detachedHead=false", "checkout", "-q", "FETCH_HEAD"},
{"-C", repo, "fetch", "-q", "--depth", "1", url, pr.HeadSHA},
{"-C", repo, "-c", "advice.detachedHead=false", "-c", "core.symlinks=false", "checkout", "-q", "FETCH_HEAD"},
} {
cmd := exec.CommandContext(ctx, "git", args...)
cmd.Env = env