From 34191e4872b2e6adab4b409845d54c78ef4c5145 Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Tue, 12 May 2026 21:39:03 +0800 Subject: [PATCH] Require owner approval for lenient merges --- .env.example | 1 + README.md | 3 + src/config.ts | 2 + src/github/webhookHandler.ts | 31 ++++++- src/review/format.ts | 3 + src/review/openaiReviewer.ts | 9 +- src/review/processor.ts | 167 +++++++++++++++++++++++++++++++++-- src/types.ts | 2 + 8 files changed, 211 insertions(+), 7 deletions(-) diff --git a/.env.example b/.env.example index f74c2dc..ef0532b 100644 --- a/.env.example +++ b/.env.example @@ -7,6 +7,7 @@ OPENAI_MODEL=gpt-4.1 # Optional controls BOT_NAME=ghbot +LENIENT_APPROVAL_USER=lezi-fun AUTO_MERGE=true MERGE_METHOD=squash REQUIRE_CHECKS=true diff --git a/README.md b/README.md index bcee60a..9e67d39 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ GitHub App bot that reviews pull requests with an AI reviewer, leaves inline rev - `suggestion` findings are included as non-blocking suggestions. - Creates a GitHub check run with a `Lenient check` button when strict review requests changes. - When `Lenient check` is clicked, reviews again and only blocks dangerous changes, runtime-impacting issues, errors, crashes, broken builds, data-loss risks, and security risks. +- A PR that passes `Lenient check` is not auto-merged until `@lezi-fun` approves the current head commit. +- If the reviewer detects clearly malicious code, the bot comments with the reason and closes the pull request. - Posts inline comments only on valid added diff lines. - Approves clean pull requests. - If `AUTO_MERGE=true`, merges only after: @@ -61,6 +63,7 @@ Important optional variables: - `AUTO_MERGE`: defaults to `false`. Set to `true` only after testing on a non-critical repo. - `MERGE_METHOD`: `merge`, `squash`, or `rebase`. Defaults to `squash`. - `REQUIRE_CHECKS`: defaults to `true`. +- `LENIENT_APPROVAL_USER`: defaults to `lezi-fun`. - `MAX_PATCH_CHARS`: maximum patch payload sent to the reviewer. Defaults to `120000`. ## Local development diff --git a/src/config.ts b/src/config.ts index ec55797..7074d9c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -9,6 +9,7 @@ const configSchema = z.object({ openAiApiKey: z.string().min(1), openAiModel: z.string().min(1).default("gpt-4.1"), botName: z.string().min(1).default("ghbot"), + lenientApprovalUser: z.string().min(1).default("lezi-fun"), autoMerge: z.coerce.boolean().default(false), mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"), requireChecks: z.coerce.boolean().default(true), @@ -23,6 +24,7 @@ export const config = configSchema.parse({ openAiApiKey: process.env.OPENAI_API_KEY, openAiModel: process.env.OPENAI_MODEL, botName: process.env.BOT_NAME, + lenientApprovalUser: process.env.LENIENT_APPROVAL_USER, autoMerge: process.env.AUTO_MERGE, mergeMethod: process.env.MERGE_METHOD, requireChecks: process.env.REQUIRE_CHECKS, diff --git a/src/github/webhookHandler.ts b/src/github/webhookHandler.ts index 90e83c0..75ed6cb 100644 --- a/src/github/webhookHandler.ts +++ b/src/github/webhookHandler.ts @@ -2,7 +2,12 @@ import { Webhooks } from "@octokit/webhooks"; import { config } from "../config.js"; import { getInstallationOctokit } from "./app.js"; import { logger } from "../logger.js"; -import { isLenientCheckAction, processLenientCheckRunAction, processPullRequest } from "../review/processor.js"; +import { + isLenientCheckAction, + processLenientCheckRunAction, + processPullRequest, + processPullRequestReviewApproval +} from "../review/processor.js"; export function createGitHubWebhooks(): Webhooks { const webhooks = new Webhooks({ @@ -47,6 +52,30 @@ export function createGitHubWebhooks(): Webhooks { }); }); + webhooks.on("pull_request_review.submitted", async ({ payload }) => { + const reviewerLogin = payload.review.user?.login; + if (!reviewerLogin) { + logger.warn({ repository: payload.repository.full_name, pullNumber: payload.pull_request.number }, "Skipping review without reviewer login."); + return; + } + + const installationId = payload.installation?.id; + if (!installationId) { + logger.warn({ repository: payload.repository.full_name, pullNumber: payload.pull_request.number }, "Skipping review without installation id."); + return; + } + + const octokit = await getInstallationOctokit(installationId); + await processPullRequestReviewApproval(octokit, { + owner: payload.repository.owner.login, + repo: payload.repository.name, + pullNumber: payload.pull_request.number, + reviewerLogin, + state: payload.review.state, + commitId: payload.review.commit_id + }); + }); + webhooks.onError((error) => { logger.error({ error }, "Webhook handler failed."); }); diff --git a/src/review/format.ts b/src/review/format.ts index b702cb5..b15fba9 100644 --- a/src/review/format.ts +++ b/src/review/format.ts @@ -8,6 +8,9 @@ export function formatReviewBody(decision: ReviewDecision, unpostedFindings: Rev "", decision.summary, "", + ...(decision.shouldClosePullRequest + ? [`Close PR: yes`, "", `Close reason: ${decision.closeReason}`, ""] + : []), `Decision: ${decision.safeToMerge ? "safe to merge" : "changes requested"}` ]; diff --git a/src/review/openaiReviewer.ts b/src/review/openaiReviewer.ts index 9b80b30..023761b 100644 --- a/src/review/openaiReviewer.ts +++ b/src/review/openaiReviewer.ts @@ -5,6 +5,8 @@ import type { PullRequestFile, ReviewDecision, ReviewMode } from "../types.js"; const reviewDecisionSchema = z.object({ safeToMerge: z.boolean(), + shouldClosePullRequest: z.boolean(), + closeReason: z.string(), summary: z.string(), findings: z.array( z.object({ @@ -37,9 +39,11 @@ export class OpenAiReviewer { schema: { type: "object", additionalProperties: false, - required: ["safeToMerge", "summary", "findings"], + required: ["safeToMerge", "shouldClosePullRequest", "closeReason", "summary", "findings"], properties: { safeToMerge: { type: "boolean" }, + shouldClosePullRequest: { type: "boolean" }, + closeReason: { type: "string" }, summary: { type: "string" }, findings: { type: "array", @@ -97,6 +101,9 @@ function buildSystemPrompt(mode: ReviewMode): string { const commonRules = [ "You are a senior software engineer reviewing a GitHub pull request.", "Only set safeToMerge=true when there are no blocking findings.", + "Set shouldClosePullRequest=true only for clearly malicious code: backdoors, credential theft, token exfiltration, destructive commands, malware, hidden persistence, privilege escalation, supply-chain compromise, or intentionally abusive behavior.", + "Do not set shouldClosePullRequest=true for ordinary bugs, crashes, failing tests, incomplete code, suspicious-but-unproven code, or low-quality changes.", + "When shouldClosePullRequest=true, explain the evidence in closeReason. Otherwise closeReason must be an empty string.", "For each finding, choose a line number that exists on an added line in the supplied patch whenever possible.", "Do not invent files, line numbers, test results, or runtime behavior." ]; diff --git a/src/review/processor.ts b/src/review/processor.ts index e6faef9..56dc718 100644 --- a/src/review/processor.ts +++ b/src/review/processor.ts @@ -59,16 +59,116 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, mode }); + if (decision.shouldClosePullRequest) { + await closeMaliciousPullRequest(octokit, { + owner, + repo, + pullNumber, + reason: decision.closeReason || "The automated review found clearly malicious code." + }); + logger.warn({ owner, repo, pullNumber }, "Closed pull request because malicious code was detected."); + return; + } + if (!decision.safeToMerge) { logger.info({ owner, repo, pullNumber }, "Review requested changes; not merging."); return; } + await maybeMergePullRequest(octokit, { + owner, + repo, + pullNumber, + title: pullRequest.title, + headSha: pullRequest.head.sha, + mode + }); +} + +export async function processPullRequestReviewApproval( + octokit: Octokit, + params: { + owner: string; + repo: string; + pullNumber: number; + reviewerLogin: string; + state: string; + commitId: string; + } +): Promise { + if (params.state !== "approved" || params.reviewerLogin !== config.lenientApprovalUser) { + return; + } + + const { data: pullRequest } = await octokit.rest.pulls.get({ + owner: params.owner, + repo: params.repo, + pull_number: params.pullNumber + }); + + if (pullRequest.head.sha !== params.commitId) { + logger.info( + { + owner: params.owner, + repo: params.repo, + pullNumber: params.pullNumber, + approvedCommit: params.commitId, + currentHead: pullRequest.head.sha + }, + "Ignoring approval because it does not match the current PR head." + ); + return; + } + + await maybeMergePullRequest(octokit, { + owner: params.owner, + repo: params.repo, + pullNumber: params.pullNumber, + title: pullRequest.title, + headSha: pullRequest.head.sha, + mode: "lenient" + }); +} + +async function maybeMergePullRequest( + octokit: Octokit, + params: { + owner: string; + repo: string; + pullNumber: number; + title: string; + headSha: string; + mode: ReviewMode; + } +): Promise { + const { owner, repo, pullNumber } = params; + if (!config.autoMerge) { logger.info({ owner, repo, pullNumber }, "AUTO_MERGE is disabled; approved only."); return; } + if (params.mode === "lenient") { + const approvedByOwner = await hasCurrentHeadApprovalFrom(octokit, { + owner, + repo, + pullNumber, + headSha: params.headSha, + reviewerLogin: config.lenientApprovalUser + }); + + if (!approvedByOwner) { + await octokit.rest.issues.createComment({ + owner, + repo, + issue_number: pullNumber, + body: `Lenient check passed, but this PR will not be merged until @${config.lenientApprovalUser} approves the current head commit.` + }); + logger.info({ owner, repo, pullNumber, reviewer: config.lenientApprovalUser }, "Waiting for lenient approval before merging."); + return; + } + } + const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber); if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") { await octokit.rest.issues.createComment({ @@ -84,7 +184,7 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, const checks = await requiredChecksAreGreen(octokit, { owner, repo, - ref: pullRequest.head.sha + ref: params.headSha }); if (!checks.ok) { await octokit.rest.issues.createComment({ @@ -102,7 +202,33 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef, repo, pull_number: pullNumber, merge_method: config.mergeMethod, - commit_title: `${pullRequest.title} (#${pullNumber})` + commit_title: `${params.title} (#${pullNumber})` + }); +} + +async function hasCurrentHeadApprovalFrom( + octokit: Octokit, + params: { + owner: string; + repo: string; + pullNumber: number; + headSha: string; + reviewerLogin: string; + } +): Promise { + const reviews = await octokit.paginate(octokit.rest.pulls.listReviews, { + owner: params.owner, + repo: params.repo, + pull_number: params.pullNumber, + per_page: 100 + }); + + return reviews.some((review) => { + return ( + review.user?.login === params.reviewerLogin && + review.state === "APPROVED" && + review.commit_id === params.headSha + ); }); } @@ -225,7 +351,8 @@ async function upsertReviewCheckRun( } ): Promise { const hasBlockingFinding = params.decision.findings.some((finding) => finding.severity === "blocking"); - const conclusion = params.decision.safeToMerge && !hasBlockingFinding ? "success" : "action_required"; + const conclusion = + params.decision.shouldClosePullRequest || hasBlockingFinding || !params.decision.safeToMerge ? "action_required" : "success"; await octokit.rest.checks.create({ owner: params.owner, @@ -235,8 +362,14 @@ async function upsertReviewCheckRun( status: "completed", conclusion, output: { - title: params.mode === "lenient" ? "Lenient review completed" : "Strict review completed", - summary: params.decision.summary + title: params.decision.shouldClosePullRequest + ? "Malicious code detected" + : params.mode === "lenient" + ? "Lenient review completed" + : "Strict review completed", + summary: params.decision.shouldClosePullRequest + ? `${params.decision.summary}\n\nClose reason: ${params.decision.closeReason}` + : params.decision.summary }, actions: params.mode === "strict" && conclusion === "action_required" @@ -255,6 +388,30 @@ export function isLenientCheckAction(identifier: string): boolean { return identifier === LENIENT_ACTION_IDENTIFIER; } +async function closeMaliciousPullRequest( + octokit: Octokit, + params: { + owner: string; + repo: string; + pullNumber: number; + reason: string; + } +): Promise { + await octokit.rest.issues.createComment({ + owner: params.owner, + repo: params.repo, + issue_number: params.pullNumber, + body: `This PR was automatically closed because the review detected clearly malicious code.\n\nReason: ${params.reason}` + }); + + await octokit.rest.pulls.update({ + owner: params.owner, + repo: params.repo, + pull_number: params.pullNumber, + state: "closed" + }); +} + async function waitForMergeable( octokit: Octokit, owner: string, diff --git a/src/types.ts b/src/types.ts index e131147..14de347 100644 --- a/src/types.ts +++ b/src/types.ts @@ -22,6 +22,8 @@ export type ReviewFinding = { export type ReviewDecision = { safeToMerge: boolean; + shouldClosePullRequest: boolean; + closeReason: string; summary: string; findings: ReviewFinding[]; };