From d85da5a4018d7e65e2e506b7a6e3f056bd2d4271 Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 1 Oct 2026 10:24:53 -0400 Subject: [PATCH 1/2] feat(cli)!: verify the comment author before issues post-comment edits issues post-comment found its earlier sticky comment by marker alone. Anyone who could comment could plant the marker (as body text, or on Jira as a property on their own comment), and every later run then wrote into the planted comment, or failed if the edit was refused. An existing comment is now edited only when it carries the marker and its author is exactly the identity the command posts as: the login from forge.Client.GetAuthenticatedUser on GitHub and GitLab (which also resolves App installation tokens and Actions' GITHUB_TOKEN through GraphQL viewer), the account ID from GET /myself on Jira. Login shapes and display names are never trusted. A planted comment is ignored and a new comment posted. The identity lookup retries twice (context-aware). If it still fails, the command returns an error naming the cause, posts or edits nothing, and says to rerun if the failure was transient or otherwise check that the token can read its own identity. Posting a new comment instead would orphan the earlier one. --dry-run resolves the identity too. Help text and the user guide's trust model state the rule, drop the "acceptable in trusted CI" caveat, and note that whoever can edit the command's own comments is still trusted. BREAKING CHANGE: issues post-comment fails, posting nothing, when it cannot resolve the identity it posts as, including under --dry-run; and it no longer edits a marker comment written by a different identity, so after a token rotation or App migration the next run posts a new comment instead of updating the old one. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- docs/guides/user/issues-commands.md | 35 ++-- internal/cli/issues.go | 131 +++++++++++-- internal/cli/issues_test.go | 292 +++++++++++++++++++++++++++- internal/tracker/fake_jira.go | 26 ++- internal/tracker/forge_client.go | 7 + internal/tracker/jira_client.go | 12 ++ internal/tracker/tracker_test.go | 38 ++++ 7 files changed, 496 insertions(+), 45 deletions(-) diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index 0956c825d6..d30981a222 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,7 +86,7 @@ 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) | | `--fullsend-dir` | No | Path to `.fullsend` config directory (sources defaults from its `config.yaml` when flags are omitted) | @@ -114,20 +115,22 @@ 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). +An existing comment is edited only when it carries the marker **and** +its author is exactly the identity the command posts as: the login on +GitHub and GitLab, where markers are hidden HTML comments in the body, +and the account ID (from `GET /myself`) on Jira, where markers are +comment entity properties. Display names and login shapes are never +trusted. A comment anyone else wrote with the same marker, as body text +or as a comment property on their own comment, is ignored, never edited. +Anyone who can edit the command's own comments (a repository maintainer, +or a Jira user with Edit All Comments) is still trusted: their edits are +kept as history when the comment is next updated. + +If that identity cannot be resolved after a short retry, the command +fails with an error naming the cause and posts or edits nothing. Rerun +it if the failure was transient; otherwise check that the token can read +its own identity. Posting a new comment instead would leave the earlier +one behind with content no later run updates. ## Environment variables diff --git a/internal/cli/issues.go b/internal/cli/issues.go index 928c1e8e27..04434b5599 100644 --- a/internal/cli/issues.go +++ b/internal/cli/issues.go @@ -8,6 +8,7 @@ import ( "os" "slices" "strings" + "time" "github.com/spf13/cobra" @@ -200,8 +201,9 @@ 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 -
blocks. This prevents comment flooding on re-runs. +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 +213,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: an existing comment is edited only when it carries the +marker and its author is exactly the identity this command posts as +(the login on GitHub and GitLab, the account ID on Jira). 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 +241,7 @@ 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(&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") @@ -341,12 +341,21 @@ func postJiraStickyComment(ctx context.Context, jc *tracker.JiraClient, project return "", fmt.Errorf("marker is empty") } + // Same rule as the GitHub/GitLab path: only the poster's own comments + // are candidates, matched by exact account ID. Filtering before the + // lookup covers both the marker property and the legacy body-text + // fallback, either of which another account can plant. + self, err := resolveTrackerSelf(ctx, jc) + if err != nil { + return "", unverifiedSelfError(err) + } + jiraComments, err := jc.ListJiraComments(ctx, project, number) if err != nil { return "", fmt.Errorf("listing comments: %w", err) } - existing := jc.FindCommentByMarkerProperty(jiraComments, cfg.Marker) + existing := jc.FindCommentByMarkerProperty(ownJiraComments(jiraComments, self), cfg.Marker) if existing != nil { printer.StepStart("Found existing comment, updating in-place") @@ -395,11 +404,11 @@ 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. 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 "", unverifiedSelfError(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 { @@ -515,11 +532,83 @@ func resolveKeepHistory(flag *bool, fullsendDir string, testConfigReader config. return true, nil } +// ownJiraComments returns the comments whose author account ID is exactly +// self. An empty self returns none. +func ownJiraComments(comments []jira.Comment, self string) []jira.Comment { + if self == "" { + return nil + } + var own []jira.Comment + for _, c := range comments { + if c.Author.AccountID == self { + own = append(own, c) + } + } + return own +} + +// authenticatedUserResolver is implemented by tracker clients that can +// report who they are authenticated as (tracker.ForgeClient by login, +// tracker.JiraClient by account ID). +type authenticatedUserResolver interface { + AuthenticatedUser(ctx context.Context) (string, error) +} + +// unverifiedSelfError reports that the posting identity could not be +// resolved, so nothing was posted or edited. +func unverifiedSelfError(err error) error { + return fmt.Errorf("cannot verify which identity this command posts as, so no comment was posted or edited; "+ + "rerun if the failure was transient, otherwise check that the token can read its own identity "+ + "(GitHub/GitLab: the authenticated user; Jira: GET /myself): %w", err) +} + +// 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..5ab1c757c4 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,272 @@ func TestIssuesPostCommentCmd_TrackerNotRequired(t *testing.T) { assert.NotContains(t, err.Error(), `required flag(s) "tracker"`) assert.Contains(t, err.Error(), "--tracker is required") } + +// 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, 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, + 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) { + err, comments, _ := postAfterCommentBy(t, testBot, 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) { + err, comments, _ := postAfterCommentBy(t, author, 0) + require.NoError(t, err) + require.Len(t, comments, 2, "the planted comment is left alone and a new one posted") + assert.NotContains(t, string(comments[0].Body), "new result") + assert.Contains(t, string(comments[1].Body), "new result") + }) + } +} + +func TestRunIssuesPostComment_TransientSelfFailureRetriesThenEdits(t *testing.T) { + err, comments, tc := postAfterCommentBy(t, testBot, 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) { + err, comments, tc := postAfterCommentBy(t, testBot, 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) + + cfg := &issuesPostCommentConfig{ + trackerName: trackerGitHub, + project: "acme/widgets", + number: 42, + marker: marker, + 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 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") +} + +// postJiraAfterCommentBy seeds one marker comment on PROJ-42 written by +// author (with the marker as a comment property, or, when legacy is set, +// embedded in the body the way pre-property comments stored it), then +// runs post-comment as tracker.FakeJiraBot. +func postJiraAfterCommentBy(t *testing.T, author jira.User, legacy bool, myselfErr error) (error, []tracker.Comment) { + t.Helper() + fastSelfLookup(t) + ctx := context.Background() + tc, fc, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") + require.NoError(t, err) + const marker = "" + + fc.Myself = author + if legacy { + _, err = tc.CreateComment(ctx, "PROJ", 42, tracker.Body(marker+"\nearlier findings")) + } else { + _, err = tc.CreateCommentWithMarker(ctx, "PROJ", 42, tracker.Body("earlier findings"), marker) + } + require.NoError(t, err) + + fc.Myself = tracker.FakeJiraBot + fc.MyselfError = myselfErr + cfg := &issuesPostCommentConfig{ + trackerName: trackerJira, + project: "PROJ", + number: 42, + marker: marker, + testClient: tc, + testPrinter: ui.New(io.Discard), + testBody: "new result", + } + runErr := runIssuesPostComment(ctx, cfg) + + comments, err := tc.ListComments(ctx, "PROJ", 42) + require.NoError(t, err) + return runErr, comments +} + +func TestRunIssuesPostComment_Jira_EditsOwnComment(t *testing.T) { + for _, legacy := range []bool{false, true} { + t.Run(fmt.Sprintf("legacy=%v", legacy), func(t *testing.T) { + err, comments := postJiraAfterCommentBy(t, tracker.FakeJiraBot, legacy, nil) + require.NoError(t, err) + require.Len(t, comments, 1) + assert.Contains(t, string(comments[0].Body), "new result") + }) + } +} + +func TestRunIssuesPostComment_Jira_IgnoresPlantedMarker(t *testing.T) { + // Another account set the marker property (or, legacy, put the marker in + // the body). Same display name as the bot: display names are not identity. + mallory := jira.User{AccountID: "mallory-account-id", DisplayName: tracker.FakeJiraBot.DisplayName} + for _, legacy := range []bool{false, true} { + t.Run(fmt.Sprintf("legacy=%v", legacy), func(t *testing.T) { + err, comments := postJiraAfterCommentBy(t, mallory, legacy, nil) + require.NoError(t, err) + require.Len(t, comments, 2, "the planted comment is left alone and a new one posted") + assert.NotContains(t, string(comments[0].Body), "new result") + assert.Contains(t, string(comments[1].Body), "new result") + }) + } +} + +func TestRunIssuesPostComment_Jira_UnresolvableSelfErrorsAndPostsNothing(t *testing.T) { + err, comments := postJiraAfterCommentBy(t, tracker.FakeJiraBot, false, errors.New("401 Unauthorized")) + require.Error(t, err) + assert.Contains(t, err.Error(), "cannot verify which identity") + assert.Contains(t, err.Error(), "401 Unauthorized") + 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 TestOwnJiraComments(t *testing.T) { + comments := []jira.Comment{ + {ID: "1", Author: jira.User{AccountID: "bot"}}, + {ID: "2", Author: jira.User{AccountID: "mallory", DisplayName: "bot"}}, + {ID: "3"}, + } + own := ownJiraComments(comments, "bot") + require.Len(t, own, 1) + assert.Equal(t, "1", own[0].ID) + assert.Empty(t, ownJiraComments(comments, ""), "an unverified self owns nothing, not even authorless comments") +} + +func TestRunIssuesPostComment_DryRunStillVerifiesIdentity(t *testing.T) { + // --dry-run resolves the posting identity too: a dry run that cannot + // verify it fails rather than silently previewing an edit. + fastSelfLookup(t) + ctx := context.Background() + const marker = "" + + fc := forge.NewFakeClient() + gh := &flakySelfClient{ForgeClient: tracker.NewForgeClient(fc), failures: 1000} + jc, fj, err := tracker.NewFakeJiraClientWithFake("https://acme.atlassian.net") + require.NoError(t, err) + fj.MyselfError = errors.New("401 Unauthorized") + + for _, tc := range []struct { + name string + tracker string + project string + client tracker.Client + }{ + {"github", trackerGitHub, "acme/widgets", gh}, + {"jira", trackerJira, "PROJ", jc}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := &issuesPostCommentConfig{ + trackerName: tc.tracker, + project: tc.project, + number: 42, + marker: marker, + dryRun: true, + testClient: tc.client, + testPrinter: ui.New(io.Discard), + testBody: "preview", + } + err := runIssuesPostComment(ctx, cfg) + require.Error(t, err) + assert.Contains(t, err.Error(), "cannot verify which identity") + }) + } +} diff --git a/internal/tracker/fake_jira.go b/internal/tracker/fake_jira.go index 2b3cc60fe7..455e27ad93 100644 --- a/internal/tracker/fake_jira.go +++ b/internal/tracker/fake_jira.go @@ -39,6 +39,30 @@ type FakeJiraClient struct { // UpdateError, when non-nil, is returned by UpdateComment to // simulate update failures. UpdateError error + + // Myself is the account GetMyself returns and new comments are + // authored by; the zero value means FakeJiraBot. MyselfError, when + // non-nil, is returned by GetMyself. + Myself jira.User + MyselfError error +} + +// FakeJiraBot is the account a FakeJiraClient posts as by default. +var FakeJiraBot = jira.User{AccountID: "fake-bot-account-id", DisplayName: "fullsend-bot"} + +func (f *FakeJiraClient) myself() jira.User { + if f.Myself.AccountID == "" && f.Myself.DisplayName == "" { + return FakeJiraBot + } + return f.Myself +} + +func (f *FakeJiraClient) GetMyself(_ context.Context) (*jira.User, error) { + if f.MyselfError != nil { + return nil, f.MyselfError + } + me := f.myself() + return &me, nil } func (f *FakeJiraClient) GetIssue(_ context.Context, issueIDOrKey string) (*jira.Issue, error) { @@ -82,7 +106,7 @@ func (f *FakeJiraClient) CreateCommentWithProperties(_ context.Context, issueIDO comment := jira.Comment{ ID: fmt.Sprintf("%d", len(f.Comments[issueIDOrKey])+1), Body: adf, - Author: jira.User{DisplayName: "fullsend-bot"}, + Author: f.myself(), Created: "2026-08-06T00:00:00.000+0000", } if f.Comments == nil { 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) { diff --git a/internal/tracker/jira_client.go b/internal/tracker/jira_client.go index 7d6ee08615..edeb4ef2f8 100644 --- a/internal/tracker/jira_client.go +++ b/internal/tracker/jira_client.go @@ -62,6 +62,7 @@ type jiraClient interface { UpdateComment(ctx context.Context, issueIDOrKey, commentID, body string) error SetCommentProperty(ctx context.Context, issueIDOrKey, commentID, propertyKey string, value any) error DeleteComment(ctx context.Context, issueIDOrKey, commentID string) error + GetMyself(ctx context.Context) (*jira.User, error) } var _ jiraClient = (*jira.LiveClient)(nil) @@ -87,6 +88,17 @@ func NewJiraClient(jc jiraClient, baseURL string) (*JiraClient, error) { return &JiraClient{jira: jc, baseURL: trimmed}, nil } +// AuthenticatedUser returns the account ID this client is authenticated +// as (GET /myself), so a caller can tell its own comments from anyone +// else's by Comment.Author.AccountID. Display names are not identities. +func (c *JiraClient) AuthenticatedUser(ctx context.Context) (string, error) { + me, err := c.jira.GetMyself(ctx) + if err != nil { + return "", err + } + return me.AccountID, nil +} + // issueKey builds a Jira issue key from a project key and issue number, // e.g. issueKey("PROJ", 123) = "PROJ-123". func issueKey(project string, number int) string { diff --git a/internal/tracker/tracker_test.go b/internal/tracker/tracker_test.go index da13762d03..79cb61e9e0 100644 --- a/internal/tracker/tracker_test.go +++ b/internal/tracker/tracker_test.go @@ -2,10 +2,12 @@ package tracker import ( "context" + "errors" "strings" "testing" "github.com/fullsend-ai/fullsend/internal/forge" + "github.com/fullsend-ai/fullsend/internal/forge/jira" ) func TestSplitProject(t *testing.T) { @@ -394,3 +396,39 @@ func (staticClient) DeleteComment(_ context.Context, _ string, _ int, _ string) var _ Client = staticClient{} var _ Client = (*ForgeClient)(nil) var _ Reactor = (*ForgeClient)(nil) + +func TestForgeClientAuthenticatedUser(t *testing.T) { + fc := forge.NewFakeClient() + fc.AuthenticatedUser = "fullsend-ai-review[bot]" + got, err := NewForgeClient(fc).AuthenticatedUser(context.Background()) + if err != nil || got != "fullsend-ai-review[bot]" { + t.Fatalf("AuthenticatedUser() = %q, %v; want the forge login", got, err) + } + + fc.Errors = map[string]error{"GetAuthenticatedUser": errors.New("401")} + if _, err := NewForgeClient(fc).AuthenticatedUser(context.Background()); err == nil { + t.Fatal("AuthenticatedUser() must return the forge error") + } +} + +func TestJiraClientAuthenticatedUser(t *testing.T) { + jc, fj, err := NewFakeJiraClientWithFake("https://acme.atlassian.net") + if err != nil { + t.Fatal(err) + } + got, err := jc.AuthenticatedUser(context.Background()) + if err != nil || got != FakeJiraBot.AccountID { + t.Fatalf("AuthenticatedUser() = %q, %v; want the account ID, not the display name", got, err) + } + + fj.Myself = jira.User{DisplayName: "no account id"} + got, err = jc.AuthenticatedUser(context.Background()) + if err != nil || got != "" { + t.Fatalf("AuthenticatedUser() = %q, %v; want an empty account ID passed through for the caller to reject", got, err) + } + + fj.MyselfError = errors.New("401") + if _, err := jc.AuthenticatedUser(context.Background()); err == nil { + t.Fatal("AuthenticatedUser() must return the GetMyself error") + } +} From be3093ce5a33a74f20a29c05f610148525b4dc8f Mon Sep 17 00:00:00 2001 From: Wayne Sun Date: Thu, 1 Oct 2026 11:44:39 -0400 Subject: [PATCH 2/2] test(cli): follow test naming for AuthenticatedUser; number the recovery steps TestForgeClient_AuthenticatedUser and TestJiraClient_AuthenticatedUser follow the Test_ convention, and the Jira one moves to jira_client_test.go with the other JiraClient tests. The user guide's identity-failure guidance becomes numbered steps. Assisted-by: Claude (fix), Claude (review) Signed-off-by: Wayne Sun --- docs/guides/user/issues-commands.md | 12 ++++++++---- internal/tracker/jira_client_test.go | 22 ++++++++++++++++++++++ internal/tracker/tracker_test.go | 25 +------------------------ 3 files changed, 31 insertions(+), 28 deletions(-) diff --git a/docs/guides/user/issues-commands.md b/docs/guides/user/issues-commands.md index d30981a222..2b995a6321 100644 --- a/docs/guides/user/issues-commands.md +++ b/docs/guides/user/issues-commands.md @@ -127,10 +127,14 @@ or a Jira user with Edit All Comments) is still trusted: their edits are kept as history when the comment is next updated. If that identity cannot be resolved after a short retry, the command -fails with an error naming the cause and posts or edits nothing. Rerun -it if the failure was transient; otherwise check that the token can read -its own identity. Posting a new comment instead would leave the earlier -one behind with content no later run updates. +fails with an error naming the cause and posts or edits nothing. Posting +a new comment instead would leave the earlier one behind with content no +later run updates. To recover: + +1. Rerun the command. A transient API failure clears on its own. +2. If it fails again, check that the token can read its own identity: + `GET /user` (or the GraphQL `viewer`) on GitHub, `GET /user` on + GitLab, `GET /myself` on Jira. ## Environment variables diff --git a/internal/tracker/jira_client_test.go b/internal/tracker/jira_client_test.go index c0f153b85b..5de50dd3ca 100644 --- a/internal/tracker/jira_client_test.go +++ b/internal/tracker/jira_client_test.go @@ -604,3 +604,25 @@ func TestNewFakeJiraClient(t *testing.T) { var _ Client = (*JiraClient)(nil) var _ StatusCommentClient = (*JiraClient)(nil) + +func TestJiraClient_AuthenticatedUser(t *testing.T) { + jc, fj, err := NewFakeJiraClientWithFake("https://acme.atlassian.net") + if err != nil { + t.Fatal(err) + } + got, err := jc.AuthenticatedUser(context.Background()) + if err != nil || got != FakeJiraBot.AccountID { + t.Fatalf("AuthenticatedUser() = %q, %v; want the account ID, not the display name", got, err) + } + + fj.Myself = jira.User{DisplayName: "no account id"} + got, err = jc.AuthenticatedUser(context.Background()) + if err != nil || got != "" { + t.Fatalf("AuthenticatedUser() = %q, %v; want an empty account ID passed through for the caller to reject", got, err) + } + + fj.MyselfError = errors.New("401") + if _, err := jc.AuthenticatedUser(context.Background()); err == nil { + t.Fatal("AuthenticatedUser() must return the GetMyself error") + } +} diff --git a/internal/tracker/tracker_test.go b/internal/tracker/tracker_test.go index 79cb61e9e0..2b204739b7 100644 --- a/internal/tracker/tracker_test.go +++ b/internal/tracker/tracker_test.go @@ -7,7 +7,6 @@ import ( "testing" "github.com/fullsend-ai/fullsend/internal/forge" - "github.com/fullsend-ai/fullsend/internal/forge/jira" ) func TestSplitProject(t *testing.T) { @@ -397,7 +396,7 @@ var _ Client = staticClient{} var _ Client = (*ForgeClient)(nil) var _ Reactor = (*ForgeClient)(nil) -func TestForgeClientAuthenticatedUser(t *testing.T) { +func TestForgeClient_AuthenticatedUser(t *testing.T) { fc := forge.NewFakeClient() fc.AuthenticatedUser = "fullsend-ai-review[bot]" got, err := NewForgeClient(fc).AuthenticatedUser(context.Background()) @@ -410,25 +409,3 @@ func TestForgeClientAuthenticatedUser(t *testing.T) { t.Fatal("AuthenticatedUser() must return the forge error") } } - -func TestJiraClientAuthenticatedUser(t *testing.T) { - jc, fj, err := NewFakeJiraClientWithFake("https://acme.atlassian.net") - if err != nil { - t.Fatal(err) - } - got, err := jc.AuthenticatedUser(context.Background()) - if err != nil || got != FakeJiraBot.AccountID { - t.Fatalf("AuthenticatedUser() = %q, %v; want the account ID, not the display name", got, err) - } - - fj.Myself = jira.User{DisplayName: "no account id"} - got, err = jc.AuthenticatedUser(context.Background()) - if err != nil || got != "" { - t.Fatalf("AuthenticatedUser() = %q, %v; want an empty account ID passed through for the caller to reject", got, err) - } - - fj.MyselfError = errors.New("401") - if _, err := jc.AuthenticatedUser(context.Background()); err == nil { - t.Fatal("AuthenticatedUser() must return the GetMyself error") - } -}