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
70 changes: 63 additions & 7 deletions internal/sticky/sticky.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"

"github.com/fullsend-ai/fullsend/internal/forge"
Expand Down Expand Up @@ -33,6 +34,14 @@ func (c Config) maxSize() int {
// Post implements the sticky comment lifecycle: find an existing comment
// bearing the marker, collapse old content into history, and create or
// update in-place. Returns the HTML URL of the comment (empty on dry run).
//
// 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 — not even
// on dry run, since dry run should not claim an edit would occur when none
// safely could.
func Post(ctx context.Context, client forge.Client, owner, repo string, number int, body string, cfg Config, printer *ui.Printer) (string, error) {
if strings.TrimSpace(body) == "" {
return "", fmt.Errorf("comment body is empty")
Expand All @@ -41,9 +50,12 @@ func Post(ctx context.Context, client forge.Client, owner, repo string, number i
return "", fmt.Errorf("marker is empty")
}

botUser, err := client.GetAuthenticatedUser(ctx)
// 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.
botUser, err := resolveBotUser(ctx, client)
if err != nil {
printer.StepInfo("Could not determine bot user, marker spoofing protection degraded")
return "", unverifiedBotUserError(err)
}

comments, err := client.ListIssueComments(ctx, owner, repo, number)
Expand Down Expand Up @@ -88,13 +100,17 @@ func Post(ctx context.Context, client forge.Client, owner, repo string, number i
return created.HTMLURL, nil
}

// FindMarkedComment returns the first comment whose body contains the
// given marker string, or nil if none is found. When botUser is non-empty,
// only comments authored by that user are considered. This prevents
// untrusted users from spoofing the marker in their own comments.
// FindMarkedComment returns the first comment whose body contains the given
// marker string and whose author is exactly botUser, or nil if none is
// found. An empty botUser matches nothing: callers pass it only when
// identity resolution failed, and matching on the marker alone would let
// anyone's comment be treated as the bot's own and edited in-place.
func FindMarkedComment(comments []forge.IssueComment, marker, botUser string) *forge.IssueComment {
if botUser == "" {
return nil
}
for i := range comments {
if botUser != "" && comments[i].Author != botUser {
if comments[i].Author != botUser {
continue
}
if strings.Contains(comments[i].Body, marker) {
Expand All @@ -104,6 +120,46 @@ func FindMarkedComment(comments []forge.IssueComment, marker, botUser string) *f
return nil
}

// botUserLookupBackoff is the wait before each retry of the bot identity
// lookup; its length is the number of retries. Tests shorten it.
var botUserLookupBackoff = []time.Duration{500 * time.Millisecond, time.Second}

// resolveBotUser returns the exact login client posts as, retrying a failed
// or empty lookup per botUserLookupBackoff so a transient error does not
// degrade marker spoofing protection. This mirrors resolveTrackerSelf in
// internal/cli/issues.go, but internal/cli imports this package, so the
// retry logic is kept local here rather than shared, to avoid an import
// cycle.
func resolveBotUser(ctx context.Context, client forge.Client) (string, error) {
var lastErr error
for attempt := 0; ; attempt++ {
botUser, err := client.GetAuthenticatedUser(ctx)
if err == nil && botUser == "" {
err = fmt.Errorf("the authenticated user is empty")
}
if err == nil {
return botUser, nil
}
lastErr = err
if attempt >= len(botUserLookupBackoff) {
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(botUserLookupBackoff[attempt]):
}
}
}

// unverifiedBotUserError reports that the posting identity could not be
// resolved, so nothing was posted or edited.
func unverifiedBotUserError(err error) error {
return fmt.Errorf("cannot verify which identity this 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 "+
"(the authenticated user): %w", err)
}

// History blocks are wrapped with sentinel comments so extraction is safe
// even when review content contains nested <details> tags.
const (
Expand Down
130 changes: 128 additions & 2 deletions internal/sticky/sticky_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package sticky

import (
"context"
"errors"
"io"
"strings"
"testing"
"time"
"unicode/utf8"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -52,8 +54,7 @@ func TestFindMarkedComment_EmptyBotUser(t *testing.T) {
}

found := FindMarkedComment(comments, "<!-- fullsend:test -->", "")
require.NotNil(t, found, "empty botUser should match any author")
assert.Equal(t, 1, found.ID)
assert.Nil(t, found, "an unresolved (empty) botUser must match nothing, not any author")
}

func TestFindMarkedComment_Empty(t *testing.T) {
Expand Down Expand Up @@ -304,6 +305,7 @@ func TestPost_UpdateExisting(t *testing.T) {

func TestPost_DryRun(t *testing.T) {
client := forge.NewFakeClient()
client.AuthenticatedUser = "bot"
printer := ui.New(io.Discard)

cfg := Config{Marker: "<!-- test -->", DryRun: true}
Expand Down Expand Up @@ -364,6 +366,7 @@ func TestPost_UpdateExisting_EmptyHTMLURL(t *testing.T) {

func TestPost_DryRunExisting(t *testing.T) {
client := forge.NewFakeClient()
client.AuthenticatedUser = "bot"
client.IssueComments = map[string][]forge.IssueComment{
"o/r/1": {{ID: 100, Body: "<!-- test -->\nOld.", Author: "bot"}},
}
Expand All @@ -376,3 +379,126 @@ func TestPost_DryRunExisting(t *testing.T) {

assert.Empty(t, client.UpdatedComments)
}

// fastBotUserLookup shortens the identity-lookup retry backoff for a test.
func fastBotUserLookup(t *testing.T) {
t.Helper()
saved := botUserLookupBackoff
botUserLookupBackoff = []time.Duration{time.Millisecond, time.Millisecond}
t.Cleanup(func() { botUserLookupBackoff = saved })
}

// flakyAuthClient fails GetAuthenticatedUser failures times, then defers to
// the wrapped forge.Client.
type flakyAuthClient struct {
forge.Client
failures int
calls int
}

func (c *flakyAuthClient) GetAuthenticatedUser(ctx context.Context) (string, error) {
c.calls++
if c.calls <= c.failures {
return "", errors.New("502 Bad Gateway")
}
return c.Client.GetAuthenticatedUser(ctx)
}

func TestPost_PersistentIdentityFailure_ErrorsAndPostsNothing(t *testing.T) {
fastBotUserLookup(t)
fc := forge.NewFakeClient()
fc.AuthenticatedUser = "bot"
fc.IssueComments = map[string][]forge.IssueComment{
"o/r/1": {{ID: 100, Body: "<!-- test -->\nOld.", Author: "bot"}},
}
client := &flakyAuthClient{Client: fc, failures: 1000}
printer := ui.New(io.Discard)

cfg := Config{Marker: "<!-- test -->", KeepHistory: true}
_, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer)
require.Error(t, err)
assert.Contains(t, err.Error(), "cannot verify which identity")
assert.Contains(t, err.Error(), "502 Bad Gateway", "the error must name the cause")
assert.Equal(t, len(botUserLookupBackoff)+1, client.calls)

assert.Empty(t, fc.UpdatedComments, "no comment may be edited")
require.Len(t, fc.IssueComments["o/r/1"], 1, "no comment may be created")
}

func TestPost_TransientIdentityFailure_RetriesThenEdits(t *testing.T) {
fastBotUserLookup(t)
fc := forge.NewFakeClient()
fc.AuthenticatedUser = "bot"
fc.IssueComments = map[string][]forge.IssueComment{
"o/r/1": {{ID: 100, Body: "<!-- test -->\nOld.", Author: "bot"}},
}
client := &flakyAuthClient{Client: fc, failures: len(botUserLookupBackoff)}
printer := ui.New(io.Discard)

cfg := Config{Marker: "<!-- test -->", KeepHistory: true}
_, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer)
require.NoError(t, err)
assert.Equal(t, len(botUserLookupBackoff)+1, client.calls, "every retry is used before success")

require.Len(t, fc.UpdatedComments, 1)
assert.Equal(t, 100, fc.UpdatedComments[0].CommentID)
assert.Contains(t, fc.UpdatedComments[0].Body, "New.")
}

func TestPost_IgnoresPlantedMarker_EditsOnlyOwnComment(t *testing.T) {
client := forge.NewFakeClient()
client.AuthenticatedUser = "bot"
client.IssueComments = map[string][]forge.IssueComment{
"o/r/1": {
{ID: 100, Body: "<!-- test -->\nplanted by attacker", Author: "attacker"},
{ID: 101, Body: "<!-- test -->\nOld.", Author: "bot"},
},
}
printer := ui.New(io.Discard)

cfg := Config{Marker: "<!-- test -->", KeepHistory: true}
_, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer)
require.NoError(t, err)

require.Len(t, client.UpdatedComments, 1)
assert.Equal(t, 101, client.UpdatedComments[0].CommentID, "only the bot's own comment may be edited")

comments := client.IssueComments["o/r/1"]
assert.NotContains(t, comments[0].Body, "New.", "the planted comment must be left untouched")
}

func TestPost_OnlyPlantedMarker_CreatesNewCommentWithoutTouchingPlanted(t *testing.T) {
client := forge.NewFakeClient()
client.AuthenticatedUser = "bot"
client.IssueComments = map[string][]forge.IssueComment{
"o/r/1": {{ID: 100, Body: "<!-- test -->\nplanted by attacker", Author: "attacker"}},
}
printer := ui.New(io.Discard)

cfg := Config{Marker: "<!-- test -->"}
commentURL, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer)
require.NoError(t, err)
assert.Contains(t, commentURL, "issuecomment-")

comments := client.IssueComments["o/r/1"]
require.Len(t, comments, 2, "a new comment is created; the planted one is left in place")
assert.NotContains(t, comments[0].Body, "New.", "the planted comment must be untouched")
assert.Contains(t, comments[1].Body, "New.")
assert.Empty(t, client.UpdatedComments)
}

func TestPost_DryRun_UnresolvedIdentity_Errors(t *testing.T) {
fastBotUserLookup(t)
client := forge.NewFakeClient()
client.IssueComments = map[string][]forge.IssueComment{
"o/r/1": {{ID: 100, Body: "<!-- test -->\nOld.", Author: "bot"}},
}
printer := ui.New(io.Discard)

cfg := Config{Marker: "<!-- test -->", DryRun: true}
commentURL, err := Post(context.Background(), client, "o", "r", 1, "New.", cfg, printer)
require.Error(t, err, "dry run must not imply an edit would occur when identity is unresolved")
assert.Contains(t, err.Error(), "cannot verify which identity")
assert.Empty(t, commentURL)
assert.Empty(t, client.UpdatedComments)
}
Loading