diff --git a/docs/cli/agent.md b/docs/cli/agent.md index e413df7220..09844bb8b0 100644 --- a/docs/cli/agent.md +++ b/docs/cli/agent.md @@ -146,6 +146,8 @@ command refuses an unknown one up front. The hosted mint serves these: | `retro` | `actions:read`, `contents:read`, `pull_requests:write`, `issues:write`, `metadata:read` | vertex-ai, github-ro, github-artifacts | | `prioritize` | `contents:read`, `issues:write`, `organization_projects:write`, `metadata:read` | vertex-ai, github-ro | +A `review` agent also gets `readonly_repo: true`, so the repository is mounted read-only in the sandbox: the prompt's "do not edit files" is enforced, not requested. That matches the review harness in fullsend-ai/agents. + Pick the role whose permissions fit what the agent does. An unknown role fails immediately with this table, rather than returning `403` from the mint the first time the agent runs. To use a role the hosted mint does not serve, you diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index ccd70719fe..f9ceb475ca 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -155,6 +155,7 @@ fullsend │ ├── --number # Issue number │ ├── --marker # Sticky marker for idempotent updates (HTML comment or Jira property) │ ├── --keep-history # Append previous content as collapsed history (default true) +│ ├── --only-if-exists # Update an existing marked comment, never create one │ └── --fullsend-dir # .fullsend config directory (resolves keep_history default) ├── post-review # Post sticky PR/MR review comments (formal review is best-effort) │ ├── --forge # Forge backend: github (default) or gitlab diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index 0956c825d6..776a19169f 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -54,7 +54,8 @@ fullsend issues get \ ## `fullsend issues post-comment` Posts a comment with a sticky marker on an issue. On re-runs, finds -the existing comment by its marker and edits in-place. By default, +the existing comment by its marker and its own author (see +[Trust model](#trust-model)) and edits in-place. By default, old content is collapsed into `
` blocks to preserve history; set `keep_history: false` in config.yaml (or pass `--keep-history=false`) to replace the body with no history. @@ -85,8 +86,9 @@ echo "Triage complete. See PR #99." | fullsend issues post-comment \ | `--token` | No | API token (default: env var per tracker) | | `--jira-url` | Jira only | Jira instance URL (default: `$JIRA_BASE_URL`) | | `--jira-email` | Jira only | Jira user email for auth (default: `$JIRA_USER_EMAIL`) | -| `--dry-run` | No | Print what would be posted without making API calls | +| `--dry-run` | No | Print what would be posted without posting or editing anything | | `--keep-history` | No | Append previous content as collapsed history blocks (default: `true`; set `false` to replace in-place) | +| `--only-if-exists` | No | Update an existing comment with this marker but never create one. Use it for an all-clear result, so a findings comment from an earlier run is updated in place (the old findings are kept as collapsed history unless `--keep-history=false`) while a clean first run posts nothing. Only a comment whose author is exactly the identity posting matches; if that identity cannot be resolved, the command fails without posting. | | `--fullsend-dir` | No | Path to `.fullsend` config directory (sources defaults from its `config.yaml` when flags are omitted) | ### Jira marker storage @@ -114,20 +116,19 @@ for how the `tracker` field resolves through the config overlay chain. ## Trust model -Marker-based comment lookup does not verify the comment author. In a -trusted CI environment (the intended deployment) this is safe because -only the bot writes marker-bearing comments. - For GitHub and GitLab, where markers are hidden HTML comments in the -body, an untrusted user who can post issue comments containing your -marker string could cause the bot to edit their comment instead of -creating its own. For Jira, markers are stored as comment entity -properties, which require comment-edit permissions to set — body-text -injection alone cannot spoof a marker. - -Do not use this command in environments where untrusted users can write -arbitrary issue comments bearing your marker (GitHub/GitLab) or have -comment-edit permissions (Jira). +body, an existing comment is edited only when it carries the marker +**and** its author is exactly the identity the command posts as. A +comment anyone else wrote with the same marker is ignored, never edited. +If that identity cannot be resolved after a short retry, the command +fails with an error naming the cause and posts or edits nothing, with or +without `--only-if-exists`; rerun it. Posting a new comment instead would +leave the earlier one behind with content no later run updates. + +For Jira, markers are stored as comment entity properties, which require +comment-edit permissions to set — body-text injection alone cannot spoof +a marker. Do not use this command where untrusted users have +comment-edit permissions on your Jira project. ## Environment variables diff --git a/internal/agentnew/postscript_exec_test.go b/internal/agentnew/postscript_exec_test.go index 0ad06c0acf..553c86fe2c 100644 --- a/internal/agentnew/postscript_exec_test.go +++ b/internal/agentnew/postscript_exec_test.go @@ -130,3 +130,185 @@ func TestGeneratedPostScriptRunsFromTheRunDirectory(t *testing.T) { } }) } + +// TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging feeds a status +// that carries a line break (LF, CR alone, or CRLF) and a workflow-command +// prefix. The rejection message must stay on one line and must not reproduce +// the injected line, because the script's stderr lands in the runner log +// where `::` at line start is interpreted as a command. +func TestGeneratedPostScriptFlattensAnInvalidStatusBeforeLogging(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + script := renderPostScriptTo(t, t.TempDir()) + for name, brk := range map[string]string{"LF": "\n", "CR": "\r", "CRLF": "\r\n"} { + t.Run(name, func(t *testing.T) { + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{ + "status": "bogus" + brk + "::error::injected", + "summary": "s", + "comment": "c", + }, + }) + _, stderr, err := runPostScript(t, script, runDir) + if err == nil { + t.Fatal("expected the script to reject an invalid status") + } + if !strings.Contains(stderr, "status must be ok, findings or error") { + t.Fatalf("expected the status rejection, got stderr:\n%s", stderr) + } + for _, line := range strings.FieldsFunc(stderr, func(r rune) bool { return r == '\n' || r == '\r' }) { + if strings.HasPrefix(line, "::") { + t.Fatalf("model-supplied status reached the log as its own line: %q", line) + } + } + if strings.ContainsRune(stderr, '\r') || strings.Count(strings.TrimSpace(stderr), "\n") != 0 { + t.Fatalf("rejection must be a single log line, got: %q", stderr) + } + }) + } +} + +// TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho runs the script +// with bash's xpg_echo option on, where `echo` interprets backslash escapes. +// A status carrying a literal backslash-n must still be logged on one line. +func TestGeneratedPostScriptDoesNotExpandEscapesUnderXpgEcho(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{ + "status": `bogus\n::error::injected`, + "summary": "s", + "comment": "c", + }, + }) + cmd := exec.Command("bash", "-O", "xpg_echo", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + DryRunEnvVar("lint-docs")+"=1", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err == nil { + t.Fatal("expected the script to reject an invalid status") + } + out := strings.TrimSpace(stderr.String()) + if strings.Count(out, "\n") != 0 { + t.Fatalf("backslash escapes were expanded into a new log line:\n%s", out) + } + if !strings.Contains(out, `bogus\n::error::injected`) { + t.Fatalf("expected the literal value on the single line, got: %q", out) + } +} + +// TestGeneratedPostScriptOkDryRunPostsNothing pins the ok path under dry +// run: the script exits 0 and says nothing was posted, without looking for +// an earlier comment. The live path is covered by the stubbed-fullsend tests +// below; the author check it relies on is tested in internal/cli. +func TestGeneratedPostScriptOkDryRunPostsNothing(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + stdout, stderr, err := runPostScript(t, script, runDir) + if err != nil { + t.Fatalf("ok status must exit 0, got %v; stderr:\n%s", err, stderr) + } + if !strings.Contains(stderr, "nothing to post") { + t.Fatalf("expected the nothing-to-post notice, got stderr:\n%s", stderr) + } + if strings.TrimSpace(stdout) != "" { + t.Fatalf("ok under dry run must print no comment body, got:\n%s", stdout) + } +} + +// TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists runs the +// live ok path (no dry run) against a stub `fullsend` on PATH that records +// its arguments. The script must delegate the "is there an earlier findings +// comment" decision to `fullsend issues post-comment --only-if-exists` +// rather than reimplementing it with raw API calls in shell. +func TestGeneratedPostScriptOkReplacesEarlierFindingsViaOnlyIfExists(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + binDir := t.TempDir() + argsFile := filepath.Join(binDir, "args") + stub := "#!/usr/bin/env bash\nif [[ \"$*\" == *--help* ]]; then echo ' --only-if-exists update an existing comment but never create one'; exit 0; fi\nprintf '%s\\n' \"$@\" > " + argsFile + "\ncat >/dev/null\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + cmd := exec.Command("bash", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH"), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + t.Fatalf("ok live path must exit 0, got %v; stderr:\n%s", err, stderr.String()) + } + got, err := os.ReadFile(argsFile) + if err != nil { + t.Fatalf("the script never invoked fullsend on the ok path: %v; stderr:\n%s", err, stderr.String()) + } + args := string(got) + for _, want := range []string{"issues\npost-comment\n", "--only-if-exists\n", "--marker\n", "fullsend-ai/demo\n", "99\n"} { + if !strings.Contains(args, want) { + t.Errorf("fullsend was called without %q; args:\n%s", strings.TrimSpace(want), args) + } + } +} + +// TestGeneratedPostScriptOkOnAnOlderFullsendPostsNothing pins the +// degradation path: the runner's fullsend is pinned by the repository, not +// by the CLI that generated the script, so when its post-comment has no +// --only-if-exists the ok path must post nothing and exit 0 rather than fail +// on an unknown flag. +func TestGeneratedPostScriptOkOnAnOlderFullsendPostsNothing(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not installed; the generated post-script needs it") + } + binDir := t.TempDir() + argsFile := filepath.Join(binDir, "args") + // An older CLI: --help lists no --only-if-exists, and any real call + // with that flag would fail — so the stub fails loudly if invoked to post. + stub := "#!/usr/bin/env bash\nif [[ \"$*\" == *--help* ]]; then echo ' --dry-run print what would be posted'; exit 0; fi\nprintf '%s\\n' \"$@\" > " + argsFile + "\necho 'Error: unknown flag: --only-if-exists' >&2; exit 1\n" + if err := os.WriteFile(filepath.Join(binDir, "fullsend"), []byte(stub), 0o755); err != nil { + t.Fatal(err) + } + script := renderPostScriptTo(t, t.TempDir()) + runDir := writeRunDir(t, map[string]any{ + "iteration-1": map[string]any{"status": "ok", "summary": "All clear", "comment": "All added documentation links resolve."}, + }) + cmd := exec.Command("bash", script) + cmd.Dir = runDir + cmd.Env = append(os.Environ(), + "PATH="+binDir+string(os.PathListSeparator)+os.Getenv("PATH"), + "ISSUE_URL=https://github.com/fullsend-ai/demo/pull/99", + "GH_TOKEN=test-token", + ) + var stderr strings.Builder + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + t.Fatalf("ok on an older fullsend must exit 0, got %v; stderr:\n%s", err, stderr.String()) + } + if !strings.Contains(stderr.String(), "nothing to post") { + t.Fatalf("expected the nothing-to-post notice, got:\n%s", stderr.String()) + } + if _, err := os.Stat(argsFile); err == nil { + t.Fatalf("an older fullsend must not be asked to post on the ok path") + } +} diff --git a/internal/agentnew/render.go b/internal/agentnew/render.go index 5e917bc0d8..ca0ed2935d 100644 --- a/internal/agentnew/render.go +++ b/internal/agentnew/render.go @@ -105,6 +105,7 @@ func buildHarness(opts Options, role Role) (*harness.Harness, error) { Effort: opts.Effort, PostScript: "scripts/post-" + opts.Name + ".sh", TimeoutMinutes: opts.TimeoutMinutes, + ReadonlyRepo: role.ReadonlyRepo, Trigger: opts.Trigger, Env: &harness.EnvConfig{ Runner: map[string]string{ diff --git a/internal/agentnew/render_test.go b/internal/agentnew/render_test.go index 64515f25be..6268f1b479 100644 --- a/internal/agentnew/render_test.go +++ b/internal/agentnew/render_test.go @@ -375,6 +375,12 @@ func TestRoleImageReachesTheHarness(t *testing.T) { if h.OpenShell == nil || !reflect.DeepEqual(h.OpenShell.Profiles, role.Profiles) { t.Errorf("role %q: profiles = %v, want %v", name, h.OpenShell, role.Profiles) } + // readonly_repo must survive into the emitted YAML, not only sit on + // the Role struct: a generated review harness that ships writable + // turns "do not edit files" back into a request. + if h.ReadonlyRepo != role.ReadonlyRepo || h.ReadonlyRepo != (name == "review") { + t.Errorf("role %q: readonly_repo = %v, want %v", name, h.ReadonlyRepo, name == "review") + } seen[role.Image] = true } // Both image constants must be reachable, or one is dead configuration. diff --git a/internal/agentnew/roles.go b/internal/agentnew/roles.go index 461672b81b..81e2aaab2f 100644 --- a/internal/agentnew/roles.go +++ b/internal/agentnew/roles.go @@ -38,6 +38,10 @@ type Role struct { Profiles []string // Image is the sandbox image this role's agents run under. Image string + // ReadonlyRepo mirrors the fleet: the review harness mounts the target + // repository read-only so the prompt's "do not edit files" is enforced, + // not requested. Set for roles whose fleet harness sets `readonly_repo`. + ReadonlyRepo bool } // roleTable is the set of roles `agent new` will generate for. Excluded on @@ -60,9 +64,10 @@ var roleTable = map[string]Role{ "contents": "read", "pull_requests": "write", "issues": "write", "checks": "read", "metadata": "read", }, - Providers: []string{"providers/vertex-ai.yaml", "providers/github-ro.yaml"}, - Profiles: []string{"profiles/fullsend-vertex-ai.yaml", "profiles/fullsend-github-ro.yaml"}, - Image: config.DefaultCodeImage, + Providers: []string{"providers/vertex-ai.yaml", "providers/github-ro.yaml"}, + Profiles: []string{"profiles/fullsend-vertex-ai.yaml", "profiles/fullsend-github-ro.yaml"}, + Image: config.DefaultCodeImage, + ReadonlyRepo: true, }, "coder": { Name: "coder", diff --git a/internal/agentnew/roles_test.go b/internal/agentnew/roles_test.go index 0208526ac0..faaa741333 100644 --- a/internal/agentnew/roles_test.go +++ b/internal/agentnew/roles_test.go @@ -126,3 +126,16 @@ func TestCoderUsesEmbeddedGithubProvider(t *testing.T) { t.Errorf("coder should use providers/github.yaml, got %v", role.Providers) } } + +// TestReviewRoleMountsTheRepositoryReadOnly pins the fleet parity the +// authoring skill relies on: the review harness in fullsend-ai/agents sets +// readonly_repo, and the prompt's "do not edit files" is enforcement only if +// the generated harness does too. +func TestReviewRoleMountsTheRepositoryReadOnly(t *testing.T) { + for _, r := range roleTable { + want := r.Name == "review" + if r.ReadonlyRepo != want { + t.Errorf("role %s: ReadonlyRepo = %v, want %v", r.Name, r.ReadonlyRepo, want) + } + } +} diff --git a/internal/agentnew/templates/post.sh.tmpl b/internal/agentnew/templates/post.sh.tmpl index 7a049dd895..d1f53490a8 100644 --- a/internal/agentnew/templates/post.sh.tmpl +++ b/internal/agentnew/templates/post.sh.tmpl @@ -81,7 +81,16 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end' case "${status}" in ok|findings|error) ;; - *) echo "post-__AGENT_NAME__: status must be ok, findings or error (got '${status}')" >&2; exit 1 ;; + *) + # status is model output: never echo it raw. A value carrying CR/LF would + # split the runner's log line (a workflow-command injection vector), so + # flatten it and cap it before it reaches stderr. + shown="${status//[$'\r\n']/ }" + # printf '%s' never interprets backslash escapes; echo does under xpg_echo, + # so a literal "\n" in the value could still forge a log line through echo. + printf '%s\n' "post-__AGENT_NAME__: status must be ok, findings or error (got '${shown:0:40}')" >&2 + exit 1 + ;; esac [[ -n "${summary}" ]] || { echo "post-__AGENT_NAME__: summary is required" >&2; exit 1; } if [[ "${summary}" == *$'\n'* || "${summary}" == *$'\r'* ]]; then @@ -102,11 +111,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-__AGENT_NAME__: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -117,6 +121,42 @@ fi REPO="${BASH_REMATCH[1]}" NUMBER="${BASH_REMATCH[3]}" +# On ok, post nothing — unless an earlier run left a findings comment on +# this work item. The harness trigger fires again on later pushes, so a +# problem the author has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend replace that comment with the all-clear, +# and post nothing when there is no earlier comment. It matches only a +# comment carrying this marker whose author is exactly the login fullsend +# posts as, so a comment anyone else planted with the marker is never +# edited. When that login cannot be resolved it exits non-zero without +# posting; under `set -e` this script, and so the run, then fails +# visibly — rerun it. +if [[ "${status}" == "ok" ]]; then + if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then + echo "post-__AGENT_NAME__: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + exit 0 + fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then + echo "post-__AGENT_NAME__: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 + exit 0 + fi + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 +fi + if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then printf '**%s**\n\n%s\n' "${summary}" "${comment}" echo "post-__AGENT_NAME__: dry run, not posting" >&2 @@ -124,8 +164,8 @@ if [[ "${__DRY_RUN_VAR__:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# finds this agent's previous comment by marker and its own author and edits +# it in place, so re-runs do not flood the work item. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/agentnew/testdata/golden/triage.txt b/internal/agentnew/testdata/golden/triage.txt index 8c518de616..b53db91fee 100644 --- a/internal/agentnew/testdata/golden/triage.txt +++ b/internal/agentnew/testdata/golden/triage.txt @@ -233,7 +233,16 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end' case "${status}" in ok|findings|error) ;; - *) echo "post-lint-docs: status must be ok, findings or error (got '${status}')" >&2; exit 1 ;; + *) + # status is model output: never echo it raw. A value carrying CR/LF would + # split the runner's log line (a workflow-command injection vector), so + # flatten it and cap it before it reaches stderr. + shown="${status//[$'\r\n']/ }" + # printf '%s' never interprets backslash escapes; echo does under xpg_echo, + # so a literal "\n" in the value could still forge a log line through echo. + printf '%s\n' "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2 + exit 1 + ;; esac [[ -n "${summary}" ]] || { echo "post-lint-docs: summary is required" >&2; exit 1; } if [[ "${summary}" == *$'\n'* || "${summary}" == *$'\r'* ]]; then @@ -254,11 +263,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-lint-docs: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -269,6 +273,42 @@ fi REPO="${BASH_REMATCH[1]}" NUMBER="${BASH_REMATCH[3]}" +# On ok, post nothing — unless an earlier run left a findings comment on +# this work item. The harness trigger fires again on later pushes, so a +# problem the author has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend replace that comment with the all-clear, +# and post nothing when there is no earlier comment. It matches only a +# comment carrying this marker whose author is exactly the login fullsend +# posts as, so a comment anyone else planted with the marker is never +# edited. When that login cannot be resolved it exits non-zero without +# posting; under `set -e` this script, and so the run, then fails +# visibly — rerun it. +if [[ "${status}" == "ok" ]]; then + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then + echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + exit 0 + fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then + echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 + exit 0 + fi + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 +fi + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then printf '**%s**\n\n%s\n' "${summary}" "${comment}" echo "post-lint-docs: dry run, not posting" >&2 @@ -276,8 +316,8 @@ if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# finds this agent's previous comment by marker and its own author and edits +# it in place, so re-runs do not flood the work item. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/agentnew/testdata/golden/validation-loop.txt b/internal/agentnew/testdata/golden/validation-loop.txt index 3253350e5b..61cfa1480b 100644 --- a/internal/agentnew/testdata/golden/validation-loop.txt +++ b/internal/agentnew/testdata/golden/validation-loop.txt @@ -241,7 +241,16 @@ comment=$(jq -r 'if (.comment | type) == "string" then .comment else empty end' case "${status}" in ok|findings|error) ;; - *) echo "post-lint-docs: status must be ok, findings or error (got '${status}')" >&2; exit 1 ;; + *) + # status is model output: never echo it raw. A value carrying CR/LF would + # split the runner's log line (a workflow-command injection vector), so + # flatten it and cap it before it reaches stderr. + shown="${status//[$'\r\n']/ }" + # printf '%s' never interprets backslash escapes; echo does under xpg_echo, + # so a literal "\n" in the value could still forge a log line through echo. + printf '%s\n' "post-lint-docs: status must be ok, findings or error (got '${shown:0:40}')" >&2 + exit 1 + ;; esac [[ -n "${summary}" ]] || { echo "post-lint-docs: summary is required" >&2; exit 1; } if [[ "${summary}" == *$'\n'* || "${summary}" == *$'\r'* ]]; then @@ -262,11 +271,6 @@ if (( ${#comment} > MAX_COMMENT_CHARS )); then comment="${comment:0:${keep}}${TRUNCATION_MARKER}" fi -if [[ "${status}" == "ok" ]]; then - echo "post-lint-docs: status=ok, nothing to post" >&2 - exit 0 -fi - # Derive the repo and number from the work item URL rather than trusting extra # environment. The pattern also rejects anything that is not a github.com URL. url_re='^https://github[.]com/([A-Za-z0-9._-]+/[A-Za-z0-9._-]+)/(issues|pull)/([0-9]+)$' @@ -277,6 +281,42 @@ fi REPO="${BASH_REMATCH[1]}" NUMBER="${BASH_REMATCH[3]}" +# On ok, post nothing — unless an earlier run left a findings comment on +# this work item. The harness trigger fires again on later pushes, so a +# problem the author has since fixed would otherwise stay reported. +# --only-if-exists makes fullsend replace that comment with the all-clear, +# and post nothing when there is no earlier comment. It matches only a +# comment carrying this marker whose author is exactly the login fullsend +# posts as, so a comment anyone else planted with the marker is never +# edited. When that login cannot be resolved it exits non-zero without +# posting; under `set -e` this script, and so the run, then fails +# visibly — rerun it. +if [[ "${status}" == "ok" ]]; then + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then + echo "post-lint-docs: status=ok, nothing to post (dry run: did not check for an earlier findings comment to replace)" >&2 + exit 0 + fi + # The runner's fullsend may predate --only-if-exists (it is pinned by the + # repository's fullsend-ref, not by the CLI that generated this script). + # Detect the flag instead of assuming it: on an older CLI, keep the old + # behaviour — post nothing — rather than fail the common ok path. + # grep reads the whole help text (no -q): an early exit could SIGPIPE + # fullsend and, under pipefail, read as "flag missing". + if ! fullsend issues post-comment --help 2>&1 | grep -- '--only-if-exists' >/dev/null; then + echo "post-lint-docs: status=ok, nothing to post (this fullsend has no --only-if-exists; an earlier findings comment, if any, stays until a later run with findings)" >&2 + exit 0 + fi + printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ + | fullsend issues post-comment \ + --tracker github \ + --project "${REPO}" \ + --number "${NUMBER}" \ + --marker "${MARKER}" \ + --only-if-exists \ + --result - + exit 0 +fi + if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then printf '**%s**\n\n%s\n' "${summary}" "${comment}" echo "post-lint-docs: dry run, not posting" >&2 @@ -284,8 +324,8 @@ if [[ "${POST_LINT_DOCS_DRY_RUN:-}" == "1" ]]; then fi # fullsend issues post-comment is the repo's sticky-comment primitive: it -# finds this agent's previous comment by marker and edits it in place, so -# re-runs do not flood the work item. +# finds this agent's previous comment by marker and its own author and edits +# it in place, so re-runs do not flood the work item. printf '**%s**\n\n%s\n' "${summary}" "${comment}" \ | fullsend issues post-comment \ --tracker github \ diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 928c1e8e27..ff4e9ef23a 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -8,6 +8,7 @@ import ( "os" "slices" "strings" + "time" "github.com/spf13/cobra" @@ -169,17 +170,18 @@ func runIssuesGet(ctx context.Context, cfg *issuesGetConfig) error { // issuesPostCommentConfig holds the flags and test overrides for // "fullsend issues post-comment". type issuesPostCommentConfig struct { - trackerName string - project string - number int - marker string - result string - token string - jiraURL string - jiraEmail string - dryRun bool - keepHistory *bool // nil = resolve from config; non-nil = explicit flag - fullsendDir string + trackerName string + project string + number int + marker string + result string + token string + jiraURL string + jiraEmail string + dryRun bool + onlyIfExists bool + keepHistory *bool // nil = resolve from config; non-nil = explicit flag + fullsendDir string // Test overrides — when non-nil, used instead of creating a real // tracker client. Not set by CLI flag parsing. @@ -200,7 +202,8 @@ func newIssuesPostCommentCmd() *cobra.Command { Short: "Post or update a sticky comment on an issue", Long: `Posts a comment with a sticky marker on an issue. On first run, creates a new comment. On re-runs, finds the existing comment -by its marker and edits in-place, collapsing old content into +by its marker and its own author and edits in-place, collapsing old +content into
blocks. This prevents comment flooding on re-runs. Works across GitHub, GitLab, and Jira via --tracker. @@ -211,14 +214,12 @@ For --tracker jira, the marker is stored as an invisible comment entity property rather than embedded in the visible comment body, so marker character restrictions do not apply. -Trust model: marker-based comment lookup does not verify the comment -author. In a trusted CI environment (the intended deployment) this -is safe because only the bot writes marker-bearing comments. If -untrusted users can post issue comments containing the marker -string, they could cause the bot to edit their comment instead of -creating its own. Do not use this command in environments where -untrusted users can write arbitrary issue comments bearing your -marker. +Trust model (GitHub, GitLab): an existing comment is edited only when +it carries the marker and its author is exactly the identity this +command posts as. A comment anyone else wrote with the same marker is +ignored, never edited. If that identity cannot be resolved after a +short retry, the command fails without posting or editing anything; +rerun it. --tracker is required unless a default is supplied via config: set "tracker: github|gitlab|jira" in config.yaml and pass --fullsend-dir @@ -241,7 +242,8 @@ The --result flag accepts a file path or "-" for stdin.`, cmd.Flags().StringVar(&cfg.token, "token", "", "API token (default: env var per tracker)") cmd.Flags().StringVar(&cfg.jiraURL, "jira-url", "", "Jira instance URL (default: $JIRA_BASE_URL)") cmd.Flags().StringVar(&cfg.jiraEmail, "jira-email", "", "Jira user email for Basic auth (default: $JIRA_USER_EMAIL)") - cmd.Flags().BoolVar(&cfg.dryRun, "dry-run", false, "print what would be posted without making API calls") + cmd.Flags().BoolVar(&cfg.dryRun, "dry-run", false, "print what would be posted without posting or editing anything") + cmd.Flags().BoolVar(&cfg.onlyIfExists, "only-if-exists", false, "update an existing comment with this marker but never create one (for an all-clear that should replace earlier findings)") cmd.Flags().BoolVar(&keepHistory, "keep-history", true, "append previous content as collapsed history blocks (set false to replace in-place)") cmd.Flags().StringVar(&cfg.fullsendDir, "fullsend-dir", "", "path to .fullsend config directory (sources defaults from its config.yaml when flags are omitted)") _ = cmd.MarkFlagRequired("project") @@ -293,9 +295,10 @@ func runIssuesPostComment(ctx context.Context, cfg *issuesPostCommentConfig) err } stickyCfg := sticky.Config{ - Marker: cfg.marker, - DryRun: cfg.dryRun, - KeepHistory: keepHistory, + Marker: cfg.marker, + DryRun: cfg.dryRun, + KeepHistory: keepHistory, + OnlyIfExists: cfg.onlyIfExists, } if trackerName == trackerJira { // The Jira write path routes every body through @@ -374,6 +377,11 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project return "", nil // Jira has no stable comment permalink } + if cfg.OnlyIfExists { + printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") + return "", nil + } + printer.StepStart("No existing comment found, creating new one") if cfg.DryRun { @@ -395,11 +403,12 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project // sticky.Post: find an existing comment bearing the marker, collapse // old content into history, and create or update in-place. // -// Unlike sticky.Post, this function does not perform bot-user -// verification for marker spoofing protection (tracker.Client has no -// GetAuthenticatedUser method). This is acceptable because the new -// command is used by agents in trusted CI environments, not by -// untrusted external callers. +// It never edits a comment it cannot verify as its own: an existing +// comment matches only when it carries the marker and its author is +// exactly the login this client posts as, so a comment anyone could plant +// with the same marker is ignored. When that login cannot be resolved +// (after a short retry) it returns an error and posts nothing, with or +// without OnlyIfExists. func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project string, number int, body string, cfg sticky.Config, printer *ui.Printer) (string, error) { if strings.TrimSpace(body) == "" { return "", fmt.Errorf("comment body is empty") @@ -408,12 +417,20 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return "", fmt.Errorf("marker is empty") } + // Without a verified identity nothing is posted at all: editing would + // trust an unverified comment, and creating a new one would orphan the + // earlier comment, whose stale content later runs would never update. + self, err := resolveTrackerSelf(ctx, tc) + if err != nil { + return "", fmt.Errorf("cannot verify which identity this command posts as, so no comment was posted or edited (rerun to retry): %w", err) + } + comments, err := tc.ListComments(ctx, project, number) if err != nil { return "", fmt.Errorf("listing comments: %w", err) } - existing := findMarkedTrackerComment(comments, cfg.Marker) + existing := findMarkedTrackerComment(comments, cfg.Marker, self) markedBody := cfg.Marker + "\n" + body if existing != nil { @@ -434,6 +451,11 @@ func postTrackerStickyComment(ctx context.Context, tc tracker.Client, project st return existing.HTMLURL, nil } + if cfg.OnlyIfExists { + printer.StepInfo("No existing comment with this marker; nothing to post (--only-if-exists)") + return "", nil + } + printer.StepStart("No existing comment found, creating new one") if cfg.DryRun { @@ -515,11 +537,59 @@ func resolveKeepHistory(flag *bool, fullsendDir string, testConfigReader config. return true, nil } +// authenticatedUserResolver is implemented by tracker clients that can +// report who they are authenticated as (tracker.ForgeClient). +type authenticatedUserResolver interface { + AuthenticatedUser(ctx context.Context) (string, error) +} + +// selfLookupBackoff is the wait before each retry of the identity lookup; +// its length is the number of retries. Tests shorten it. +var selfLookupBackoff = []time.Duration{500 * time.Millisecond, time.Second} + +// resolveTrackerSelf returns the exact login tc posts as, retrying a failed +// lookup per selfLookupBackoff so a transient error does not fail the run. +// For GitHub this goes through forge.Client.GetAuthenticatedUser, which +// also resolves an App installation token (GraphQL viewer) where GET /user +// is refused. +func resolveTrackerSelf(ctx context.Context, tc tracker.Client) (string, error) { + ar, ok := tc.(authenticatedUserResolver) + if !ok { + return "", fmt.Errorf("this tracker cannot report the authenticated user") + } + var lastErr error + for attempt := 0; ; attempt++ { + self, err := ar.AuthenticatedUser(ctx) + if err == nil && self == "" { + err = fmt.Errorf("the authenticated user is empty") + } + if err == nil { + return self, nil + } + lastErr = err + if attempt >= len(selfLookupBackoff) { + return "", fmt.Errorf("after %d attempts: %w", attempt+1, lastErr) + } + select { + case <-ctx.Done(): + return "", fmt.Errorf("%w (last lookup error: %v)", ctx.Err(), lastErr) + case <-time.After(selfLookupBackoff[attempt]): + } + } +} + // findMarkedTrackerComment returns the first tracker comment whose body -// contains the given marker string, or nil if none is found. This is -// the tracker.Comment equivalent of sticky.FindMarkedComment. -func findMarkedTrackerComment(comments []tracker.Comment, marker string) *tracker.Comment { +// contains the given marker string and whose author is exactly self, or nil +// if none is found. An empty self matches nothing: a comment whose author +// cannot be verified is never returned for editing. +func findMarkedTrackerComment(comments []tracker.Comment, marker, self string) *tracker.Comment { + if self == "" { + return nil + } for i := range comments { + if comments[i].Author != self { + continue + } if strings.Contains(string(comments[i].Body), marker) { return &comments[i] } diff --git a/internal/cli/issues_test.go b/internal/cli/issues_test.go index 066448f51d..86fe915b59 100644 --- a/internal/cli/issues_test.go +++ b/internal/cli/issues_test.go @@ -4,12 +4,14 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "os" "path/filepath" "strings" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -75,14 +77,19 @@ func TestNewIssuesPostCommentCmd_DefaultFlags(t *testing.T) { func TestFindMarkedTrackerComment(t *testing.T) { marker := "" comments := []tracker.Comment{ - {ID: "1", Body: "irrelevant comment"}, - {ID: "2", Body: tracker.Body(marker + "\nsome content")}, - {ID: "3", Body: "another comment"}, + {ID: "1", Body: "irrelevant comment", Author: "bot"}, + {ID: "0", Body: tracker.Body(marker + "\nauthorless")}, + {ID: "2", Body: tracker.Body(marker + "\nplanted"), Author: "mallory"}, + {ID: "3", Body: tracker.Body(marker + "\nsome content"), Author: "bot"}, + {ID: "4", Body: "another comment", Author: "bot"}, } - found := findMarkedTrackerComment(comments, marker) + found := findMarkedTrackerComment(comments, marker, "bot") require.NotNil(t, found) - assert.Equal(t, "2", found.ID) + assert.Equal(t, "3", found.ID) + + assert.Nil(t, findMarkedTrackerComment(comments, marker, ""), + "an unverified self must never match a comment for editing") } func TestFindMarkedTrackerComment_NotFound(t *testing.T) { @@ -90,12 +97,12 @@ func TestFindMarkedTrackerComment_NotFound(t *testing.T) { {ID: "1", Body: "no marker here"}, } - found := findMarkedTrackerComment(comments, "") + found := findMarkedTrackerComment(comments, "", "bot") assert.Nil(t, found) } func TestFindMarkedTrackerComment_Empty(t *testing.T) { - found := findMarkedTrackerComment(nil, "") + found := findMarkedTrackerComment(nil, "", "bot") assert.Nil(t, found) } @@ -168,6 +175,7 @@ func TestPostTrackerStickyComment_EmptyMarker(t *testing.T) { func TestPostTrackerStickyComment_DryRun_Create(t *testing.T) { fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) printer := ui.New(io.Discard) cfg := sticky.Config{Marker: "", DryRun: true, KeepHistory: true} @@ -425,6 +433,7 @@ func TestRunIssuesPostComment_EmptyMarker(t *testing.T) { func TestRunIssuesPostComment_DryRun(t *testing.T) { fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" tc := tracker.NewForgeClient(fc) cfg := &issuesPostCommentConfig{ @@ -1005,3 +1014,284 @@ func TestIssuesPostCommentCmd_TrackerNotRequired(t *testing.T) { assert.NotContains(t, err.Error(), `required flag(s) "tracker"`) assert.Contains(t, err.Error(), "--tracker is required") } + +func TestRunIssuesPostComment_OnlyIfExists_SkipsCreate(t *testing.T) { + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" + tc := tracker.NewForgeClient(fc) + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + + require.NoError(t, runIssuesPostComment(context.Background(), cfg)) + + comments, err := tc.ListComments(context.Background(), "acme/widgets", 42) + require.NoError(t, err) + assert.Empty(t, comments, "only-if-exists must not create a first comment") +} + +func TestRunIssuesPostComment_OnlyIfExists_ReplacesEarlierFindings(t *testing.T) { + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "bot" + tc := tracker.NewForgeClient(fc) + ctx := context.Background() + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: "", + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "2 broken links", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + cfg.onlyIfExists = true + cfg.testBody = "all clear" + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.Contains(t, string(comments[0].Body), "all clear") +} + +func TestRunIssuesPostComment_Jira_OnlyIfExists(t *testing.T) { + tc, _, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") + require.NoError(t, err) + ctx := context.Background() + + cfg := &issuesPostCommentConfig{ + trackerName: trackerJira, + project: "PROJ", + number: 42, + marker: "", + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + // No earlier comment: nothing is created. + require.NoError(t, runIssuesPostComment(ctx, cfg)) + comments, err := tc.ListComments(ctx, "PROJ", 42) + require.NoError(t, err) + assert.Empty(t, comments) + + // An earlier findings comment exists: it is replaced. + cfg.onlyIfExists = false + cfg.testBody = "2 broken links" + require.NoError(t, runIssuesPostComment(ctx, cfg)) + cfg.onlyIfExists = true + cfg.testBody = "all clear" + require.NoError(t, runIssuesPostComment(ctx, cfg)) + comments, err = tc.ListComments(ctx, "PROJ", 42) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.Contains(t, string(comments[0].Body), "all clear") +} + +// fastSelfLookup shortens the identity-lookup retry backoff for a test. +func fastSelfLookup(t *testing.T) { + t.Helper() + saved := selfLookupBackoff + selfLookupBackoff = []time.Duration{time.Millisecond, time.Millisecond} + t.Cleanup(func() { selfLookupBackoff = saved }) +} + +// flakySelfClient fails the identity lookup failures times, then defers to +// the wrapped ForgeClient. +type flakySelfClient struct { + *tracker.ForgeClient + failures int + calls int +} + +func (c *flakySelfClient) AuthenticatedUser(ctx context.Context) (string, error) { + c.calls++ + if c.calls <= c.failures { + return "", errors.New("502 Bad Gateway") + } + return c.ForgeClient.AuthenticatedUser(ctx) +} + +const testBot = "fullsend-ai-review[bot]" + +// postAfterCommentBy seeds one marker comment written by author, then runs +// post-comment as testBot through tc (a *flakySelfClient wrapping fc, so the +// identity lookup can be made to fail). It returns the run's error and the +// comments afterwards. +func postAfterCommentBy(t *testing.T, author string, onlyIfExists bool, failures int) (error, []tracker.Comment, *flakySelfClient) { + t.Helper() + fastSelfLookup(t) + ctx := context.Background() + fc := forge.NewFakeClient() + tc := &flakySelfClient{ForgeClient: tracker.NewForgeClient(fc), failures: failures} + const marker = "" + + fc.AuthenticatedUser = author + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nearlier findings")) + require.NoError(t, err) + + fc.AuthenticatedUser = testBot + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: onlyIfExists, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "new result", + } + runErr := runIssuesPostComment(ctx, cfg) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + return runErr, comments, tc +} + +func TestRunIssuesPostComment_EditsOwnComment(t *testing.T) { + for _, onlyIfExists := range []bool{false, true} { + t.Run(fmt.Sprintf("only-if-exists=%v", onlyIfExists), func(t *testing.T) { + err, comments, _ := postAfterCommentBy(t, testBot, onlyIfExists, 0) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.Contains(t, string(comments[0].Body), "new result") + }) + } +} + +func TestRunIssuesPostComment_IgnoresPlantedMarker(t *testing.T) { + // Login shape is not identity: another user, a different App whose login + // merely shares the "[bot]" suffix, the same name without it, or a prefix + // must not match. + for _, author := range []string{"mallory", "evil-review[bot]", "fullsend-ai-review", "x-fullsend-ai-review[bot]"} { + t.Run(author, func(t *testing.T) { + // Normal path: the planted comment is left alone, a new one posted. + err, comments, _ := postAfterCommentBy(t, author, false, 0) + require.NoError(t, err) + require.Len(t, comments, 2) + assert.NotContains(t, string(comments[0].Body), "new result") + assert.Contains(t, string(comments[1].Body), "new result") + + // --only-if-exists: neither edited nor created. + err, comments, _ = postAfterCommentBy(t, author, true, 0) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.NotContains(t, string(comments[0].Body), "new result") + }) + } +} + +func TestRunIssuesPostComment_TransientSelfFailureRetriesThenEdits(t *testing.T) { + err, comments, tc := postAfterCommentBy(t, testBot, false, len(selfLookupBackoff)) + require.NoError(t, err) + assert.Equal(t, len(selfLookupBackoff)+1, tc.calls, "every retry is used before success") + require.Len(t, comments, 1, "a transient failure must not create a second comment") + assert.Contains(t, string(comments[0].Body), "new result") +} + +func TestRunIssuesPostComment_PersistentSelfFailureErrorsAndPostsNothing(t *testing.T) { + for _, onlyIfExists := range []bool{false, true} { + t.Run(fmt.Sprintf("only-if-exists=%v", onlyIfExists), func(t *testing.T) { + err, comments, tc := postAfterCommentBy(t, testBot, onlyIfExists, 1000) + require.Error(t, err) + assert.Contains(t, err.Error(), "cannot verify which identity") + assert.Contains(t, err.Error(), "rerun") + assert.Contains(t, err.Error(), "502 Bad Gateway", "the error must name the cause") + assert.Equal(t, len(selfLookupBackoff)+1, tc.calls) + require.Len(t, comments, 1, "no comment may be created") + assert.NotContains(t, string(comments[0].Body), "new result", "no comment may be edited") + }) + } +} + +func TestRunIssuesPostComment_EmptySelfErrors(t *testing.T) { + // An empty login with no error is unresolved too, never marker-only. + fastSelfLookup(t) + ctx := context.Background() + fc := forge.NewFakeClient() + tc := tracker.NewForgeClient(fc) + const marker = "" + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nauthorless")) + require.NoError(t, err) + + for _, onlyIfExists := range []bool{false, true} { + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: onlyIfExists, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "new result", + } + err := runIssuesPostComment(ctx, cfg) + require.Error(t, err) + assert.Contains(t, err.Error(), "authenticated user is empty") + } + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.NotContains(t, string(comments[0].Body), "new result") +} + +func TestRunIssuesPostComment_OnlyIfExists_SkipsPlantedCommentBeforeOwn(t *testing.T) { + // The realistic attack order: a planted marker comment listed first, the + // poster's own comment second. The planted one is skipped, the own one + // updated. + ctx := context.Background() + fc := forge.NewFakeClient() + tc := tracker.NewForgeClient(fc) + const marker = "" + + fc.AuthenticatedUser = "mallory" + _, err := tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\nplanted")) + require.NoError(t, err) + fc.AuthenticatedUser = testBot + _, err = tc.CreateComment(ctx, "acme/widgets", 42, tracker.Body(marker+"\n2 broken links")) + require.NoError(t, err) + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + onlyIfExists: true, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "all clear", + } + require.NoError(t, runIssuesPostComment(ctx, cfg)) + + comments, err := tc.ListComments(ctx, "acme/widgets", 42) + require.NoError(t, err) + require.Len(t, comments, 2) + assert.NotContains(t, string(comments[0].Body), "all clear") + assert.Contains(t, string(comments[1].Body), "all clear") +} + +func TestResolveTrackerSelf_StopsRetryingWhenCancelled(t *testing.T) { + saved := selfLookupBackoff + selfLookupBackoff = []time.Duration{time.Hour, time.Hour} + t.Cleanup(func() { selfLookupBackoff = saved }) + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + tc := &flakySelfClient{ForgeClient: tracker.NewForgeClient(forge.NewFakeClient()), failures: 1000} + + _, err := resolveTrackerSelf(ctx, tc) + require.Error(t, err) + assert.ErrorIs(t, err, context.Canceled) + assert.Equal(t, 1, tc.calls, "a cancelled context must not wait out the backoff") +} diff --git a/internal/sticky/sticky.go b/internal/sticky/sticky.go index 0b0a014862..a686bd70ed 100644 --- a/internal/sticky/sticky.go +++ b/internal/sticky/sticky.go @@ -21,6 +21,10 @@ type Config struct { MaxSize int // max comment body size (default 65000) DryRun bool KeepHistory bool // when false, updates replace the body in-place with no "Previous run" history + // OnlyIfExists updates an existing marked comment but never creates one: + // a post-script uses it on an all-clear result so an earlier findings + // comment is replaced while a clean first run stays silent. + OnlyIfExists bool } func (c Config) maxSize() int { @@ -72,6 +76,11 @@ func Post(ctx context.Context, client forge.Client, owner, repo string, number i return existing.HTMLURL, nil } + if cfg.OnlyIfExists { + printer.StepInfo("No existing comment with this marker; nothing to post (only-if-exists)") + return "", nil + } + printer.StepStart("No existing comment found, creating new one") if cfg.DryRun { diff --git a/internal/sticky/sticky_test.go b/internal/sticky/sticky_test.go index e65bf17b63..323c5e84f3 100644 --- a/internal/sticky/sticky_test.go +++ b/internal/sticky/sticky_test.go @@ -376,3 +376,30 @@ func TestPost_DryRunExisting(t *testing.T) { assert.Empty(t, client.UpdatedComments) } + +func TestPost_OnlyIfExists_SkipsCreate(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + printer := ui.New(io.Discard) + + cfg := Config{Marker: "", OnlyIfExists: true} + commentURL, err := Post(context.Background(), client, "o", "r", 1, "All clear.", cfg, printer) + require.NoError(t, err) + assert.Empty(t, commentURL) + assert.Empty(t, client.IssueComments["o/r/1"], "only-if-exists must not create a first comment") +} + +func TestPost_OnlyIfExists_UpdatesExisting(t *testing.T) { + client := forge.NewFakeClient() + client.AuthenticatedUser = "bot" + client.IssueComments = map[string][]forge.IssueComment{ + "o/r/1": {{ID: 100, HTMLURL: "https://github.com/o/r/issues/1#issuecomment-100", Body: "\n2 broken links", Author: "bot"}}, + } + printer := ui.New(io.Discard) + + cfg := Config{Marker: "", OnlyIfExists: true} + commentURL, err := Post(context.Background(), client, "o", "r", 1, "All clear.", cfg, printer) + require.NoError(t, err) + assert.Equal(t, "https://github.com/o/r/issues/1#issuecomment-100", commentURL) + require.Len(t, client.UpdatedComments, 1) +} diff --git a/internal/tracker/forge_client.go b/internal/tracker/forge_client.go index 42e47b83e4..36de0e500e 100644 --- a/internal/tracker/forge_client.go +++ b/internal/tracker/forge_client.go @@ -24,6 +24,13 @@ func NewForgeClient(fc forge.Client) *ForgeClient { return &ForgeClient{forge: fc} } +// AuthenticatedUser returns the login the underlying forge client is +// authenticated as, so a caller can tell the bot's own comments from +// anyone else's. +func (c *ForgeClient) AuthenticatedUser(ctx context.Context) (string, error) { + return c.forge.GetAuthenticatedUser(ctx) +} + // GetIssue implements Client by splitting project into owner/repo for the // underlying forge call. func (c *ForgeClient) GetIssue(ctx context.Context, project string, number int) (*Issue, error) {