fix(agentreview): scope git auth to the GitHub host, redact logged errors, cap diff size
This commit is contained in:
@@ -16,6 +16,7 @@ import (
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"slices"
|
||||
@@ -85,9 +86,15 @@ func newServeCmd() *cobra.Command {
|
||||
for _, k := range []string{"CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"} {
|
||||
cfg.secrets = append(cfg.secrets, os.Getenv(k))
|
||||
}
|
||||
allow = cleanAllow(allow)
|
||||
if err := validateAllow(allow); err != nil {
|
||||
return err
|
||||
}
|
||||
for flag, u := range map[string]string{"--github-url": cfg.githubWeb, "--github-api": cfg.githubAPI} {
|
||||
if err := validateBaseURL(u); err != nil {
|
||||
return fmt.Errorf("%s: %w", flag, err)
|
||||
}
|
||||
}
|
||||
if cfg.maxConcurrent < 1 {
|
||||
return errors.New("--max-concurrent must be at least 1")
|
||||
}
|
||||
@@ -128,6 +135,30 @@ func envList(key string) []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func cleanAllow(allow []string) []string {
|
||||
var out []string
|
||||
for _, a := range allow {
|
||||
if a = strings.TrimSpace(a); a != "" {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// validateBaseURL requires https so the GitHub token never crosses plain HTTP;
|
||||
// loopback http is allowed for local testing.
|
||||
func validateBaseURL(raw string) error {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
loopback := u.Hostname() == "127.0.0.1" || u.Hostname() == "localhost"
|
||||
if u.Host == "" || (u.Scheme != "https" && (u.Scheme != "http" || !loopback)) {
|
||||
return fmt.Errorf("%q: want an https:// URL", raw)
|
||||
}
|
||||
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")
|
||||
|
||||
@@ -344,8 +344,19 @@ func TestReviewPostsCommentReview(t *testing.T) {
|
||||
t.Error("github credential leaked into claude env")
|
||||
}
|
||||
}
|
||||
if !slices.Contains(fetch.Env, "GIT_CONFIG_KEY_0=http.extraHeader") {
|
||||
t.Errorf("git fetch is not authenticated via env: %v", fetch.Env)
|
||||
if !slices.Contains(fetch.Env, "GIT_CONFIG_KEY_0=http.https://github.com/.extraHeader") || !slices.Contains(fetch.Env, "GIT_CONFIG_KEY_1=http.followRedirects") {
|
||||
t.Errorf("git fetch auth is not host-scoped via env: %v", fetch.Env)
|
||||
}
|
||||
for _, target := range []struct {
|
||||
url string
|
||||
want bool
|
||||
}{{"https://github.com/acme/repo.git", true}, {"https://evil.example/acme/repo.git", false}, {"https://github.com.evil.example/x", false}} {
|
||||
cmd := exec.Command("git", "config", "--get-urlmatch", "http.extraHeader", target.url)
|
||||
cmd.Env = fetch.Env
|
||||
out, _ := cmd.Output()
|
||||
if got := strings.HasPrefix(string(out), "Authorization: Basic "); got != target.want {
|
||||
t.Errorf("auth header sent to %s: %v, want %v", target.url, got, target.want)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(workDir); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Errorf("temp dir %s not cleaned up", workDir)
|
||||
@@ -381,7 +392,13 @@ func TestAllow(t *testing.T) {
|
||||
if err := validateAllow([]string{"acme", "other/repo"}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
allow := []string{"acme", "other/repo"}
|
||||
allow := cleanAllow([]string{" acme", "", " other/repo ", " "})
|
||||
if !slices.Equal(allow, []string{"acme", "other/repo"}) {
|
||||
t.Fatalf("cleanAllow: %q", allow)
|
||||
}
|
||||
if err := validateAllow(cleanAllow([]string{" ", ""})); err == nil {
|
||||
t.Error("blank-only allowlist must refuse to start")
|
||||
}
|
||||
cases := []struct {
|
||||
owner, repo string
|
||||
want bool
|
||||
@@ -455,3 +472,46 @@ func TestCloneChecksOutSymlinksAsFiles(t *testing.T) {
|
||||
t.Fatalf("x content %q", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateBaseURL(t *testing.T) {
|
||||
for _, ok := range []string{"https://github.com", "https://ghe.example/api/v3", "http://127.0.0.1:8080", "http://localhost"} {
|
||||
if err := validateBaseURL(ok); err != nil {
|
||||
t.Errorf("%s rejected: %v", ok, err)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"http://github.com", "http://127.0.0.1.evil.example", "file:///srv/git", "github.com", "https://", ""} {
|
||||
if err := validateBaseURL(bad); err == nil {
|
||||
t.Errorf("%q accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewErrorIsRedacted(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
|
||||
}
|
||||
return []byte(`{"subtype":"error","is_error":true,"result":"bad token ` + testOAuth + `"}`), &exec.ExitError{Stderr: []byte("auth " + testGHToken + " rejected")}
|
||||
}}
|
||||
pr, _ := reviewable("pull_request", prPayload("opened", false))
|
||||
err := rv.review(context.Background(), pr)
|
||||
if err == nil || strings.Contains(err.Error(), testOAuth) || strings.Contains(err.Error(), testGHToken) || strings.Count(err.Error(), "[REDACTED]") != 2 {
|
||||
t.Fatalf("want redacted error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOversizedDiffFailsReview(t *testing.T) {
|
||||
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(make([]byte, maxGitHubBody+1))
|
||||
}))
|
||||
t.Cleanup(gh.Close)
|
||||
rv := &reviewer{cfg: testConfig(gh.URL), http: gh.Client(), exec: func(c *exec.Cmd) ([]byte, error) {
|
||||
t.Error("nothing may run after an oversized diff")
|
||||
return nil, nil
|
||||
}}
|
||||
pr, _ := reviewable("pull_request", prPayload("opened", false))
|
||||
if err := rv.review(context.Background(), pr); err == nil || !strings.Contains(err.Error(), "exceeds") {
|
||||
t.Fatalf("want size error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,17 @@ func newReviewer(cfg config) reviewFunc {
|
||||
return rv.review
|
||||
}
|
||||
|
||||
const maxGitHubBody = 5 << 20
|
||||
|
||||
// review redacts configured secrets from its error because callers log it.
|
||||
func (rv *reviewer) review(ctx context.Context, pr pullRequest) error {
|
||||
if err := rv.doReview(ctx, pr); err != nil {
|
||||
return errors.New(redact(err.Error(), rv.cfg.secrets))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rv *reviewer) doReview(ctx context.Context, pr pullRequest) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, rv.cfg.timeout)
|
||||
defer cancel()
|
||||
tmp, err := os.MkdirTemp("", "agentreview-")
|
||||
@@ -103,26 +113,38 @@ func containsSecret(text string, secrets []string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func redact(text string, secrets []string) string {
|
||||
for _, s := range secrets {
|
||||
if s != "" {
|
||||
text = strings.ReplaceAll(text, s, "[REDACTED]")
|
||||
}
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
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 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
|
||||
// remote URL, scoped to that host with redirects off. 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)
|
||||
web := strings.TrimRight(rv.cfg.githubWeb, "/")
|
||||
url := fmt.Sprintf("%s/%s/%s.git", web, pr.Owner, pr.Repo)
|
||||
auth := base64.StdEncoding.EncodeToString([]byte("x-access-token:" + rv.cfg.githubToken))
|
||||
env := []string{
|
||||
"PATH=" + os.Getenv("PATH"),
|
||||
"HOME=" + home,
|
||||
"GIT_TERMINAL_PROMPT=0",
|
||||
"GIT_CONFIG_NOSYSTEM=1",
|
||||
"GIT_CONFIG_COUNT=1",
|
||||
"GIT_CONFIG_KEY_0=http.extraHeader",
|
||||
"GIT_CONFIG_COUNT=2",
|
||||
"GIT_CONFIG_KEY_0=http." + web + "/.extraHeader",
|
||||
"GIT_CONFIG_VALUE_0=Authorization: Basic " + auth,
|
||||
"GIT_CONFIG_KEY_1=http.followRedirects",
|
||||
"GIT_CONFIG_VALUE_1=false",
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"init", "-q", repo},
|
||||
@@ -220,10 +242,13 @@ func (rv *reviewer) github(ctx context.Context, method, path, accept string, bod
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, maxGitHubBody+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(data) > maxGitHubBody {
|
||||
return nil, fmt.Errorf("%s %s: response exceeds %d bytes", method, path, maxGitHubBody)
|
||||
}
|
||||
if resp.StatusCode/100 != 2 {
|
||||
return nil, fmt.Errorf("%s %s: %s: %s", method, path, resp.Status, truncate(string(data), 300))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user