diff --git a/changelog.d/fixed-15133-workflow-fork-rebase.md b/changelog.d/fixed-15133-workflow-fork-rebase.md new file mode 100644 index 0000000000..d968eb3470 --- /dev/null +++ b/changelog.d/fixed-15133-workflow-fork-rebase.md @@ -0,0 +1 @@ +- Rebase-then-merge refuses workflow-changing fork rebases before dispatching a fixer push the App cannot complete, and asks for a human rebase instead of timing out ([#15133](https://github.com/hivecommons/hive/issues/15133)). diff --git a/src/pkg/dashboard/api_repo_item_decision_test.go b/src/pkg/dashboard/api_repo_item_decision_test.go index aa3464cd52..7ae56fdc65 100644 --- a/src/pkg/dashboard/api_repo_item_decision_test.go +++ b/src/pkg/dashboard/api_repo_item_decision_test.go @@ -35,10 +35,14 @@ type repoItemDecisionMock struct { // prMergeState is PR #8's mergeable_state ("" = clean); prRedCI and // prNoCI shape the head's combined status when the state alone does not // settle CI (e.g. "blocked"). - prMergeState string - updates int - prRedCI bool - prNoCI bool + prFork bool + // prNoMaintainerEdits clears maintainer_can_modify on PR #8. + prNoMaintainerEdits bool + workflowPath string + prMergeState string + updates int + prRedCI bool + prNoCI bool // priorComments are the comment bodies GET /comments lists (a prior // delegated decision makes a repeat click a no-op). priorComments []string @@ -131,7 +135,19 @@ func newRepoItemDecisionServer(t *testing.T, m *repoItemDecisionMock) *Server { for _, label := range m.prLabels { prLabels = append(prLabels, map[string]string{"name": label}) } - _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "body": m.prBody, "labels": prLabels, "user": author, "mergeable": mergeState != "dirty", "mergeable_state": mergeState, "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface"}, "base": map[string]any{"ref": "main"}}) + headRepo := "testorg/testrepo" + if m.prFork { + headRepo = "someone/testrepo" + } + _ = json.NewEncoder(w).Encode(map[string]any{"number": n, "state": "open", "body": m.prBody, "labels": prLabels, "user": author, "mergeable": mergeState != "dirty", "mergeable_state": mergeState, "maintainer_can_modify": !m.prNoMaintainerEdits, + "head": map[string]any{"sha": "feedfacefeedfacefeedfacefeedfacefeedface", "repo": map[string]any{"full_name": headRepo}}, + "base": map[string]any{"ref": "main", "repo": map[string]any{"full_name": "testorg/testrepo"}}}) + case r.Method == http.MethodGet && strings.Contains(path, "/compare/"): + files := []map[string]string{} + if m.workflowPath != "" { + files = append(files, map[string]string{"filename": m.workflowPath}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"files": files}) case r.Method == http.MethodPut && strings.HasSuffix(path, "/pulls/8/update-branch"): m.updates++ w.WriteHeader(http.StatusAccepted) diff --git a/src/pkg/dashboard/rebase_merge_followthrough.go b/src/pkg/dashboard/rebase_merge_followthrough.go index f9b3f2d4f3..6ab4b4ce31 100644 --- a/src/pkg/dashboard/rebase_merge_followthrough.go +++ b/src/pkg/dashboard/rebase_merge_followthrough.go @@ -62,11 +62,21 @@ func (s *Server) armRebaseThenMerge(ctx context.Context, w http.ResponseWriter, gh := s.deps.GHClient now := rebaseMergeNow() hiveAuthored := gh.IsHiveAuthorLogin(st.Author) - if !hiveAuthored && !st.PushReachable() { + // Workflow paths refuse every author: the App token cannot push them + // even to the hive's own fork. Plain reachability keeps the hive-authored + // bypass — the hive pushes its own heads without maintainer edits. + refusal := "" + switch { + case len(st.WorkflowPushPaths) > 0: + refusal = rebasemerge.FailWorkflowPush + case !hiveAuthored && !st.PushReachable(): + refusal = rebasemerge.FailNotReachable + } + if refusal != "" { f := rebasemerge.Arm(repoFull, number, user, st.BaseRef, st.HeadSHA, false, now) - f.FailNow(now, rebasemerge.FailNotReachable, nil) + f.FailNow(now, refusal, st.WorkflowPushPaths) // A 200 with a refused result, not an error: the toast shows the - // reason and the two ways out instead of "HTTP 409". + // reason and a recovery step instead of "HTTP 409". jsonStatusResponse(w, http.StatusOK, repoItemDecisionResponse{OK: true, Repo: repoFull, Number: number, Decision: repoItemDecisionMergeNow, Status: rowActionRefused, Head: st.HeadSHA, Result: rebaseMergeFailedResult(f)}) return @@ -132,6 +142,9 @@ func rebaseMergeQueuedResult(f rebasemerge.FollowThrough, already bool) *RowActi func rebaseMergeFailedResult(f rebasemerge.FollowThrough) *RowActionResult { out := &RowActionResult{Action: rowActionRefused, Target: rowActionTarget(f.Repo, rowActionTargetPR, f.Number), Outcome: f.FailureText(), Why: f.FailReason} out.Next = "Pick a way out: adopt the commits into a fresh branch, or close it as superseded." + if f.FailReason == rebasemerge.FailWorkflowPush { + out.Next = "Rebase the fork branch with credentials that can push workflow changes, then approve and merge again." + } if f.FailReason == rebasemerge.FailForeignHead { out.Next = "Read the new head; if it is what you meant to merge, approve it again — or close the PR as superseded." } @@ -167,11 +180,18 @@ func renderRebaseThenMergeComment(user, comment string, number int, base string) func renderRebaseThenMergeFailedComment(f rebasemerge.FollowThrough) string { body := "Rebase, then merge as maintainer did not land: " + f.FailureText() if len(f.ConflictFiles) > 0 { - body += "\n\nFiles to resolve:\n" + if f.FailReason == rebasemerge.FailWorkflowPush { + body += "\n\nWorkflow paths blocking the push:\n" + } else { + body += "\n\nFiles to resolve:\n" + } for _, file := range f.ConflictFiles { body += "- `" + file + "`\n" } } + if f.FailReason == rebasemerge.FailWorkflowPush { + return body + } if f.FailReason == rebasemerge.FailForeignHead { body += fmt.Sprintf("\n@%s: from the dashboard row, **%s** or **%s**.", f.Actor, rebasemerge.OptionReapproveLabel, rebasemerge.OptionCloseSupersLabel) return body @@ -220,6 +240,13 @@ func (s *Server) tickRebaseMerge(ctx context.Context) { func (s *Server) driveRebaseMerge(ctx context.Context, store *rebasemerge.Store, f rebasemerge.FollowThrough, st ghpkg.PRMergeState) { gh := s.deps.GHClient now := rebaseMergeNow() + if st.NeedsRebase() && len(st.WorkflowPushPaths) > 0 && !st.Merged { + f.FailNow(now, rebasemerge.FailWorkflowPush, st.WorkflowPushPaths) + _ = store.Update(f) + s.settleRebaseMergeLedger(ctx, f) + s.invalidateStageTrackerForWebhook() + return + } obs := rebasemerge.Observation{Now: now, Head: st.HeadSHA, State: st.State, Merged: st.Merged, MergeableState: st.MergeableState, CIRed: st.CIRed} if head := strings.TrimSpace(st.HeadSHA); head != "" && head != f.ApprovedHead && head != f.RebasedHead && !f.HiveAuthored && !st.Merged { // The approval was bound to ApprovedHead. Before the new head can diff --git a/src/pkg/dashboard/rebase_merge_followthrough_test.go b/src/pkg/dashboard/rebase_merge_followthrough_test.go index f4acbcfdd7..17fb013617 100644 --- a/src/pkg/dashboard/rebase_merge_followthrough_test.go +++ b/src/pkg/dashboard/rebase_merge_followthrough_test.go @@ -3,6 +3,7 @@ package dashboard import ( "context" "encoding/json" + "fmt" "net/http" "path/filepath" "strings" @@ -367,3 +368,77 @@ func TestDriveRebaseMergeForeignHeadFailsClosed(t *testing.T) { t.Fatalf("failed result = %+v", res) } } + +// A maintainer-editable fork with workflow changes must not enter the fixer +// queue, even when its author is the hive's App. Approval cannot grant push +// permissions, and a fresh-branch adoption is fenced for these paths too. +func TestRebaseMergeWorkflowForkRefusesBeforeArming(t *testing.T) { + for _, foreign := range []bool{false, true} { + t.Run(fmt.Sprint("foreign=", foreign), func(t *testing.T) { + store := useRebaseMergeStore(t) + mock := &repoItemDecisionMock{prForeign: foreign, prFork: true, prMergeState: "dirty", workflowPath: ".github/workflows/ci.yml"} + srv := newRepoItemDecisionServer(t, mock) + w := postRepoItemDecisionAs(t, srv, 8, "writer", "merger", `{"decision":"merge-now","type":"pr"}`) + if w.Code != http.StatusOK { + t.Fatalf("code=%d body=%s", w.Code, w.Body.String()) + } + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if resp.Result == nil || resp.Result.Why != rebasemerge.FailWorkflowPush || !strings.Contains(resp.Result.Outcome, mock.workflowPath) || len(resp.Result.Options) != 0 { + t.Fatalf("result = %+v", resp.Result) + } + if store.Armed("testorg/testrepo", 8) || len(mock.comments) != 0 || len(mock.merges) != 0 || mock.updates != 0 || len(mock.reviews) != 0 { + t.Fatalf("refused request armed or wrote to GitHub: store=%v mock=%+v", store.Live(), mock) + } + }) + } +} + +// A fork head without maintainer edits is only unreachable for a +// contributor's PR: the hive pushes its own heads with its own credentials, +// so a hive-authored fork PR still arms as it did before the workflow fence. +func TestRebaseMergeForkWithoutMaintainerEditsKeepsHiveAuthoredBypass(t *testing.T) { + for _, foreign := range []bool{false, true} { + t.Run(fmt.Sprint("foreign=", foreign), func(t *testing.T) { + store := useRebaseMergeStore(t) + mock := &repoItemDecisionMock{prForeign: foreign, prFork: true, prNoMaintainerEdits: true, prMergeState: "dirty"} + srv := newRepoItemDecisionServer(t, mock) + w := postRepoItemDecisionAs(t, srv, 8, "writer", "merger", `{"decision":"merge-now","type":"pr"}`) + var resp repoItemDecisionResponse + _ = json.Unmarshal(w.Body.Bytes(), &resp) + if !foreign { + f, ok := store.Get("testorg/testrepo", 8) + if w.Code != http.StatusAccepted || resp.Status != repoItemStatusRebaseQd || !ok || !f.HiveAuthored || f.State != rebasemerge.StateRebasing { + t.Fatalf("hive-authored fork must still arm: code=%d body=%s follow-through=%+v ok=%v", w.Code, w.Body.String(), f, ok) + } + return + } + if w.Code != http.StatusOK || resp.Result == nil || resp.Result.Why != rebasemerge.FailNotReachable { + t.Fatalf("contributor fork must be refused as unreachable: code=%d result=%+v", w.Code, resp.Result) + } + if store.Armed("testorg/testrepo", 8) || len(mock.comments) != 0 || len(mock.merges) != 0 { + t.Fatalf("refused request armed or wrote to GitHub: store=%v mock=%+v", store.Live(), mock) + } + }) + } +} + +func TestRebaseMergeWorkflowDriftStopsExistingFollowThrough(t *testing.T) { + store := useRebaseMergeStore(t) + mock := &repoItemDecisionMock{} + srv := newRepoItemDecisionServer(t, mock) + now := time.Now() + f := rebasemerge.Arm("testorg/testrepo", 8, "writer", "main", "feedface", false, now) + f.Kicked(now, "fixer") + _ = store.Put(f) + _ = srv.operatorActions().Record(f.Repo, f.Number, OperatorAction{Action: operatorActionMergeNow, Actor: "writer", At: now, Outcome: operatorActionOutcomePending, Stage: 85}) + srv.driveRebaseMerge(context.Background(), store, f, ghpkg.PRMergeState{State: "open", HeadSHA: f.ApprovedHead, BaseRef: "main", MergeableState: "dirty", FromFork: true, MaintainerCanModify: true, WorkflowPushPaths: []string{".github/workflows/new.yml"}}) + got, _ := store.Get(f.Repo, f.Number) + if got.Live() || got.FailReason != rebasemerge.FailWorkflowPush || store.Armed(f.Repo, f.Number) { + t.Fatalf("follow-through = %+v", got) + } + acts := srv.operatorActions().List(f.Repo, f.Number) + if len(acts) != 1 || acts[0].Outcome != operatorActionOutcomeFailed || len(mock.comments) != 1 || len(mock.merges) != 0 || strings.Contains(mock.comments[0], rebasemerge.OptionAdoptFreshLabel) { + t.Fatalf("ledger=%+v comments=%v merges=%v", acts, mock.comments, mock.merges) + } +} diff --git a/src/pkg/github/pr_merge_state.go b/src/pkg/github/pr_merge_state.go index 1c465e49e9..a543c7d0bd 100644 --- a/src/pkg/github/pr_merge_state.go +++ b/src/pkg/github/pr_merge_state.go @@ -26,6 +26,9 @@ type PRMergeState struct { MergeableState string FromFork bool MaintainerCanModify bool + // WorkflowPushPaths names workflow files on either side of a fork rebase. + // Maintainer edits alone do not make such an App-token push deliverable. + WorkflowPushPaths []string // CIRed is true when a check or status on HeadSHA concluded red. CIRed bool // RedChecks names them. @@ -51,7 +54,7 @@ func (s PRMergeState) Conflicting() bool { // PushReachable reports whether the hive's token can push to the head. func (s PRMergeState) PushReachable() bool { - return !s.FromFork || s.MaintainerCanModify + return (!s.FromFork || s.MaintainerCanModify) && len(s.WorkflowPushPaths) == 0 } // GetPRMergeState reads the PR fresh (no detail cache: the follow-through @@ -79,6 +82,24 @@ func (c *Client) GetPRMergeState(ctx context.Context, repo string, number int) ( if head, base := pr.GetHead().GetRepo(), pr.GetBase().GetRepo(); head != nil && base != nil && head.GetFullName() != "" && base.GetFullName() != "" { st.FromFork = !strings.EqualFold(head.GetFullName(), base.GetFullName()) } + if strings.EqualFold(st.State, "open") && st.FromFork && st.MaintainerCanModify && st.NeedsRebase() { + // Match the adoption lane's conservative workflow push fence: a base + // installation's grants do not establish workflow push access on a + // contributor's fork. Check both the PR and the incoming base changes. + for _, pair := range [][2]string{{st.BaseRef, st.HeadSHA}, {st.HeadSHA, st.BaseRef}} { + files, err := c.compareFiles(ctx, owner, repoName, pair[0], pair[1]) + if err != nil { + return PRMergeState{}, err + } + for file := range files { + if strings.HasPrefix(file, ".github/workflows/") { + st.WorkflowPushPaths = append(st.WorkflowPushPaths, file) + } + } + } + slices.Sort(st.WorkflowPushPaths) + st.WorkflowPushPaths = slices.Compact(st.WorkflowPushPaths) + } if strings.EqualFold(st.State, "open") && st.HeadSHA != "" { if sum, err := SummarizeCommitChecks(ctx, c.client, owner, repoName, st.HeadSHA); err == nil && len(sum.Red) > 0 { st.CIRed = true @@ -151,8 +172,10 @@ func (c *Client) compareFiles(ctx context.Context, owner, repo, base, head strin return nil, fmt.Errorf("comparing %s/%s %s...%s: %w", owner, repo, base, head, err) } for _, f := range cmp.Files { - if name := f.GetFilename(); name != "" { - out[name] = true + for _, name := range []string{f.GetFilename(), f.GetPreviousFilename()} { + if name != "" { + out[name] = true + } } } if resp == nil || resp.NextPage == 0 || len(cmp.Files) == 0 { diff --git a/src/pkg/github/pr_merge_state_workflow_test.go b/src/pkg/github/pr_merge_state_workflow_test.go new file mode 100644 index 0000000000..1d51ad38b3 --- /dev/null +++ b/src/pkg/github/pr_merge_state_workflow_test.go @@ -0,0 +1,99 @@ +package github + +import ( + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestGetPRMergeStateForkWorkflowPushFence(t *testing.T) { + for _, tc := range []struct { + name string + fork bool + state string + prFile string + baseFile string + previous string + compareErr bool + wantBlock bool + wantErr bool + }{ + {name: "PR workflow", fork: true, state: "dirty", prFile: ".github/workflows/ci.yml", wantBlock: true}, + {name: "incoming base workflow", fork: true, state: "behind", baseFile: ".github/workflows/ci.yml", wantBlock: true}, + {name: "renamed out of workflows", fork: true, state: "dirty", prFile: "ci.yml", previous: ".github/workflows/ci.yml", wantBlock: true}, + {name: "ordinary fork rebase", fork: true, state: "dirty", prFile: "src/main.go", baseFile: "README.md"}, + {name: "same repo unaffected", state: "dirty", prFile: ".github/workflows/ci.yml"}, + {name: "clean fork can still merge", fork: true, state: "clean", prFile: ".github/workflows/ci.yml"}, + {name: "compare failure fails closed", fork: true, state: "dirty", compareErr: true, wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + compares := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/pulls/8"): + headRepo := "org/repo" + if tc.fork { + headRepo = "person/repo" + } + _ = json.NewEncoder(w).Encode(map[string]any{"state": "open", "mergeable_state": tc.state, "maintainer_can_modify": true, + "head": map[string]any{"sha": "head", "repo": map[string]string{"full_name": headRepo}}, + "base": map[string]any{"ref": "v5", "repo": map[string]string{"full_name": "org/repo"}}}) + case strings.Contains(r.URL.Path, "/compare/"): + compares++ + if tc.compareErr { + http.Error(w, "unavailable", http.StatusServiceUnavailable) + return + } + file, previous := tc.prFile, tc.previous + if strings.HasSuffix(r.URL.Path, "head...v5") { + file, previous = tc.baseFile, "" + } + // Put the file on page two: a workflow can occur after a + // full page of ordinary paths in a real comparison. + if r.URL.Query().Get("page") == "" { + w.Header().Set("Link", fmt.Sprintf(`; rel="next"`, r.Host, r.URL.Path)) + _, _ = io.WriteString(w, `{"files":[{"filename":"README.md"}]}`) + return + } + files := []map[string]string{} + if file != "" { + files = append(files, map[string]string{"filename": file, "previous_filename": previous}) + } + _ = json.NewEncoder(w).Encode(map[string]any{"files": files}) + case strings.HasSuffix(r.URL.Path, "/status"): + _, _ = io.WriteString(w, `{"state":"success","statuses":[]}`) + case strings.HasSuffix(r.URL.Path, "/check-runs"): + _, _ = io.WriteString(w, `{"check_runs":[]}`) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + c := NewClientForTest(srv.URL, "org", []string{"repo"}, slog.New(slog.NewTextHandler(io.Discard, nil))) + st, err := c.GetPRMergeState(context.Background(), "org/repo", 8) + if (err != nil) != tc.wantErr { + t.Fatalf("state=%+v err=%v", st, err) + } + if tc.wantErr { + return + } + if st.PushReachable() == tc.wantBlock || (len(st.WorkflowPushPaths) > 0) != tc.wantBlock { + t.Fatalf("push reachability or workflow evidence incorrect: %+v", st) + } + if tc.fork && st.NeedsRebase() { + if compares != 4 { + t.Fatalf("compares=%d, want both pages of both directions", compares) + } + } else if compares != 0 { + t.Fatalf("unnecessary compares=%d", compares) + } + }) + } +} diff --git a/src/pkg/rebasemerge/rebasemerge.go b/src/pkg/rebasemerge/rebasemerge.go index 2df02ce71a..0c75995052 100644 --- a/src/pkg/rebasemerge/rebasemerge.go +++ b/src/pkg/rebasemerge/rebasemerge.go @@ -64,6 +64,7 @@ const ( FailTimeout = "rebase-timeout" FailClosed = "pr-closed" FailNotReachable = "head-not-pushable" + FailWorkflowPush = "workflow-push-unavailable" // FailForeignHead: the head moved after the approval, but not by the // hive — a person pushed new content. The approval was bound to the // head the operator read, so the follow-through stops instead of @@ -203,6 +204,10 @@ func (f *FollowThrough) fail(now time.Time, reason string, files []string) { f.FailReason = reason f.ConflictFiles = slices.Clone(files) f.Options = []string{OptionAdoptFresh, OptionCloseSuperseded} + if reason == FailWorkflowPush { + // Workflow-path supersession is also fenced by the adoption lane. + f.Options = nil + } if reason == FailForeignHead { f.Options = []string{OptionReapprove, OptionCloseSuperseded} } @@ -338,6 +343,8 @@ func (f FollowThrough) FailureText() string { return fmt.Sprintf("#%d was closed before the hive could merge it.", f.Number) case FailNotReachable: return fmt.Sprintf("The hive cannot push to #%d's head (fork without maintainer edits).", f.Number) + case FailWorkflowPush: + return fmt.Sprintf("The hive cannot rebase #%d's fork branch with workflow changes (%s). A person with workflow push access must rebase the branch, then approve and merge it again.", f.Number, strings.Join(f.ConflictFiles, ", ")) case FailForeignHead: return fmt.Sprintf("#%d's head moved after your approval, and not by the hive's rebase: someone pushed %s. Your approval was for %s, so nothing merged; read the new head and approve it again.", f.Number, nonEmpty(short(f.ForeignHead), "a new head"), nonEmpty(short(f.ApprovedHead), "the head you saw")) }