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
20 changes: 15 additions & 5 deletions .github/MAINTAINERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,14 @@ that carries the **`open-for-contribution`** label. This is enforced by the
[`Contribution Gate`](./workflows/contribution-gate.yml) workflow, whose decision logic
lives in [`scripts/contribution-gate.ts`](./scripts/contribution-gate.ts).

The gate runs **manually across every open PR** via the workflow's _Run workflow_
button. Opening, reopening, or editing a PR does not run the gate.
The gate sweeps **every open PR every 15 minutes**, at minutes 7, 22, 37, and 52 of
each hour (UTC), and can also run manually. GitHub can delay or drop scheduled runs,
so enforcement has no fixed response time. Opening, reopening, or editing a PR does
not trigger an immediate run.

Both scheduled and manual sweeps run only from the default branch. They execute
repository code, never PR code, and share a concurrency group to prevent overlap.
The schedule starts once this workflow reaches the default branch.

During a sweep, a pull request is **closed with an explanatory comment** when the author
is external and any of these is true:
Expand All @@ -21,15 +27,19 @@ is external and any of these is true:
- the linked issue is closed, or
- the linked issue is missing the `open-for-contribution` label.

Sweeps also catch issue closures and label removals without a PR edit. Reopening a
PR does not bypass the policy: link a qualifying issue before reopening, or the
next sweep will comment and close it again.

Authors whose `author_association` is `OWNER`, `MEMBER`, or `COLLABORATOR`, and bot
accounts, are **exempt** — Supabase maintainers can keep working from Linear tickets that
aren't public on GitHub.

### Running the gate manually

Use **Actions → Contribution Gate → Run workflow** from a trusted branch to sweep all open
PRs on demand, for example after bulk-applying `open-for-contribution` labels. Maintainers
must run this sweep to enforce the contribution policy. Set the **`dry_run`**
Use **Actions → Contribution Gate → Run workflow** from the default branch to sweep
all open PRs on demand, for example after bulk-applying `open-for-contribution` labels.
Runs from other branches are skipped. Set the **`dry_run`**
input to `true` first to log each PR's decision in the run output without commenting on or
closing anything; run again with `dry_run` unchecked to apply the decisions.

Expand Down
129 changes: 129 additions & 0 deletions .github/scripts/contribution-gate.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import { expect, test } from "bun:test";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { evaluateGate } from "./contribution-gate.ts";

test("sweeps reuse the same explanation after close fails but post a new one when the reason changes", async () => {
const root = await mkdtemp(join(tmpdir(), "contribution-gate-"));
const statePath = join(root, "state.json");
const preloadPath = join(root, "github.ts");
const message = evaluateGate({
repository: "supabase/cli",
isInternal: false,
isBot: false,
linkedIssues: [],
}).message;
const bot = { id: 41898282, login: "github-actions[bot]", type: "Bot" };
const comments = Array.from({ length: 100 }, (_, index) => ({
body: index === 3 ? "unrelated bot comment" : message,
user:
index === 0
? { ...bot, id: 123 }
: index === 1
? { ...bot, login: "attacker" }
: index === 2
? { ...bot, type: "User" }
: index === 3
? bot
: { id: 123, login: "attacker", type: "User" },
}));
try {
await writeFile(
statePath,
JSON.stringify({ comments, posts: 0, closes: 0, pages: [], hasLinkedIssue: false }),
);
// Every request is intercepted in the child, including mutations and unknown URLs.
await writeFile(
preloadPath,
`
import { readFileSync, writeFileSync } from "node:fs";
const path = ${JSON.stringify(statePath)};
const state = JSON.parse(readFileSync(path, "utf8"));
const base = "https://api.github.com/repos/supabase/cli";
const respond = (body, status = 200) => new Response(JSON.stringify(body), { status });
globalThis.fetch = async (input, init = {}) => {
const url = String(input);
const method = init.method ?? "GET";
if (url === base + "/pulls?state=open&per_page=100&page=1" && method === "GET") {
return respond([{ number: 1, author_association: "NONE", user: { login: "ext", type: "User" } }]);
}
if (url === base + "/collaborators/ext/permission" && method === "GET") {
return respond({ permission: "read" });
}
if (url === "https://api.github.com/graphql" && method === "POST") {
const nodes = state.hasLinkedIssue ? [{ number: 5, state: "OPEN", repository: { nameWithOwner: "supabase/cli" }, labels: { nodes: [] } }] : [];
return respond({ data: { repository: { pullRequest: { closingIssuesReferences: { nodes } } } } });
}
if (url.startsWith(base + "/issues/1/comments?") && method === "GET") {
const params = new URL(url).searchParams;
if (params.get("per_page") !== "100") throw new Error("Expected paginated comments");
const page = Number(params.get("page"));
state.pages.push(page);
return respond(state.comments.slice((page - 1) * 100, page * 100));
}
if (url === base + "/issues/1/comments" && method === "POST") {
state.posts++;
state.comments.push({ body: JSON.parse(init.body).body, user: ${JSON.stringify(bot)} });
return respond({});
}
if (url === base + "/issues/1" && method === "PATCH") {
state.closes++;
return respond({}, state.closes === 1 ? 503 : 200);
}
throw new Error("Unexpected mocked GitHub request: " + method + " " + url);
};
process.on("exit", () => writeFileSync(path, JSON.stringify(state)));
`,
);
const sweep = async () => {
const child = Bun.spawn(
[process.execPath, "--preload", preloadPath, join(import.meta.dir, "contribution-gate.ts")],
{
env: {
...process.env,
GITHUB_TOKEN: "fake-test-token",
GITHUB_REPOSITORY: "supabase/cli",
DRY_RUN: "false",
},
stdout: "pipe",
stderr: "pipe",
},
);
const [code, stdout, stderr] = await Promise.all([
child.exited,
new Response(child.stdout).text(),
new Response(child.stderr).text(),
]);
return { code, stdout, stderr };
};
const first = await sweep();
expect(first.code).toBe(1);
expect(first.stderr).toContain("503");
const afterFirst = JSON.parse(await readFile(statePath, "utf8"));
expect(afterFirst.posts).toBe(1);
expect(afterFirst.closes).toBe(1);

const second = await sweep();
expect(second).toMatchObject({ code: 0, stderr: "" });
expect(second.stdout).toContain("1 closed");
expect(second.stdout).toContain("reason=no-linked-issue");
const afterSecond = JSON.parse(await readFile(statePath, "utf8"));
expect(afterSecond.posts).toBe(1);
expect(afterSecond.closes).toBe(2);
expect(afterSecond.pages).toEqual([1, 2, 1, 2]);

await writeFile(statePath, JSON.stringify({ ...afterSecond, hasLinkedIssue: true }));
const third = await sweep();
expect(third).toMatchObject({ code: 0, stderr: "" });
expect(third.stdout).toContain("reason=missing-label");
const afterThird = JSON.parse(await readFile(statePath, "utf8"));
expect(afterThird.posts).toBe(2);
expect(afterThird.closes).toBe(3);
expect(afterThird.comments.at(-1).body).toContain(
"The linked issue hasn't been marked `open-for-contribution` yet",
);
} finally {
await rm(root, { recursive: true, force: true });
}
});
95 changes: 94 additions & 1 deletion .github/scripts/contribution-gate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,99 @@ describe("evaluateAllOpenPrs", () => {
expect(permissionLookups).not.toContain("dependabot");
});

test.each(["permission", "issues", "close"])(
"continues after a %s failure and rejects the sweep with PR context",
async (failure) => {
const { io, closed } = makeIo(
[1, 2].map((number) => ({
number,
authorLogin: `ext-${number}`,
authorAssociation: "NONE",
isBot: false,
})),
{},
);
if (failure === "permission") {
io.fetchPermission = async (login) => {
if (login === "ext-1") throw new Error("permission outage");
return undefined;
};
} else if (failure === "issues") {
io.fetchLinkedIssues = async (number) => {
if (number === 1) throw new Error("issues outage");
return [];
};
} else {
const close = io.closePr;
io.closePr = async (number, message) => {
if (number === 1) throw new Error("close outage");
await close(number, message);
};
}
await expect(evaluateAllOpenPrs(io, REPO)).rejects.toThrow(/PR #1/);
expect(closed.map((pr) => pr.number)).toEqual([2]);
},
);

test("exempt PRs do not depend on the linked issue API", async () => {
const { io, closed } = makeIo(
[
{ number: 1, authorLogin: "bot", authorAssociation: "NONE", isBot: true },
{ number: 2, authorLogin: "member", authorAssociation: "MEMBER", isBot: false },
{ number: 3, authorLogin: "private", authorAssociation: "NONE", isBot: false },
],
{},
{ private: "write" },
);
io.fetchLinkedIssues = async () => {
throw new Error("issues outage");
};
expect((await evaluateAllOpenPrs(io, REPO)).map((entry) => entry.result.reason)).toEqual([
"bot",
"internal",
"internal",
]);
expect(closed).toEqual([]);
});

test.each(["read", "write", undefined])(
"reuses successful %s permission results per author",
async (permission) => {
const { io, permissionLookups } = makeIo(
[1, 2].map((number) => ({
number,
authorLogin: "same-author",
authorAssociation: "NONE",
isBot: false,
})),
{},
permission ? { "same-author": permission } : {},
);
await evaluateAllOpenPrs(io, REPO);
expect(permissionLookups).toEqual(["same-author"]);
},
);

test("retries failed permission lookups for later PRs by the same author", async () => {
const { io, closed } = makeIo(
[1, 2].map((number) => ({
number,
authorLogin: "same-author",
authorAssociation: "NONE",
isBot: false,
})),
{},
);
let attempts = 0;
io.fetchPermission = async () => {
if (++attempts === 1) throw new Error("temporary outage");
return "write";
};
await expect(evaluateAllOpenPrs(io, REPO)).rejects.toThrow(/PR #1/);
expect(attempts).toBe(2);
expect(closed).toEqual([]);
});

test("returns an entry per PR and closes none when all conform", async () => {
const { io, closed } = makeIo(
[{ number: 9, authorLogin: "ext", authorAssociation: "NONE", isBot: false }],
Expand Down Expand Up @@ -274,7 +367,7 @@ describe("fetchAuthorPermission", () => {
expect(permission).toBeUndefined();
});

test("throws on other API failures so the run aborts without closing PRs", async () => {
test("throws on other API failures rather than treating the author as external", async () => {
stubFetch(403, { message: "Forbidden" });
await expect(fetchAuthorPermission("t", "supabase", "cli", "ext")).rejects.toThrow(/403/);
});
Expand Down
Loading
Loading