Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 23 additions & 16 deletions docs/guides/user/issues-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<details>` blocks to preserve history;
set `keep_history: false` in config.yaml (or pass `--keep-history=false`)
to replace the body with no history.
Expand Down Expand Up @@ -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) |

Expand Down Expand Up @@ -114,20 +115,26 @@ 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. 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

Expand Down
131 changes: 110 additions & 21 deletions internal/cli/issues.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"slices"
"strings"
"time"

"github.com/spf13/cobra"

Expand Down Expand Up @@ -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
<details> blocks. This prevents comment flooding on re-runs.
by its marker and its own author and edits in-place, collapsing old
content into <details> blocks. This prevents comment flooding on
re-runs.

Works across GitHub, GitLab, and Jira via --tracker.

Expand All @@ -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
Expand All @@ -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")
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand All @@ -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 {
Expand Down Expand Up @@ -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]
}
Expand Down
Loading
Loading