From 424acc3ebd1706efe6a443be833586fbbfc269ee Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 10:51:03 +0000 Subject: [PATCH 1/3] fix(github): Ask to merge only a requester with write access Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../junior-github/src/webhooks/handler.ts | 1 + .../src/webhooks/installation-requests.ts | 52 +++++-- .../src/webhooks/pull-request-action-text.ts | 7 + .../src/webhooks/pull-request-action.ts | 45 ++++-- .../src/webhooks/pull-request-next-action.ts | 6 + .../tests/pull-request-action-harness.ts | 23 +++- .../tests/pull-request-merge-access.test.ts | 130 ++++++++++++++++++ packages/junior-github/tsconfig.json | 1 + 8 files changed, 242 insertions(+), 23 deletions(-) create mode 100644 packages/junior-github/tests/pull-request-merge-access.test.ts diff --git a/packages/junior-github/src/webhooks/handler.ts b/packages/junior-github/src/webhooks/handler.ts index a530f68beee..421378fedaf 100644 --- a/packages/junior-github/src/webhooks/handler.ts +++ b/packages/junior-github/src/webhooks/handler.ts @@ -476,6 +476,7 @@ export function createGitHubWebhookRoute(args: { }; await syncGitHubPullRequestActions({ botEmail, + cache: args.cache, codeChanges: args.codeChanges, db: args.db, deliveryId, diff --git a/packages/junior-github/src/webhooks/installation-requests.ts b/packages/junior-github/src/webhooks/installation-requests.ts index 09525cc28f1..6373fc56a55 100644 --- a/packages/junior-github/src/webhooks/installation-requests.ts +++ b/packages/junior-github/src/webhooks/installation-requests.ts @@ -428,21 +428,31 @@ const repositoryPermissionSchema = z.object({ const REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1000; /** - * Read one user's role on a repository, with a metadata-only token. GitHub - * returns "none" for accounts without access, such as most bots. Roles are - * cached for ten minutes. + * One user's access to a repository. `role` is GitHub's `role_name`, which + * includes maintain, triage, and custom roles. `permission` is the base + * role that it maps to: admin, write, read, or none. */ -export async function loadRepositoryRole( +interface RepositoryPermission { + permission: string; + role: string; +} + +/** + * Read one user's access to a repository, with a metadata-only token. + * GitHub returns "none" for accounts without access, such as most bots. It + * is cached for ten minutes. + */ +async function loadRepositoryPermission( env: GitHubInstallationEnv, cache: PluginCache, target: { login: string; repositoryFullName: string }, -): Promise { +): Promise { const { owner, name } = splitRepository( target.repositoryFullName, "repository role", ); - return await cache.getOrLoad( - `repository-role:${owner}/${name}:${target.login}`.toLowerCase(), + return await cache.getOrLoad( + `repository-permission:${owner}/${name}:${target.login}`.toLowerCase(), async () => { const token = await issueInstallationToken({ ...env, @@ -456,15 +466,39 @@ export async function loadRepositoryRole( { responses: env.responses, token: token.token }, ), ); - // role_name includes maintain, triage, and custom roles; permission does not. return { - value: response.role_name?.trim() || response.permission, + value: { + permission: response.permission, + role: response.role_name?.trim() || response.permission, + }, ttlMs: REPOSITORY_ROLE_TTL_MS, }; }, ); } +/** Read one user's role on a repository, such as "maintain" or "none". */ +export async function loadRepositoryRole( + env: GitHubInstallationEnv, + cache: PluginCache, + target: { login: string; repositoryFullName: string }, +): Promise { + return (await loadRepositoryPermission(env, cache, target)).role; +} + +/** + * Whether one user can merge pull requests on a repository: their base role + * is write or admin. Maintain and custom roles map to one of these. + */ +export async function loadRepositoryMergeAccess( + env: GitHubInstallationEnv, + cache: PluginCache, + target: { login: string; repositoryFullName: string }, +): Promise { + const { permission } = await loadRepositoryPermission(env, cache, target); + return permission === "admin" || permission === "write"; +} + const timestampSchema = z.iso.datetime({ offset: true }); // GitHub can return a null node for a deleted or hidden item, so the diff --git a/packages/junior-github/src/webhooks/pull-request-action-text.ts b/packages/junior-github/src/webhooks/pull-request-action-text.ts index 34d0c512fb7..6bf9a6f4673 100644 --- a/packages/junior-github/src/webhooks/pull-request-action-text.ts +++ b/packages/junior-github/src/webhooks/pull-request-action-text.ts @@ -29,6 +29,7 @@ export function endedReason( export function closeReason( state: GitHubPullRequestMergeState, previous: GitHubPullRequestAction, + mergeAccess: boolean | undefined, ): CloseReason { const ended = endedReason(state.state); if (ended) return ended; @@ -38,6 +39,12 @@ export function closeReason( if (state.autoMerge) { return { reason: "Auto-merge is on.", status: "dismissed" }; } + if (mergeAccess === false) { + return { + reason: "Only a person with write access can merge it.", + status: "dismissed", + }; + } return { reason: "The pull request is no longer ready to merge.", status: "dismissed", diff --git a/packages/junior-github/src/webhooks/pull-request-action.ts b/packages/junior-github/src/webhooks/pull-request-action.ts index 354906969ef..da51e025515 100644 --- a/packages/junior-github/src/webhooks/pull-request-action.ts +++ b/packages/junior-github/src/webhooks/pull-request-action.ts @@ -4,7 +4,9 @@ * * The action derives from GitHub state. It is "merge" when the pull request * is open, not a draft, auto-merge is off, GitHub's merge state is `clean`, - * no reviewer still requests changes, and GitHub requests no review. GitHub + * no reviewer still requests changes, GitHub requests no review, and the + * requester has write access to the repository. A requester without it + * gets no merge ask: a person with write access merges it. GitHub * gives `blocked` until a required review approves, so a pull request with * no approval is "merge" only where GitHub requires no review, and its item * asks the requester to review it first. A pending review request comes @@ -69,6 +71,7 @@ */ import type { ConversationInboxItemChange, + PluginCache, PluginCodeChanges, PluginConversationInboxItems, PluginLogger, @@ -127,6 +130,7 @@ import { GitHubGraphqlError } from "./graphql-request.js"; import { loadGraphqlRateLimitReset, loadPullRequestMergeState, + loadRepositoryMergeAccess, loadReviewAgainReader, requestPullRequestReviewers, type GitHubInstallationEnv, @@ -269,6 +273,8 @@ async function showAction( action: GitHubPullRequestAction | undefined; dedupeKey: string; identityId: string; + /** Undefined when this sync did not read it. */ + mergeAccess: boolean | undefined; number: number; previous: GitHubPullRequestAction | undefined; reason: GitHubReviewAskReason | undefined; @@ -302,7 +308,7 @@ async function showAction( } else if (args.previous) { await items.close({ dedupeKey: args.dedupeKey, - ...closeReason(state, args.previous), + ...closeReason(state, args.previous, args.mergeAccess), }); } } @@ -460,6 +466,8 @@ interface PullRequestActionSyncContext { */ askAfterRequesterActed?: boolean | undefined; botEmail: string | undefined; + /** Holds the requester's repository access, which decides a merge ask. */ + cache: PluginCache; codeChanges: Pick; db: GitHubDb; env: GitHubInstallationEnv; @@ -533,16 +541,27 @@ async function syncOne( requesterAt: activity.requesterAt, requesterLogin, }); - const next = nextAction( - state, - { - actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt), - askedAgain: asked !== undefined && reason !== undefined, - feedback: requesterFeedback(state, activity), - login: requesterLogin, - }, - previous, - ); + const requester = { + actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt), + askedAgain: asked !== undefined && reason !== undefined, + feedback: requesterFeedback(state, activity), + login: requesterLogin, + }; + const decide = (mergeAccess: boolean) => + nextAction(state, { ...requester, mergeAccess }, previous); + const withAccess = decide(true); + // Only a merge ask, new or saved, needs the requester's access, so most + // syncs read none. Junior knows a requester's access only through their + // linked GitHub login. + const mergeAccess = + withAccess?.action === "merge" || previous === "merge" + ? requesterLogin !== undefined && + (await loadRepositoryMergeAccess(args.env, args.cache, { + login: requesterLogin, + repositoryFullName: target.repositoryFullName, + })) + : undefined; + const next = mergeAccess === false ? decide(false) : withAccess; if ( !askedRequester && requesterLogin && @@ -583,6 +602,7 @@ async function syncOne( action: next.action, dedupeKey, identityId: opener.identityId, + mergeAccess, number: target.number, previous, reason, @@ -796,6 +816,7 @@ export function startedTaskSyncContext( ): PullRequestActionSyncContext { return { botEmail: options.botEmail, + cache: ctx.cache, codeChanges: ctx.codeChanges, db: gitHubDbSchema.parse(ctx.db), env: { ...options.env, responses: ctx.state, tokens: new Map() }, diff --git a/packages/junior-github/src/webhooks/pull-request-next-action.ts b/packages/junior-github/src/webhooks/pull-request-next-action.ts index b20aba629f1..6a7ea94e4e0 100644 --- a/packages/junior-github/src/webhooks/pull-request-next-action.ts +++ b/packages/junior-github/src/webhooks/pull-request-next-action.ts @@ -108,6 +108,11 @@ export function nextAction( /** `requesterFeedback`: the requester waits for Junior's answer. */ feedback: boolean; login: string | undefined; + /** + * GitHub lets the requester merge on the repository. Without it, a + * person with write access merges, so the requester gets no merge ask. + */ + mergeAccess: boolean; }, saved: GitHubPullRequestAction | undefined, ): { action?: GitHubPullRequestAction } | undefined { @@ -116,6 +121,7 @@ export function nextAction( // review request comes first, even where GitHub requires no review. So // does the requester's feedback, because Junior acts next. const canMerge = + requester.mergeAccess && !state.draft && !state.autoMerge && !state.reviewPending && diff --git a/packages/junior-github/tests/pull-request-action-harness.ts b/packages/junior-github/tests/pull-request-action-harness.ts index 8b806c92b98..4e57b739b30 100644 --- a/packages/junior-github/tests/pull-request-action-harness.ts +++ b/packages/junior-github/tests/pull-request-action-harness.ts @@ -217,6 +217,11 @@ export interface GitHubState { laggingFeedback?: string[]; /** GitHub rejects review requests, such as during an outage. */ rejectReviewRequests?: boolean; + /** + * Each user's base role on the repository, by login. A user who is not + * listed has write access, so they can merge. + */ + permissions?: Record; /** The checks of the head commit. */ checks?: Array<{ conclusion: string | null; name: string; status: string }>; /** The checks that a ruleset of the base branch requires. */ @@ -436,6 +441,15 @@ export function mockGitHub(github: GitHubState, requests: string[]) { return HttpResponse.json({ content, id: 1 }, { status: 201 }); }, ), + http.get( + "https://api.github.com/repos/getsentry/junior/collaborators/:login/permission", + ({ params }) => { + const login = String(params["login"]); + requests.push(`permission ${login}`); + const permission = github.permissions?.[login] ?? "write"; + return HttpResponse.json({ permission, role_name: permission }); + }, + ), http.get( "https://api.github.com/repos/getsentry/junior/rules/branches/main", () => { @@ -705,10 +719,12 @@ export function route( }; }, }; - // These webhooks use no Conversation dispatch or cache. + // These webhooks use no Conversation dispatch. const unused = () => { throw new Error("The next-action webhooks do not use this"); }; + // The requester's repository access stays cached across webhooks. + const cached = new Map(); const annotations: PluginConversationAnnotations = { forConversation() { return { @@ -745,7 +761,10 @@ export function route( async update() {}, delete: unused, get: unused, - getOrLoad: unused, + async getOrLoad(key: string, load: () => Promise<{ value: T }>) { + if (!cached.has(key)) cached.set(key, (await load()).value); + return cached.get(key) as T; + }, }, inboxItems, state, diff --git a/packages/junior-github/tests/pull-request-merge-access.test.ts b/packages/junior-github/tests/pull-request-merge-access.test.ts new file mode 100644 index 00000000000..0dea46325b0 --- /dev/null +++ b/packages/junior-github/tests/pull-request-merge-access.test.ts @@ -0,0 +1,130 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createGitHubFixture } from "./github-db"; +import { + DEDUPE_KEY, + checkSuiteCompleted, + mockGitHub, + reviewSubmitted, + route, + seedJuniorPullRequest, + stubGitHubAppEnv, + type GitHubState, + type InboxItemCall, +} from "./pull-request-action-harness"; + +// Only a requester with write access to the repository can merge, so only +// they get a merge ask. +describe("merge ask access", () => { + beforeEach(() => { + stubGitHubAppEnv(); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("gives no merge ask to a requester without write access, and asks for their review instead", async () => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + // The repo requires no review, so GitHub says that it can merge. The + // requester can only read the repo, so a person with write access + // merges it. + const github: GitHubState = { + draft: false, + mergeableStates: ["clean"], + merged: false, + permissions: { Requester: "read" }, + reviews: [], + state: "open", + }; + mockGitHub(github, requests); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + const webhook = route(fixture, calls); + + // The requester can still review it, so Junior asks for that. + await webhook.handler(checkSuiteCompleted()); + expect(requests).toContain("request Requester"); + expect(calls).toMatchObject([ + { kind: "upsert", notice: { title: "Review requested · #946" } }, + ]); + + // Their approval ends the review, and no merge ask follows. + github.requestedReviewers = []; + github.reviews = [ + { + state: "APPROVED", + submitted_at: "2026-07-02T12:00:00.000Z", + user: { login: "Requester" }, + }, + ]; + await webhook.handler( + reviewSubmitted("approved", { login: "Requester" }), + ); + await webhook.handler(checkSuiteCompleted()); + expect(calls.slice(1)).toEqual([ + { + conversationId: "slack:C123:1712345.0001", + input: { + dedupeKey: DEDUPE_KEY, + reason: "The review request ended.", + status: "done", + }, + kind: "close", + }, + ]); + // The access stays cached, so later syncs do not read it again. + expect( + requests.filter((request) => request.startsWith("permission")), + ).toEqual(["permission Requester"]); + } finally { + await fixture.close(); + } + }); + + it("closes a merge ask when the requester has no write access", async () => { + const fixture = await createGitHubFixture(); + const calls: InboxItemCall[] = []; + const requests: string[] = []; + const github: GitHubState = { + draft: false, + mergeableStates: ["clean"], + merged: false, + reviews: [ + { + state: "APPROVED", + submitted_at: "2026-07-02T12:00:00.000Z", + user: { login: "Requester" }, + }, + ], + state: "open", + }; + mockGitHub(github, requests); + try { + await seedJuniorPullRequest(fixture, "slack:C123:1712345.0001"); + await route(fixture, calls).handler(checkSuiteCompleted()); + expect(calls).toMatchObject([ + { kind: "upsert", notice: { title: "Ready to merge · #946" } }, + ]); + + // The requester loses write access. A new route has an empty cache, + // as after the cached access expires. + github.permissions = { Requester: "read" }; + await route(fixture, calls).handler(checkSuiteCompleted()); + expect(calls.slice(1)).toEqual([ + { + conversationId: "slack:C123:1712345.0001", + input: { + dedupeKey: DEDUPE_KEY, + reason: "Only a person with write access can merge it.", + status: "dismissed", + }, + kind: "close", + }, + ]); + } finally { + await fixture.close(); + } + }); +}); diff --git a/packages/junior-github/tsconfig.json b/packages/junior-github/tsconfig.json index 39b74af6c6b..4c0c84240b4 100644 --- a/packages/junior-github/tsconfig.json +++ b/packages/junior-github/tsconfig.json @@ -23,6 +23,7 @@ "tests/pull-request-action.test.ts", "tests/pull-request-comment-only-review.test.ts", "tests/pull-request-limbo.test.ts", + "tests/pull-request-merge-access.test.ts", "tests/pull-request-requester-backfill.test.ts", "tests/pull-request-review-again.test.ts" ] From 634ad941ef207f05c329288c94cee1c87994d7da Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:08:18 +0000 Subject: [PATCH 2/3] docs(design): State that only a requester with write access gets a merge ask Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- design/github.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/design/github.md b/design/github.md index 4652aadcb68..c5d57b93ee1 100644 --- a/design/github.md +++ b/design/github.md @@ -71,10 +71,13 @@ also wake a Conversation or run an Event automation. draft that Junior held, Junior marks it ready, so GitHub asks its code owners only after the requester has looked. - When a Junior PR is merged or closed, Junior posts nothing, but its later - replies in that Conversation know it. When GitHub says that it can merge - and no reviewer requests changes, the requester gets a "Ready to merge" - Inbox item. Where GitHub requires no review, a PR with no approval gets - it too, and the item tells the requester to review it before they merge. + replies in that Conversation know it. When GitHub says that it can merge, + no reviewer requests changes, and the requester has write access to the + repo, the requester gets a "Ready to merge" Inbox item. A requester + without write access gets no merge ask, because a person with write + access merges the PR. Where GitHub requires no review, a PR with no + approval gets it too, and the item tells the requester to review it + before they merge. When a review is requested and still pending, the PR asks for that review instead, even where the repo allows merging without one. - When GitHub fails the next-action read for a while (rate limit or From 399f6a91e9be44c69e718aba7649dc9c8ceda95e Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 11:33:38 +0000 Subject: [PATCH 3/3] test(github): Link the requester's GitHub login in the merge ask test --- .../github-pull-request-ask.test.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/packages/junior/tests/integration/github-pull-request-ask.test.ts b/packages/junior/tests/integration/github-pull-request-ask.test.ts index 66e9c6a1beb..0fba3bfd961 100644 --- a/packages/junior/tests/integration/github-pull-request-ask.test.ts +++ b/packages/junior/tests/integration/github-pull-request-ask.test.ts @@ -8,7 +8,7 @@ import { createApp, defineJuniorPlugins } from "@/app"; import { turnBehavior } from "@/chat/conversations/kind-behavior"; import { setDashboardConversationLinkOptions } from "@/chat/dashboard-link"; import { getDb, getSqlExecutor } from "@/chat/db"; -import { upsertIdentity } from "@/chat/identities/sql"; +import { upsertIdentity, upsertLinkedIdentity } from "@/chat/identities/sql"; import { getPluginTools } from "@/chat/plugins/hooks/tools"; import { listConversationAnnotations } from "@/chat/plugins/annotations"; import { migratePluginSchemas } from "@/chat/plugins/migrations"; @@ -150,13 +150,23 @@ describe("the ask of a Junior pull request", () => { it("closes before the chip says merged, so no reader sees a merged pull request with an open ask", async () => { app = await createApp({ plugins: defineJuniorPlugins([githubPlugin()]) }); - await upsertIdentity(getSqlExecutor(), { + const requester = await upsertIdentity(getSqlExecutor(), { displayName: "Pat Requester", + email: "pat@example.com", + emailVerified: true, kind: "user", provider: "slack", providerSubjectId: person.userId, providerTenantId: person.teamId, }); + // A merge ask needs the requester's GitHub login, to read their access. + if (!requester.userId) throw new Error("missing requester user"); + await upsertLinkedIdentity(getSqlExecutor(), requester.userId, { + handle: "pat-requester", + kind: "user", + provider: "github", + providerSubjectId: "1001", + }); const { fixture } = await prepareSlackParentConversation(); // The footer that links the pull request to its Conversation needs a // dashboard link. @@ -226,6 +236,11 @@ describe("the ask of a Junior pull request", () => { }, }); }), + // The requester has write access, so they get the merge ask. + http.get( + "https://api.github.com/repos/getsentry/junior/collaborators/pat-requester/permission", + () => HttpResponse.json({ permission: "write", role_name: "write" }), + ), http.get(`${API}/commits`, async () => { await observe(); return HttpResponse.json([]);