Skip to content
Open
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
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,10 @@
<groupId>io.jenkins.plugins</groupId>
<artifactId>okhttp-api</artifactId>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>branch-api</artifactId>

Copy link
Copy Markdown
Member

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

Copy link
Copy Markdown
Member

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.

Copy link
Copy Markdown
Member Author

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.

Copy link
Copy Markdown
Member Author

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)

</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>credentials</artifactId>
Expand Down
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)) {

Check warning on line 71 in src/main/java/org/jenkinsci/plugins/github_branch_source/ExternalApprovalHelper.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 71 is only partially covered, one branch is missing
return null;

Check warning on line 72 in src/main/java/org/jenkinsci/plugins/github_branch_source/ExternalApprovalHelper.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 72 is not covered by tests
}
Branch branch = factory.getBranch(job);
SCMHead head = branch.getHead();
if (!(head instanceof PullRequestSCMHead)) {

Check warning on line 76 in src/main/java/org/jenkinsci/plugins/github_branch_source/ExternalApprovalHelper.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 76 is only partially covered, one branch is missing
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;
}

Check warning on line 235 in src/main/java/org/jenkinsci/plugins/github_branch_source/ExternalApprovalHelper.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 79-235 are not covered by tests
}
Loading