-
Notifications
You must be signed in to change notification settings - Fork 397
[WIP] Add an external contributor approval mechanism of Pull Requests #1556
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
olamy
wants to merge
5
commits into
jenkinsci:master
Choose a base branch
from
olamy:pr-approval
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ba4abcb
Add an external contributor approval mechanism
olamy 1709f11
Fix approval bypass and auto-approval, add permission check
olamy 580c2ab
Merge remote-tracking branch 'origin/master' into pr-approval
olamy 4a55d54
Address review feedback
olamy 58ac01a
Leave the SECURITY-3808 test comments alone
olamy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
236 changes: 236 additions & 0 deletions
236
src/main/java/org/jenkinsci/plugins/github_branch_source/ExternalApprovalHelper.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,236 @@ | ||
| /* | ||
| * The MIT License | ||
| * | ||
| * Copyright 2026 Olivier Lamy | ||
| * | ||
| * Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| * of this software and associated documentation files (the "Software"), to deal | ||
| * in the Software without restriction, including without limitation the rights | ||
| * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| * copies of the Software, and to permit persons to whom the Software is | ||
| * furnished to do so, subject to the following conditions: | ||
| * | ||
| * The above copyright notice and this permission notice shall be included in | ||
| * all copies or substantial portions of the Software. | ||
| * | ||
| * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| * THE SOFTWARE. | ||
| */ | ||
| package org.jenkinsci.plugins.github_branch_source; | ||
|
|
||
| import com.cloudbees.plugins.credentials.common.StandardCredentials; | ||
| import edu.umd.cs.findbugs.annotations.CheckForNull; | ||
| import hudson.model.Item; | ||
| import hudson.model.Job; | ||
| import java.io.IOException; | ||
| import java.util.List; | ||
| import java.util.logging.Level; | ||
| import java.util.logging.Logger; | ||
| import jenkins.branch.Branch; | ||
| import jenkins.branch.BranchProjectFactory; | ||
| import jenkins.branch.BranchSource; | ||
| import jenkins.branch.MultiBranchProject; | ||
| import jenkins.scm.api.SCMHead; | ||
| import jenkins.scm.api.SCMHeadOrigin; | ||
| import jenkins.scm.api.SCMRevision; | ||
| import jenkins.scm.api.SCMSource; | ||
| import jenkins.scm.api.trait.SCMSourceTrait; | ||
| import org.kohsuke.github.GHLabel; | ||
| import org.kohsuke.github.GHPullRequest; | ||
| import org.kohsuke.github.GHRepository; | ||
| import org.kohsuke.github.GitHub; | ||
|
|
||
| /** | ||
| * Works out whether a branch job needs external approval before it can build, and whether its pull | ||
| * request can be approved without asking anyone. | ||
| */ | ||
| final class ExternalApprovalHelper { | ||
|
|
||
| private static final Logger LOGGER = Logger.getLogger(ExternalApprovalHelper.class.getName()); | ||
|
|
||
| private ExternalApprovalHelper() {} | ||
|
|
||
| /** | ||
| * Returns the approval details for a fork pull request job in a multibranch project using the | ||
| * {@link ForkPullRequestDiscoveryTrait.TrustExternalApproval} policy, or {@code null} when | ||
| * external approval doesn't apply to this job. | ||
| */ | ||
| @CheckForNull | ||
| @SuppressWarnings({"rawtypes", "unchecked"}) | ||
| static ExternalApprovalInfo getApprovalInfo(Job<?, ?> job) { | ||
| if (!(job.getParent() instanceof MultiBranchProject)) { | ||
| return null; | ||
| } | ||
| MultiBranchProject mp = (MultiBranchProject) job.getParent(); | ||
| BranchProjectFactory factory = mp.getProjectFactory(); | ||
| if (!factory.isProject(job)) { | ||
| return null; | ||
| } | ||
| Branch branch = factory.getBranch(job); | ||
| SCMHead head = branch.getHead(); | ||
| if (!(head instanceof PullRequestSCMHead)) { | ||
| return null; | ||
| } | ||
| PullRequestSCMHead prHead = (PullRequestSCMHead) head; | ||
| if (prHead.getOrigin().equals(SCMHeadOrigin.DEFAULT)) { | ||
| return null; | ||
| } | ||
| GitHubSCMSource source = findSourceWithExternalApproval(mp); | ||
| if (source == null) { | ||
| return null; | ||
| } | ||
| ForkPullRequestDiscoveryTrait.TrustExternalApproval trustPolicy = getTrustPolicy(source); | ||
| if (trustPolicy == null) { | ||
| return null; | ||
| } | ||
| String currentPullHash = getCurrentPullHash(factory, job); | ||
| return new ExternalApprovalInfo( | ||
| prHead.getNumber(), | ||
| prHead.getSourceOwner(), | ||
| currentPullHash, | ||
| trustPolicy.isRequireApprovalForNewCommits(), | ||
| trustPolicy.getAutoApprovalUsers(), | ||
| trustPolicy.getAutoApprovalLabels(), | ||
| source, | ||
| mp); | ||
| } | ||
|
|
||
| /** Finds the project's {@link GitHubSCMSource} that uses the external-approval policy, if any. */ | ||
| @CheckForNull | ||
| @SuppressWarnings("rawtypes") | ||
| private static GitHubSCMSource findSourceWithExternalApproval(MultiBranchProject mp) { | ||
| for (Object src : mp.getSources()) { | ||
| if (src instanceof BranchSource) { | ||
| SCMSource source = ((BranchSource) src).getSource(); | ||
| if (source instanceof GitHubSCMSource && getTrustPolicy((GitHubSCMSource) source) != null) { | ||
| return (GitHubSCMSource) source; | ||
| } | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| @CheckForNull | ||
| private static ForkPullRequestDiscoveryTrait.TrustExternalApproval getTrustPolicy(GitHubSCMSource source) { | ||
| for (SCMSourceTrait trait : source.getTraits()) { | ||
| if (trait instanceof ForkPullRequestDiscoveryTrait) { | ||
| Object trust = ((ForkPullRequestDiscoveryTrait) trait).getTrust(); | ||
| if (trust instanceof ForkPullRequestDiscoveryTrait.TrustExternalApproval) { | ||
| return (ForkPullRequestDiscoveryTrait.TrustExternalApproval) trust; | ||
| } | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| /** | ||
| * Returns the pull request head as branch indexing last saw it. It has to be the last seen | ||
| * revision and not the last built one: branch-api records the built revision only after a build | ||
| * has been scheduled, so that one still holds the previous commit while we decide about the new | ||
| * one. | ||
| */ | ||
| @CheckForNull | ||
| @SuppressWarnings({"rawtypes", "unchecked"}) | ||
| private static String getCurrentPullHash(BranchProjectFactory factory, Job<?, ?> job) { | ||
| String pullHash = pullHashOf(factory.getLastSeenRevision(job)); | ||
| return pullHash != null ? pullHash : pullHashOf(factory.getRevision(job)); | ||
| } | ||
|
|
||
| @CheckForNull | ||
| private static String pullHashOf(@CheckForNull SCMRevision revision) { | ||
| return revision instanceof PullRequestSCMRevision ? ((PullRequestSCMRevision) revision).getPullHash() : null; | ||
| } | ||
|
|
||
| /** Returns {@code true} when the PR author is on the auto-approval list. Just a list lookup. */ | ||
| static boolean isAutoApprovedUser(ExternalApprovalInfo info) { | ||
| if (info.autoApprovalUsers == null || info.prAuthor == null) { | ||
| return false; | ||
| } | ||
| for (String user : info.autoApprovalUsers) { | ||
| // GitHub logins are case-insensitive. | ||
| if (user.equalsIgnoreCase(info.prAuthor)) { | ||
| return true; | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| /** | ||
| * Decides whether a pull request can be approved without asking anyone, because its author is on | ||
| * the user list or it carries one of the auto-approval labels. The label check costs a GitHub | ||
| * call, so only ask when first recording the approval or when the commit has moved on. | ||
| */ | ||
| static boolean evaluateAutoApproval(ExternalApprovalInfo info) { | ||
| if (isAutoApprovedUser(info)) { | ||
| return true; | ||
| } | ||
| if (info.autoApprovalLabels == null || info.autoApprovalLabels.isEmpty() || info.source == null) { | ||
| return false; | ||
| } | ||
| GitHubSCMSource src = info.source; | ||
| StandardCredentials credentials = Connector.lookupScanCredentials( | ||
| info.context, src.getApiUri(), src.getCredentialsId(), src.getRepoOwner()); | ||
| GitHub github = null; | ||
| try { | ||
| github = Connector.connect(src.getApiUri(), credentials); | ||
| GHRepository repo = github.getRepository(src.getRepoOwner() + "/" + src.getRepository()); | ||
| GHPullRequest pr = repo.getPullRequest(info.prNumber); | ||
| for (GHLabel label : pr.getLabels()) { | ||
| if (info.autoApprovalLabels.contains(label.getName())) { | ||
| return true; | ||
| } | ||
| } | ||
| } catch (IOException e) { | ||
| LOGGER.log(Level.WARNING, "Failed to check auto-approval labels for PR #" + info.prNumber, e); | ||
| } finally { | ||
| if (github != null) { | ||
| Connector.release(github); | ||
| } | ||
| } | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| /** A snapshot of a fork pull request, with everything needed to decide its approval. */ | ||
| class ExternalApprovalInfo { | ||
| final int prNumber; | ||
| final String prAuthor; | ||
| final String currentPullHash; | ||
| final boolean requireApprovalForNewCommits; | ||
|
|
||
| @CheckForNull | ||
| final List<String> autoApprovalUsers; | ||
|
|
||
| @CheckForNull | ||
| final List<String> autoApprovalLabels; | ||
|
|
||
| @CheckForNull | ||
| final GitHubSCMSource source; | ||
|
|
||
| @CheckForNull | ||
| final Item context; | ||
|
|
||
| ExternalApprovalInfo( | ||
| int prNumber, | ||
| String prAuthor, | ||
| String currentPullHash, | ||
| boolean requireApprovalForNewCommits, | ||
| @CheckForNull List<String> autoApprovalUsers, | ||
| @CheckForNull List<String> autoApprovalLabels, | ||
| @CheckForNull GitHubSCMSource source, | ||
| @CheckForNull Item context) { | ||
| this.prNumber = prNumber; | ||
| this.prAuthor = prAuthor; | ||
| this.currentPullHash = currentPullHash; | ||
| this.requireApprovalForNewCommits = requireApprovalForNewCommits; | ||
| this.autoApprovalUsers = autoApprovalUsers; | ||
| this.autoApprovalLabels = autoApprovalLabels; | ||
| this.source = source; | ||
| this.context = context; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Architecturally this is wrong—branch sources do not depend on project specifics.
Now I recall that I actually started work on this problem a while back but review stalled in discussions about security implications: jenkinsci/scm-api-plugin#180
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correction: a related problem, about PRs specifically changing Pipeline script, which is riskier. Perhaps there should be a unified DX allowing maintainers to permit or deny builds from forks based on whether or not Pipeline script changed; approval of a given commit vs. any commit to that PR; whitelisting of a given author. In the case of GH specifically, there are as I recall several modes available to GHA though I doubt a Jenkins controller could inspect those settings without elevated permissions.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, this layering approach is perfectly right.
BUT I would prefer the feature proposed here (it's actually not a feature, but get back on track with what GHA has been proposing for years) to not depend on another change that has been stalled for 3 years.
The idea here is to prevent the execution of any code without approval. (Jenkinsfile or not)
But rather than focusing on the "ideal" technical approach, we could focus on delivering features users have been expecting for years now.
Anyway, I will try a separate plugin approach because my goal here is to have happy users enjoying some interesting features.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
But frankly, such a feature should be a natural part of this plugin; users should not have to install anything else.
That's definitely not a user-friendly approach (IMO)