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
1 change: 1 addition & 0 deletions changelog.d/fixed-14938-trusted-queue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Refuse dashboard auto-merge queues whose recorded actor is not an owner or merger in `dashboard.authorized_users`, and explain merge-time authorization refusals with one PR comment per head.
12 changes: 12 additions & 0 deletions src/pkg/dashboard/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,18 @@ func (s *Server) handleQueuePRAutoMerge(w http.ResponseWriter, r *http.Request)
jsonError(w, "GitHub client not configured", http.StatusServiceUnavailable)
return
}
// Match the merge sweep's trustedMergerFunc against the identity that
// QueuePRAutoMerge will record, rather than trusting the request role.
if s.deps.Config == nil || len(s.deps.Config.Dashboard.AuthorizedUsers) == 0 {
jsonError(w, "dashboard.authorized_users is empty: no queued PR can merge until an owner or merger is listed", http.StatusForbidden)
return
}
role, authorized := s.deps.Config.Dashboard.AuthorizedRole(user)
if !authorized || !config.RoleAtLeast(role, config.RoleMerger) {
jsonError(w, "@"+user+" cannot merge: queue from a signed-in owner/merger account listed in dashboard.authorized_users", http.StatusForbidden)
return
}

number, err := strconv.Atoi(r.PathValue("number"))
if err != nil || number <= 0 {
jsonError(w, "invalid pull request number", http.StatusBadRequest)
Expand Down
28 changes: 28 additions & 0 deletions src/pkg/dashboard/api_v1_pr_automerge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,3 +242,31 @@ func TestAPIV1QueuePRAutoMergeAcceptsLegacyTokenScheme(t *testing.T) {
t.Fatalf("reviewCreated=%v labelAdded=%v, want both true", *reviewCreated, *labelAdded)
}
}

// The dashboard's shared operator credential authenticates successfully but
// must not create an approval attributed to an actor the sweep will refuse.
func TestDashboardQueueInternalCredentialChecksRecordedMerger(t *testing.T) {
for _, tt := range []struct {
name string
users []string
wantStatus int
wantError string
}{
{"empty allowlist", nil, http.StatusForbidden, "dashboard.authorized_users is empty"},
{"untrusted internal", []string{"alice:merger"}, http.StatusForbidden, "@internal cannot merge"},
{"trusted internal", []string{"internal:merger"}, http.StatusOK, ""},
} {
t.Run(tt.name, func(t *testing.T) {
s, reviewCreated, labelAdded := newAPIV1QueueServer(t, config.RoleMerger, "alice", "bob", "head7")
s.deps.Config.Dashboard.AuthorizedUsers = tt.users
rr := queueAPIV1Request(t, s, "/api/prs/acme/widget/7/queue-automerge", "", map[string]string{"X-Hive-Internal": "dashboard-token"})
if rr.Code != tt.wantStatus || !strings.Contains(rr.Body.String(), tt.wantError) {
t.Fatalf("status=%d body=%s, want %d containing %q", rr.Code, rr.Body.String(), tt.wantStatus, tt.wantError)
}
wantMutation := tt.wantStatus == http.StatusOK
if *reviewCreated != wantMutation || *labelAdded != wantMutation {
t.Fatalf("review=%v label=%v, want mutations=%v", *reviewCreated, *labelAdded, wantMutation)
}
})
}
}
30 changes: 22 additions & 8 deletions src/pkg/dashboard/pr_automerge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,22 @@ func TestQueuePRAutoMergeRoleAndSelfGate(t *testing.T) {
user string
author string
wantStatus int
users []string
wantError string
}{
{"merger queues other pr", config.RoleMerger, "alice", "bob", http.StatusOK},
{"merger cannot queue own pr", config.RoleMerger, "alice", "ALICE", http.StatusForbidden},
{"read write forbidden", config.RoleReadWrite, "alice", "bob", http.StatusForbidden},
{"read forbidden", config.RoleRead, "alice", "bob", http.StatusForbidden},
{"owner queues other pr", config.RoleOwner, "alice", "bob", http.StatusOK},
{"owner cannot queue own pr", config.RoleOwner, "alice", "ALICE", http.StatusForbidden},
{"owner needs authenticated user", config.RoleOwner, "", "bob", http.StatusForbidden},
{"merger queues other pr", config.RoleMerger, "alice", "bob", http.StatusOK, []string{"alice:owner"}, ""},
{"merger cannot queue own pr", config.RoleMerger, "alice", "ALICE", http.StatusForbidden, []string{"alice:owner"}, ""},
{"read write forbidden", config.RoleReadWrite, "alice", "bob", http.StatusForbidden, []string{"alice:owner"}, ""},
{"read forbidden", config.RoleRead, "alice", "bob", http.StatusForbidden, []string{"alice:owner"}, ""},
{"owner queues other pr", config.RoleOwner, "alice", "bob", http.StatusOK, []string{"alice:owner"}, ""},
{"owner cannot queue own pr", config.RoleOwner, "alice", "ALICE", http.StatusForbidden, []string{"alice:owner"}, ""},
{"owner needs authenticated user", config.RoleOwner, "", "bob", http.StatusForbidden, []string{"alice:owner"}, ""},
{"empty allowlist", config.RoleOwner, "alice", "bob", http.StatusForbidden, nil, "dashboard.authorized_users is empty"},
{"unlisted internal", config.RoleOwner, "internal", "bob", http.StatusForbidden, []string{"alice:merger"}, "@internal cannot merge"},
{"listed internal", config.RoleOwner, "internal", "bob", http.StatusOK, []string{"internal:merger"}, ""},
{"listed merger", config.RoleMerger, "ALICE", "bob", http.StatusOK, []string{"alice:merger"}, ""},
{"allowlist read cannot use owner request role", config.RoleOwner, "alice", "bob", http.StatusForbidden, []string{"alice:read"}, "@alice cannot merge"},
{"unlisted human", config.RoleMerger, "alice", "bob", http.StatusForbidden, []string{"carol:owner"}, "@alice cannot merge"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -67,7 +75,7 @@ func TestQueuePRAutoMergeRoleAndSelfGate(t *testing.T) {
s := NewServer(0, slog.Default())
s.deps = &Dependencies{
GHClient: ghpkg.NewClient("token", "acme", []string{"widget"}, slog.Default(), api.URL),
Config: &config.Config{Project: config.ProjectConfig{Org: "acme", Repos: []string{"widget"}}},
Config: &config.Config{Project: config.ProjectConfig{Org: "acme", Repos: []string{"widget"}}, Dashboard: config.DashboardConfig{AuthorizedUsers: tt.users}},
}
req := httptest.NewRequest(http.MethodPost, "/api/prs/acme/widget/7/queue-automerge", nil)
req.Header.Set("X-Hive-Role", tt.role)
Expand All @@ -84,6 +92,12 @@ func TestQueuePRAutoMergeRoleAndSelfGate(t *testing.T) {
if rr.Code != tt.wantStatus {
t.Fatalf("status = %d body %s, want %d", rr.Code, rr.Body.String(), tt.wantStatus)
}
if tt.wantError != "" && !strings.Contains(rr.Body.String(), tt.wantError) {
t.Fatalf("body = %s, want %q", rr.Body.String(), tt.wantError)
}
if tt.wantStatus != http.StatusOK && (labelAdded || reviewCreated) {
t.Fatalf("refused queue mutated GitHub: labelAdded=%v reviewCreated=%v", labelAdded, reviewCreated)
}
if tt.wantStatus == http.StatusOK {
if !labelAdded || !reviewCreated {
t.Fatalf("labelAdded=%v reviewCreated=%v, want both true", labelAdded, reviewCreated)
Expand Down
2 changes: 2 additions & 0 deletions src/pkg/github/automerge/automerge_sweep.go
Original file line number Diff line number Diff line change
Expand Up @@ -2042,6 +2042,7 @@ func (c *Engine) queueApprovalStillHolds(ctx context.Context, owner, repo string
return fmt.Errorf("the queue approval covers head %s, not %s", approval.HeadSHA, head)
}
if trusted, configured := c.isTrustedMerger(approval.QueuedBy); !configured || !trusted {
c.noteUntrustedMerger(ctx, owner, repo, number, head, approval.QueuedBy)
return fmt.Errorf("queuer %s is not a trusted merger", approval.QueuedBy)
}
return nil
Expand Down Expand Up @@ -2675,6 +2676,7 @@ func (c *Engine) trySweepQueuedPR(ctx context.Context, displayRepo, owner, repo
return AutoMergeSweepEvent{}, autoMergeReasonNoMergerAuthz, nil
}
if !trusted {
c.noteUntrustedMerger(ctx, owner, repo, number, headSHA, queuedBy)
c.warn(autoMergeWarnUntrustedMerger, "owner", owner, "repo", repo, "pr", number,
"queued_by", queuedBy, "author", author)
return AutoMergeSweepEvent{}, autoMergeReasonUntrustedMerger, nil
Expand Down
19 changes: 19 additions & 0 deletions src/pkg/github/automerge/automerge_sweep_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2879,6 +2879,7 @@ func newAutoMergeSweepClient(apiURL string) *Engine {
func newAutoMergeSweepAPI(t *testing.T, expectedLabel string, prs []sweepPR, merged *[]int, extras ...func(http.ResponseWriter, *http.Request)) *httptest.Server {
t.Helper()
byNumber := make(map[int]sweepPR, len(prs))
comments := make(map[int][]map[string]any)
for _, pr := range prs {
byNumber[pr.number] = pr
}
Expand Down Expand Up @@ -3007,6 +3008,24 @@ func newAutoMergeSweepAPI(t *testing.T, expectedLabel string, prs []sweepPR, mer
extra(w, r)
return
}
if strings.HasPrefix(r.URL.Path, "/repos/acme/widget/issues/") && strings.HasSuffix(r.URL.Path, "/comments") {
number := pathNumber(t, r.URL.Path, "/repos/acme/widget/issues/", "/comments")
switch r.Method {
case http.MethodGet:
json.NewEncoder(w).Encode(comments[number])
return
case http.MethodPost:
var payload map[string]any
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Errorf("decode comment: %v", err)
}
payload["user"] = map[string]string{"login": testHiveAppBotLogin}
comments[number] = append(comments[number], payload)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(payload)
return
}
}
t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
}
}))
Expand Down
47 changes: 47 additions & 0 deletions src/pkg/github/automerge/automerge_sweep_trusted_merger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,32 @@ func TestF3_UntrustedMergerDoesNotMerge(t *testing.T) {
if result.Skipped != 1 {
t.Fatalf("skipped = %d, want 1", result.Skipped)
}
// Restart the engine: dedupe must survive process-local state being lost.
c = newAutoMergeSweepClient(api.URL)
_, reason, err := c.trySweepQueuedPR(context.Background(), "widget", "acme", "widget", 7, hgithub.AutoMergeQueuedLabel)
if err != nil || reason != autoMergeReasonUntrustedMerger {
t.Fatalf("repeat sweep reason=%q err=%v", reason, err)
}
comments, _, err := c.gh.Issues.ListComments(context.Background(), "acme", "widget", 7, nil)
if err != nil || len(comments) != 1 {
t.Fatalf("comments=%v err=%v, want one notice across sweeps", comments, err)
}
for _, text := range []string{"untrusted-merger", "@mallory", "sha7", "dashboard.authorized_users"} {
if !strings.Contains(comments[0].GetBody(), text) {
t.Errorf("notice %q missing %q", comments[0].GetBody(), text)
}
}
// A new head gets its own notice, while repeated lane re-checks do not.
if err := c.commentUntrustedMerger(context.Background(), "acme", "widget", 7, "newsha", "mallory"); err != nil {
t.Fatal(err)
}
if err := c.commentUntrustedMerger(context.Background(), "acme", "widget", 7, "newsha", "mallory"); err != nil {
t.Fatal(err)
}
comments, _, err = c.gh.Issues.ListComments(context.Background(), "acme", "widget", 7, nil)
if err != nil || len(comments) != 2 {
t.Fatalf("comments=%v err=%v, want one notice for each head", comments, err)
}
}

// TestF3_SockpuppetPairDoesNotMerge covers the case the self-merge ban cannot
Expand Down Expand Up @@ -183,3 +209,24 @@ func TestF3_IsTrustedMergerFailsClosedOnEdgeCases(t *testing.T) {
t.Fatal("mallory must not be trusted")
}
}

func TestQueueApprovalRevokedBeforeLaneExecutionPostsNotice(t *testing.T) {
var merged []int
api := newAutoMergeSweepAPI(t, hgithub.AutoMergeQueuedLabel, []sweepPR{greenQueuedPR(7, "alice", "bob")}, &merged)
defer api.Close()
c := newAutoMergeSweepClient(api.URL)
ctx := context.Background()
if err := c.queueApprovalStillHolds(ctx, "acme", "widget", 7, "sha7"); err != nil {
t.Fatalf("trusted approval rejected: %v", err)
}
c.SetMergerAuthorizer(func(string) bool { return false })
for range 2 {
if err := c.queueApprovalStillHolds(ctx, "acme", "widget", 7, "sha7"); err == nil {
t.Fatal("revoked merger must fail the lane's final authorization")
}
}
comments, _, err := c.gh.Issues.ListComments(ctx, "acme", "widget", 7, nil)
if err != nil || len(comments) != 1 || !strings.Contains(comments[0].GetBody(), "@bob") {
t.Fatalf("comments=%v err=%v, want one notice for revoked merger bob", comments, err)
}
}
58 changes: 58 additions & 0 deletions src/pkg/github/automerge/automerge_untrusted_merger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package automerge

import (
"context"
"fmt"
"strconv"
"strings"

gh "github.com/google/go-github/v72/github"
"github.com/hivecommons/hive/pkg/effects"
hgithub "github.com/hivecommons/hive/pkg/github"
)

// noteUntrustedMerger leaves one durable notice per head, including when a
// merger's authorization is revoked between sweep evaluation and lane execution.
// Failure to publish the notice never changes the merge authorization decision.
func (c *Engine) noteUntrustedMerger(ctx context.Context, owner, repo string, number int, head, queuedBy string) {
if err := c.commentUntrustedMerger(ctx, owner, repo, number, head, queuedBy); err != nil {
c.warn("automerge could not report untrusted merger", "repo", owner+"/"+repo, "pr", number, "error", err)
}
}

func (c *Engine) commentUntrustedMerger(ctx context.Context, owner, repo string, number int, head, queuedBy string) error {
marker := "<!-- hive:untrusted-merger head=" + head + " -->"
appLogin := strings.TrimSpace(c.transport.AppBotLogin())
opts := &gh.IssueListCommentsOptions{ListOptions: gh.ListOptions{PerPage: 100}}
for {
comments, resp, err := c.gh.Issues.ListComments(ctx, owner, repo, number, opts)
if err != nil {
return err
}
for _, comment := range comments {
if appLogin != "" && strings.EqualFold(hgithub.SafeGetLogin(comment.GetUser()), appLogin) && strings.Contains(comment.GetBody(), marker) {
return nil
}
}
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
body := fmt.Sprintf("%s\nHive auto-merge is blocked (untrusted-merger): @%s is not a trusted merger for head `%s`. Queue again from a signed-in owner/merger account listed in `dashboard.authorized_users`; an empty allowlist permits no queued merges.", marker, queuedBy, head)
_, err := effects.Execute(ctx, c.mutation, effects.Claim{
Repo: owner + "/" + repo,
Kind: effects.KindIssueComment,
Target: strconv.Itoa(number),
Actor: "automerge",
Inputs: map[string]string{"body": effects.StableDigest(marker)},
}, func(ctx context.Context) (effects.Result, error) {
comment, _, err := c.gh.Issues.CreateComment(ctx, owner, repo, number, &gh.IssueComment{Body: gh.Ptr(body)})
if err != nil {
return effects.Result{}, effects.NotApplied(err)
}
c.noteOwnStageComment(owner, repo, number)
return effects.Result{Provenance: comment.GetHTMLURL()}, nil
})
return err
}
Loading