Require owner approval for lenient merges
This commit is contained in:
1 parent
5cca2e8564
commit
34191e4872
8 files changed
+211
-7
No files matched your search
@@ -7,6 +7,7 @@ OPENAI_MODEL=gpt-4.1
|
|||||||
|
|
||||||
# Optional controls
|
# Optional controls
|
||||||
BOT_NAME=ghbot
|
BOT_NAME=ghbot
|
||||||
|
LENIENT_APPROVAL_USER=lezi-fun
|
||||||
AUTO_MERGE=true
|
AUTO_MERGE=true
|
||||||
MERGE_METHOD=squash
|
MERGE_METHOD=squash
|
||||||
REQUIRE_CHECKS=true
|
REQUIRE_CHECKS=true
|
||||||
|
|||||||
@@ -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.
|
- `suggestion` findings are included as non-blocking suggestions.
|
||||||
- Creates a GitHub check run with a `Lenient check` button when strict review requests changes.
|
- 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.
|
- 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.
|
- Posts inline comments only on valid added diff lines.
|
||||||
- Approves clean pull requests.
|
- Approves clean pull requests.
|
||||||
- If `AUTO_MERGE=true`, merges only after:
|
- 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.
|
- `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`.
|
- `MERGE_METHOD`: `merge`, `squash`, or `rebase`. Defaults to `squash`.
|
||||||
- `REQUIRE_CHECKS`: defaults to `true`.
|
- `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`.
|
- `MAX_PATCH_CHARS`: maximum patch payload sent to the reviewer. Defaults to `120000`.
|
||||||
|
|
||||||
## Local development
|
## Local development
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ const configSchema = z.object({
|
|||||||
openAiApiKey: z.string().min(1),
|
openAiApiKey: z.string().min(1),
|
||||||
openAiModel: z.string().min(1).default("gpt-4.1"),
|
openAiModel: z.string().min(1).default("gpt-4.1"),
|
||||||
botName: z.string().min(1).default("ghbot"),
|
botName: z.string().min(1).default("ghbot"),
|
||||||
|
lenientApprovalUser: z.string().min(1).default("lezi-fun"),
|
||||||
autoMerge: z.coerce.boolean().default(false),
|
autoMerge: z.coerce.boolean().default(false),
|
||||||
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
|
mergeMethod: z.enum(["merge", "squash", "rebase"]).default("squash"),
|
||||||
requireChecks: z.coerce.boolean().default(true),
|
requireChecks: z.coerce.boolean().default(true),
|
||||||
@@ -23,6 +24,7 @@ export const config = configSchema.parse({
|
|||||||
openAiApiKey: process.env.OPENAI_API_KEY,
|
openAiApiKey: process.env.OPENAI_API_KEY,
|
||||||
openAiModel: process.env.OPENAI_MODEL,
|
openAiModel: process.env.OPENAI_MODEL,
|
||||||
botName: process.env.BOT_NAME,
|
botName: process.env.BOT_NAME,
|
||||||
|
lenientApprovalUser: process.env.LENIENT_APPROVAL_USER,
|
||||||
autoMerge: process.env.AUTO_MERGE,
|
autoMerge: process.env.AUTO_MERGE,
|
||||||
mergeMethod: process.env.MERGE_METHOD,
|
mergeMethod: process.env.MERGE_METHOD,
|
||||||
requireChecks: process.env.REQUIRE_CHECKS,
|
requireChecks: process.env.REQUIRE_CHECKS,
|
||||||
|
|||||||
@@ -2,7 +2,12 @@ import { Webhooks } from "@octokit/webhooks";
|
|||||||
import { config } from "../config.js";
|
import { config } from "../config.js";
|
||||||
import { getInstallationOctokit } from "./app.js";
|
import { getInstallationOctokit } from "./app.js";
|
||||||
import { logger } from "../logger.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 {
|
export function createGitHubWebhooks(): Webhooks {
|
||||||
const webhooks = new 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) => {
|
webhooks.onError((error) => {
|
||||||
logger.error({ error }, "Webhook handler failed.");
|
logger.error({ error }, "Webhook handler failed.");
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ export function formatReviewBody(decision: ReviewDecision, unpostedFindings: Rev
|
|||||||
"",
|
"",
|
||||||
decision.summary,
|
decision.summary,
|
||||||
"",
|
"",
|
||||||
|
...(decision.shouldClosePullRequest
|
||||||
|
? [`Close PR: yes`, "", `Close reason: ${decision.closeReason}`, ""]
|
||||||
|
: []),
|
||||||
`Decision: ${decision.safeToMerge ? "safe to merge" : "changes requested"}`
|
`Decision: ${decision.safeToMerge ? "safe to merge" : "changes requested"}`
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import type { PullRequestFile, ReviewDecision, ReviewMode } from "../types.js";
|
|||||||
|
|
||||||
const reviewDecisionSchema = z.object({
|
const reviewDecisionSchema = z.object({
|
||||||
safeToMerge: z.boolean(),
|
safeToMerge: z.boolean(),
|
||||||
|
shouldClosePullRequest: z.boolean(),
|
||||||
|
closeReason: z.string(),
|
||||||
summary: z.string(),
|
summary: z.string(),
|
||||||
findings: z.array(
|
findings: z.array(
|
||||||
z.object({
|
z.object({
|
||||||
@@ -37,9 +39,11 @@ export class OpenAiReviewer {
|
|||||||
schema: {
|
schema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
additionalProperties: false,
|
additionalProperties: false,
|
||||||
required: ["safeToMerge", "summary", "findings"],
|
required: ["safeToMerge", "shouldClosePullRequest", "closeReason", "summary", "findings"],
|
||||||
properties: {
|
properties: {
|
||||||
safeToMerge: { type: "boolean" },
|
safeToMerge: { type: "boolean" },
|
||||||
|
shouldClosePullRequest: { type: "boolean" },
|
||||||
|
closeReason: { type: "string" },
|
||||||
summary: { type: "string" },
|
summary: { type: "string" },
|
||||||
findings: {
|
findings: {
|
||||||
type: "array",
|
type: "array",
|
||||||
@@ -97,6 +101,9 @@ function buildSystemPrompt(mode: ReviewMode): string {
|
|||||||
const commonRules = [
|
const commonRules = [
|
||||||
"You are a senior software engineer reviewing a GitHub pull request.",
|
"You are a senior software engineer reviewing a GitHub pull request.",
|
||||||
"Only set safeToMerge=true when there are no blocking findings.",
|
"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.",
|
"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."
|
"Do not invent files, line numbers, test results, or runtime behavior."
|
||||||
];
|
];
|
||||||
|
|||||||
+162
-5
@@ -59,16 +59,116 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef,
|
|||||||
mode
|
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) {
|
if (!decision.safeToMerge) {
|
||||||
logger.info({ owner, repo, pullNumber }, "Review requested changes; not merging.");
|
logger.info({ owner, repo, pullNumber }, "Review requested changes; not merging.");
|
||||||
return;
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
const { owner, repo, pullNumber } = params;
|
||||||
|
|
||||||
if (!config.autoMerge) {
|
if (!config.autoMerge) {
|
||||||
logger.info({ owner, repo, pullNumber }, "AUTO_MERGE is disabled; approved only.");
|
logger.info({ owner, repo, pullNumber }, "AUTO_MERGE is disabled; approved only.");
|
||||||
return;
|
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);
|
const mergeablePullRequest = await waitForMergeable(octokit, owner, repo, pullNumber);
|
||||||
if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") {
|
if (mergeablePullRequest.mergeable !== true || mergeablePullRequest.mergeable_state === "dirty") {
|
||||||
await octokit.rest.issues.createComment({
|
await octokit.rest.issues.createComment({
|
||||||
@@ -84,7 +184,7 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef,
|
|||||||
const checks = await requiredChecksAreGreen(octokit, {
|
const checks = await requiredChecksAreGreen(octokit, {
|
||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
ref: pullRequest.head.sha
|
ref: params.headSha
|
||||||
});
|
});
|
||||||
if (!checks.ok) {
|
if (!checks.ok) {
|
||||||
await octokit.rest.issues.createComment({
|
await octokit.rest.issues.createComment({
|
||||||
@@ -102,7 +202,33 @@ export async function processPullRequest(octokit: Octokit, ref: PullRequestRef,
|
|||||||
repo,
|
repo,
|
||||||
pull_number: pullNumber,
|
pull_number: pullNumber,
|
||||||
merge_method: config.mergeMethod,
|
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<boolean> {
|
||||||
|
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<void> {
|
): Promise<void> {
|
||||||
const hasBlockingFinding = params.decision.findings.some((finding) => finding.severity === "blocking");
|
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({
|
await octokit.rest.checks.create({
|
||||||
owner: params.owner,
|
owner: params.owner,
|
||||||
@@ -235,8 +362,14 @@ async function upsertReviewCheckRun(
|
|||||||
status: "completed",
|
status: "completed",
|
||||||
conclusion,
|
conclusion,
|
||||||
output: {
|
output: {
|
||||||
title: params.mode === "lenient" ? "Lenient review completed" : "Strict review completed",
|
title: params.decision.shouldClosePullRequest
|
||||||
summary: params.decision.summary
|
? "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:
|
actions:
|
||||||
params.mode === "strict" && conclusion === "action_required"
|
params.mode === "strict" && conclusion === "action_required"
|
||||||
@@ -255,6 +388,30 @@ export function isLenientCheckAction(identifier: string): boolean {
|
|||||||
return identifier === LENIENT_ACTION_IDENTIFIER;
|
return identifier === LENIENT_ACTION_IDENTIFIER;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function closeMaliciousPullRequest(
|
||||||
|
octokit: Octokit,
|
||||||
|
params: {
|
||||||
|
owner: string;
|
||||||
|
repo: string;
|
||||||
|
pullNumber: number;
|
||||||
|
reason: string;
|
||||||
|
}
|
||||||
|
): Promise<void> {
|
||||||
|
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(
|
async function waitForMergeable(
|
||||||
octokit: Octokit,
|
octokit: Octokit,
|
||||||
owner: string,
|
owner: string,
|
||||||
|
|||||||
@@ -22,6 +22,8 @@ export type ReviewFinding = {
|
|||||||
|
|
||||||
export type ReviewDecision = {
|
export type ReviewDecision = {
|
||||||
safeToMerge: boolean;
|
safeToMerge: boolean;
|
||||||
|
shouldClosePullRequest: boolean;
|
||||||
|
closeReason: string;
|
||||||
summary: string;
|
summary: string;
|
||||||
findings: ReviewFinding[];
|
findings: ReviewFinding[];
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in new issue
Block a user