Skip to content
Merged
Changes from 1 commit
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
243 changes: 243 additions & 0 deletions .github/workflows/close-unvetted-pr.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
name: Close Unvetted Non-Maintainer PRs

on:
pull_request_target:
types: [opened]

jobs:
validate-non-maintainer-pr:
name: Validate Non-Maintainer PR
runs-on: ubuntu-24.04
permissions:
pull-requests: write
contents: write
steps:
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v2
with:
app-id: ${{ vars.SDK_MAINTAINER_BOT_APP_ID }}
private-key: ${{ secrets.SDK_MAINTAINER_BOT_PRIVATE_KEY }}

- name: Validate PR
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
with:
github-token: ${{ steps.app-token.outputs.token }}
script: |
const pullRequest = context.payload.pull_request;
const repo = context.repo;
const prAuthor = pullRequest.user.login;
const contributingUrl = `https://github.com/${repo.owner}/${repo.repo}/blob/master/CONTRIBUTING.md`;

// --- Helper: check if a user has write+ permission on a repo ---
async function hasWriteAccess(owner, repoName, username) {
try {
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({
owner,
repo: repoName,
username,
});
return ['admin', 'maintain', 'write'].includes(data.permission);
} catch {
return false;
}
}

// --- Step 1: Check if PR author is a maintainer ---
const isMaintainer = await hasWriteAccess(repo.owner, repo.repo, prAuthor);
if (isMaintainer) {
core.info(`PR author ${prAuthor} has write+ access. Skipping.`);
return;
}
core.info(`PR author ${prAuthor} is not a maintainer.`);

// --- Step 2: Parse issue references from PR body ---
const body = pullRequest.body || '';

// Match all issue reference formats:
// #123, Fixes #123, getsentry/repo#123, Fixes getsentry/repo#123
// https://github.com/getsentry/repo/issues/123
const issueRefs = [];
const seen = new Set();

// Pattern 1: Full GitHub URLs
const urlPattern = /https?:\/\/github\.com\/(getsentry)\/([\w.-]+)\/issues\/(\d+)/gi;
for (const match of body.matchAll(urlPattern)) {
const key = `${match[1]}/${match[2]}#${match[3]}`;
if (!seen.has(key)) {
seen.add(key);
issueRefs.push({ owner: match[1], repo: match[2], number: parseInt(match[3]) });
}
}

// Pattern 2: Cross-repo references (getsentry/repo#123)
const crossRepoPattern = /(?:(?:fix|fixes|fixed|close|closes|closed|resolve|resolves|resolved)\s+)?(getsentry)\/([\w.-]+)#(\d+)/gi;
for (const match of body.matchAll(crossRepoPattern)) {
const key = `${match[1]}/${match[2]}#${match[3]}`;
if (!seen.has(key)) {
seen.add(key);
issueRefs.push({ owner: match[1], repo: match[2], number: parseInt(match[3]) });
}
}

// Pattern 3: Same-repo references (#123)
// Negative lookbehind to avoid matching cross-repo refs or URLs already captured
const sameRepoPattern = /(?:(?:fix|fixes|fixed|close|closes|closed|resolve|resolves|resolved)\s+)?(?<![/\w])#(\d+)/gi;
for (const match of body.matchAll(sameRepoPattern)) {
const key = `${repo.owner}/${repo.repo}#${match[1]}`;
if (!seen.has(key)) {
seen.add(key);
issueRefs.push({ owner: repo.owner, repo: repo.repo, number: parseInt(match[1]) });
}
}

core.info(`Found ${issueRefs.length} issue reference(s): ${[...seen].join(', ')}`);

// --- Helper: close PR with comment and label ---
async function closePR(message) {
await github.rest.issues.addLabels({
...repo,
issue_number: pullRequest.number,
labels: ['violating-contribution-guidelines'],
});

await github.rest.issues.createComment({
...repo,
issue_number: pullRequest.number,
body: message,
});

await github.rest.pulls.update({
...repo,
pull_number: pullRequest.number,
state: 'closed',
});
}

// --- Step 3: No issue references ---
if (issueRefs.length === 0) {
core.info('No issue references found. Closing PR.');
await closePR([
'This PR has been automatically closed. All non-maintainer contributions must reference an existing GitHub issue.',
'',
'**Next steps:**',
'1. Find or open an issue describing the problem or feature',
'2. Discuss the approach with a maintainer in the issue',
'3. Once a maintainer has acknowledged your proposed approach, open a new PR referencing the issue',
'',
`Please review our [contributing guidelines](${contributingUrl}) for more details.`,
].join('\n'));
return;
}

// --- Step 4: Validate each referenced issue ---
// A PR is valid if ANY referenced issue passes all checks.
let hasAssigneeConflict = false;
let hasNoDiscussion = false;

for (const ref of issueRefs) {
core.info(`Checking issue ${ref.owner}/${ref.repo}#${ref.number}...`);

let issue;
try {
const { data } = await github.rest.issues.get({
owner: ref.owner,
repo: ref.repo,
issue_number: ref.number,
});
issue = data;
} catch (e) {
core.warning(`Could not fetch issue ${ref.owner}/${ref.repo}#${ref.number}: ${e.message}`);
continue;
}

// Check assignee: if assigned to someone other than PR author, flag it
if (issue.assignees && issue.assignees.length > 0) {
const assignedToAuthor = issue.assignees.some(a => a.login === prAuthor);
if (!assignedToAuthor) {
core.info(`Issue ${ref.owner}/${ref.repo}#${ref.number} is assigned to someone else.`);
hasAssigneeConflict = true;
continue;
}
}

// Check discussion: both PR author and a maintainer must have commented
const comments = await github.paginate(github.rest.issues.listComments, {
owner: ref.owner,
repo: ref.repo,
issue_number: ref.number,
per_page: 100,
});

Check warning on line 170 in .github/workflows/close-unvetted-pr.yml

View check run for this annotation

@sentry/warden / warden: code-review

N+1 API calls when checking maintainer participation

The loop at lines 188-195 makes a separate `hasWriteAccess` API call for each unique commenter/issue author to check if they have write access. For issues with many commenters, this results in O(n) API calls which could hit rate limits or cause slow execution. Consider batching the permission checks or caching results across issues.
Comment thread
sentry-warden[bot] marked this conversation as resolved.

// Also consider the issue author as a participant (opening the issue is a form of discussion)
const prAuthorParticipated =

Check warning on line 173 in .github/workflows/close-unvetted-pr.yml

View check run for this annotation

@sentry/warden / warden: code-review

[H7W-2MH] Potential runtime error when accessing deleted user's login (additional location)

The code accesses `issue.user.login` and `comment.user.login` without null checks. GitHub's API returns `null` for `user` when the account has been deleted or suspended. If a PR references an issue created by a deleted user, or if a comment was made by a deleted user, this will cause a runtime error and the workflow will fail.
issue.user.login === prAuthor ||
comments.some(c => c.user.login === prAuthor);

Check warning on line 175 in .github/workflows/close-unvetted-pr.yml

View check run for this annotation

@sentry/warden / warden: code-review

Potential runtime error when accessing deleted user's login

The code accesses `issue.user.login` and `comment.user.login` without null checks. GitHub's API returns `null` for `user` when the account has been deleted or suspended. If a PR references an issue created by a deleted user, or if a comment was made by a deleted user, this will cause a runtime error and the workflow will fail.

Check warning on line 175 in .github/workflows/close-unvetted-pr.yml

View check run for this annotation

@sentry/warden / warden: find-bugs

Null reference exception when issue or comment author is a deleted (ghost) user

The code accesses `issue.user.login`, `comment.user.login`, and `c.user.login` without null checks. On GitHub, when a user account is deleted, the `user` property becomes `null` (the account shows as "ghost"). If a referenced issue was created by a deleted user or contains comments from deleted users, the workflow will crash with a TypeError, preventing the PR validation from completing.
Comment thread
sentry-warden[bot] marked this conversation as resolved.
Outdated

let maintainerParticipated = false;
if (prAuthorParticipated) {
// Check each commenter (and issue author) for write+ access on the issue's repo
const usersToCheck = new Set();
usersToCheck.add(issue.user.login);
for (const comment of comments) {
if (comment.user.login !== prAuthor) {
usersToCheck.add(comment.user.login);
}
}

for (const user of usersToCheck) {
if (user === prAuthor) continue;
if (await hasWriteAccess(ref.owner, ref.repo, user)) {
maintainerParticipated = true;
core.info(`Maintainer ${user} participated in ${ref.owner}/${ref.repo}#${ref.number}.`);
break;
}
}
}

if (prAuthorParticipated && maintainerParticipated) {
core.info(`Issue ${ref.owner}/${ref.repo}#${ref.number} has valid discussion. PR is allowed.`);
return; // PR is valid — at least one issue passes all checks
}

core.info(`Issue ${ref.owner}/${ref.repo}#${ref.number} lacks discussion between author and maintainer.`);
hasNoDiscussion = true;
}

// --- Step 5: No valid issue found — close with the most relevant reason ---
if (hasAssigneeConflict) {
core.info('Closing PR: referenced issue is assigned to someone else.');
await closePR([
'This PR has been automatically closed. The referenced issue is already assigned to someone else.',
'',
'If you believe this assignment is outdated, please comment on the issue to discuss before opening a new PR.',
'',
`Please review our [contributing guidelines](${contributingUrl}) for more details.`,
].join('\n'));
return;
}

if (hasNoDiscussion) {
core.info('Closing PR: no discussion between PR author and a maintainer in the referenced issue.');
await closePR([
'This PR has been automatically closed. The referenced issue does not show a discussion between you and a maintainer.',
'',
'To avoid wasted effort on both sides, please discuss your proposed approach in the issue first and wait for a maintainer to respond before opening a PR.',
'',
`Please review our [contributing guidelines](${contributingUrl}) for more details.`,
].join('\n'));
return;
}

// If we get here, all issue refs were unfetchable
core.info('Could not validate any referenced issues. Closing PR.');
await closePR([
'This PR has been automatically closed. The referenced issue(s) could not be found.',
'',
'**Next steps:**',
'1. Ensure the issue exists and is in a `getsentry` repository',
'2. Discuss the approach with a maintainer in the issue',
'3. Once a maintainer has acknowledged your proposed approach, open a new PR referencing the issue',
'',
`Please review our [contributing guidelines](${contributingUrl}) for more details.`,
].join('\n'));
Loading