fix(agentreview): require repo allowlist, pin clone host, block symlinks and secret leaks
This commit is contained in:
@@ -35,30 +35,30 @@ parsing, watch-state comparison, git worktree helpers).
|
||||
## Structure
|
||||
|
||||
```
|
||||
cmd/agentpr/main.go # agentpr CLI (pr + issue create/comment/edit, issue close/reopen, whoami)
|
||||
cmd/watchpr/main.go # watchpr CLI (poll + meaningful-change exit)
|
||||
cmd/agentws/main.go # agentws CLI (new / list / rm / clean / token / credential)
|
||||
cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe ones)
|
||||
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 # agentreview run (diff, shallow clone, claude argv/env, post review)
|
||||
internal/agent/ # shared plumbing:
|
||||
token.go # env config + in-process Gitea-token cache
|
||||
vault.go # AppRole login + read the gitea creds path
|
||||
gitea.go # Gitea REST client (PR/issue create/edit/get, issue state, comments, status, whoami)
|
||||
parse.go # owner/repo#N and owner/repo parsing
|
||||
watch.go # PRState snapshot + MeaningfulChange comparison
|
||||
git.go # git worktree/clone/fetch helpers (os/exec, no go-git)
|
||||
vaultkv.go # AppRole-authenticated Vault client + KV-v2 read/write
|
||||
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)
|
||||
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)
|
||||
scripts/build-rpm.sh # generates completions + packages the RPM with nfpm
|
||||
.woodpecker/ # CI: build, test, pre-commit (PR) + release (tag)
|
||||
dist/ # build output: binaries, completions, RPM (not committed)
|
||||
cmd/agentpr/main.go # agentpr CLI (pr + issue create/comment/edit, issue close/reopen, whoami)
|
||||
cmd/watchpr/main.go # watchpr CLI (poll + meaningful-change exit)
|
||||
cmd/agentws/main.go # agentws CLI (new / list / rm / clean / token / credential)
|
||||
cmd/agentws/prune.go # agentws prune (classify worktrees, remove the safe ones)
|
||||
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)
|
||||
internal/agent/ # shared plumbing:
|
||||
token.go # env config + in-process Gitea-token cache
|
||||
vault.go # AppRole login + read the gitea creds path
|
||||
gitea.go # Gitea REST client (PR/issue create/edit/get, issue state, comments, status, whoami)
|
||||
parse.go # owner/repo#N and owner/repo parsing
|
||||
watch.go # PRState snapshot + MeaningfulChange comparison
|
||||
git.go # git worktree/clone/fetch helpers (os/exec, no go-git)
|
||||
vaultkv.go # AppRole-authenticated Vault client + KV-v2 read/write
|
||||
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)
|
||||
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)
|
||||
scripts/build-rpm.sh # generates completions + packages the RPM with nfpm
|
||||
.woodpecker/ # CI: build, test, pre-commit (PR) + release (tag)
|
||||
dist/ # build output: binaries, completions, RPM (not committed)
|
||||
```
|
||||
|
||||
Every binary is a separate `main` package, so `make build` builds each with its
|
||||
@@ -191,6 +191,12 @@ wrapped per stage (login / read denied / write denied) via `ErrVaultDenied`.
|
||||
`ANTHROPIC_AUTH_TOKEN`/`ANTHROPIC_API_KEY` is set the OAuth token is withheld so
|
||||
a gateway never sees it. Tests swap `reviewer.exec` so no CLI is needed.
|
||||
|
||||
- `agentreview` refuses to start without `--allow`, ignores events from other
|
||||
repos, and clones from `--github-url` + `full_name`, never the payload's
|
||||
`clone_url` (the token would follow it). Symlinks check out as plain files
|
||||
(`core.symlinks=false`), and a review containing any configured secret is
|
||||
not posted.
|
||||
|
||||
- `watchpr` exits 0 with no output changes on `--once` (just prints state).
|
||||
- Background commands are killed at a 2h cap, indistinguishable from a crash.
|
||||
Orchestrators run `watchpr --max-wait 110m ...` and restart it on exit code 3
|
||||
|
||||
@@ -389,14 +389,14 @@ denied. Only key names, actions and the KV version are printed.
|
||||
## agentreview
|
||||
|
||||
`agentreview serve` receives GitHub webhooks on `POST /webhook` (health check on
|
||||
`GET /healthz`). For a `pull_request` event with action `opened`, `reopened` or
|
||||
`GET /healthz`). For a `pull_request` event from a repo in `--allow` with action `opened`, `reopened` or
|
||||
`ready_for_review` on a non-draft PR it acks `202` at once, then in the
|
||||
background fetches the PR diff, shallow-clones the head commit and runs
|
||||
`claude -p` over it, posting the result as a `COMMENT` review. A failed run is
|
||||
logged and nothing is posted.
|
||||
|
||||
```bash
|
||||
agentreview serve --listen :8080 --max-concurrent 2 --timeout 15m \
|
||||
agentreview serve --allow acme,other/repo --listen :8080 --max-concurrent 2 --timeout 15m \
|
||||
--system-prompt /etc/agentreview/prompt.md --model sonnet
|
||||
```
|
||||
|
||||
@@ -404,7 +404,13 @@ PR content is untrusted, so Claude runs with only `Read`, `Grep` and `Glob`,
|
||||
`--restricted` (file tools confined to the review directory, project settings
|
||||
ignored), no MCP servers and a throwaway `HOME`. Its environment carries only
|
||||
`PATH`, `HOME` and the Claude credentials. The GitHub token reaches git through
|
||||
`GIT_CONFIG_*` env, never a URL or argv. Reviews for the same PR never overlap.
|
||||
`GIT_CONFIG_*` env, never a URL or argv, and the clone URL is built from
|
||||
`--github-url` and the repo's `full_name`, never the payload's `clone_url`.
|
||||
Symlinks check out as plain files, and a review containing any configured secret
|
||||
is logged and not posted. Reviews for the same PR never overlap.
|
||||
|
||||
`--allow` (owner or owner/repo, comma-separated) is required; the server refuses
|
||||
to start without it and ignores events from other repos.
|
||||
|
||||
Secrets come from the environment only; the server refuses to start without the
|
||||
webhook secret, a GitHub token and one Claude backend:
|
||||
@@ -417,9 +423,10 @@ webhook secret, a GitHub token and one Claude backend:
|
||||
| `ANTHROPIC_AUTH_TOKEN` / `ANTHROPIC_API_KEY` | gateway or API auth; wins over the OAuth token |
|
||||
| `ANTHROPIC_BASE_URL` | gateway URL, e.g. LiteLLM (optional) |
|
||||
|
||||
Every flag also reads an env var: `AGENTREVIEW_LISTEN`, `AGENTREVIEW_MAX_CONCURRENT`,
|
||||
Every flag also reads an env var: `AGENTREVIEW_ALLOW`, `AGENTREVIEW_LISTEN`, `AGENTREVIEW_MAX_CONCURRENT`,
|
||||
`AGENTREVIEW_TIMEOUT`, `AGENTREVIEW_SYSTEM_PROMPT`, `AGENTREVIEW_MODEL`,
|
||||
`AGENTREVIEW_CLAUDE` (binary path) and `GITHUB_API_URL` (`--github-api`).
|
||||
`AGENTREVIEW_CLAUDE` (binary path), `GITHUB_SERVER_URL` (`--github-url`) and
|
||||
`GITHUB_API_URL` (`--github-api`).
|
||||
|
||||
## Build & package
|
||||
|
||||
|
||||
+63
-21
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user