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
54 changes: 53 additions & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,63 @@

### Configure the item

1. When configuring the new item, select "Repository Sources"
1. When configuring the new item, select "Repository Sources"

ℹ️ **This is only necessary when using `branch-api` plugin version >=2.7.0**

2. In the "Gitea organzations" section, add a new credential of type "Gitea personal access token".
3. Add the access token created before for the jenkins user in Gitea. Ignore the error about the token not having the correct length.
4. In the "Owner" field, add the name of the organization in Gitea you want to build projects for (**not** the full name).
5. Fill the rest of the form as required. Click "Save". The following scan should list the repositories that the jenkins user can see in the organization selected.

## Using a Gitea personal access token in a Jenkins Pipeline

["Using credentials"](https://www.jenkins.io/doc/book/using/using-credentials/) includes a Jenkins Pipeline credentials tutorial.
Additional credentials examples are available in the ["Injecting secrets into builds"](https://docs.cloudbees.com/docs/cloudbees-ci/latest/secure/injecting-secrets) page from CloudBees.

The Gitea plugin includes support for Gitea personal access tokens as Jenkins [credentials](https://www.jenkins.io/doc/book/using/using-credentials/).
Personal access tokens are used to authenticate Gitea repository and API access without using a Gitea username and password.
Gitea personal access tokens are defined in Gitea from the "Applications" page of each Gitea user's "Settings" (/user/settings/applications).
Personal access token permissions can be defined to grant access to a subset of the resources of the Gitea server.

Once a Gitea personal access token has been created in Gitea and added to Jenkins as a credential, it can be referenced from a Pipeline job using the `withCredentials` Pipeline step.
Use the [Pipeline syntax snippet generator](https://www.jenkins.io/pipeline/getting-started-pipelines/#using-snippet-generator) to create an example of the `withCredentials` step.

A typical example of a Gitea personal access token in a Jenkins declarative Pipeline would look like:

```groovy
pipeline {
agent any
stages {
stage('Checkout') {
steps {
withCredentials([giteaPersonalAccessToken(credentialsId: 'my-gitea-token',
variable: 'MY_TOKEN')]) {
sh 'git clone https://[email protected]/exampleUser/private-repo.git'
}
}
}
}
}
```

A typical example of a Gitea personal access token in a Jenkins scripted Pipeline would look like:

```groovy
node {
stage('Checkout') {
withCredentials([giteaPersonalAccessToken(credentialsId: 'my-gitea-token',
variable: 'MY_TOKEN')]) {
sh 'git clone https://[email protected]/exampleUser/private-repo.git'
}
}
}
```

### Note

You should use a single quote (`'`) instead of a double quote (`"`) whenever you can.
This is particularly important in Pipelines where a statement may be interpreted by both the Pipeline engine and an external interpreter, such as a Unix shell (`sh`) or Windows Command (`bat`) or Powershell (`ps`).
This reduces complications with password masking and command processing.
The `sh` step in the above examples properly demonstrates this.
It references an environment variable, so the single-quoted string passes its value unprocessed to the `sh` step, and the shell interprets `$MY_TOKEN`.
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@
<artifactId>workflow-multibranch</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-basic-steps</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<repositories>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.jenkinsci.plugin.gitea.credentials;

import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import java.io.IOException;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.credentialsbinding.Binding;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.kohsuke.stapler.DataBoundConstructor;

public class PersonalAccessTokenBinding extends Binding<PersonalAccessToken> {

@DataBoundConstructor
public PersonalAccessTokenBinding(String credentialsId, String variable) {
super(variable, credentialsId);
}

@Override
protected Class<PersonalAccessToken> type() {
return PersonalAccessToken.class;
}

@Override
public Binding.SingleEnvironment bindSingle(@NonNull Run<?,?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener)
throws IOException,InterruptedException {
PersonalAccessToken credential = getCredentials(build);
return new SingleEnvironment(credential.getToken().getPlainText());
}

@Symbol("giteaPersonalAccessToken") // Symbol annotation for use in Jenkins UI
@Extension
public static class DescriptorImpl extends BindingDescriptor<PersonalAccessTokenImpl> {

@Override
protected Class<PersonalAccessTokenImpl> type() {
return PersonalAccessTokenImpl.class;

Check warning on line 44 in src/main/java/org/jenkinsci/plugin/gitea/credentials/PersonalAccessTokenBinding.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 44 is not covered by tests
}

@NonNull
@Override
public String getDisplayName() {
return Messages.PersonalAccessTokenImpl_displayName(); // Localized display name
}

@Override
public boolean requiresWorkspace() {
return false; // This binding does not require a workspace
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>

<?jelly escape-by-default='true'?>
<j:jelly xmlns:j="jelly:core" xmlns:f="/lib/form" xmlns:st="jelly:stapler" xmlns:c="/lib/credentials">
<f:entry title="${%Variable}" field="variable">
<f:textbox/>
</f:entry>
<f:entry title="${%Credentials}" field="credentialsId">
<c:select expressionAllowed="${expressionAllowed}"/>
</f:entry>
</j:jelly>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# The MIT License
#
# Copyright (c) 2016-, Seiji Sogabe
#
# 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.

Credentials=\u8a8d\u8a3c\u60c5\u5831
Variable=\u5909\u6570
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package org.jenkinsci.plugin.gitea.credentials;

import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.CredentialsStore;
import com.cloudbees.plugins.credentials.SystemCredentialsProvider;
import com.cloudbees.plugins.credentials.domains.Domain;
import hudson.model.Run;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.junit.jupiter.WithJenkins;

@WithJenkins
class PersonalAccessTokenBindingTest {

private static final String API_TOKEN = "secret";
private static final String API_TOKEN_ID = "personalAccessTokenId";

private JenkinsRule jenkins;

@BeforeEach
void setUp(JenkinsRule rule) throws Exception {
jenkins = rule;
for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(jenkins.jenkins)) {
if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
List<Domain> domains = credentialsStore.getDomains();
credentialsStore.addCredentials(
domains.get(0),
new PersonalAccessTokenImpl(
CredentialsScope.GLOBAL,
API_TOKEN_ID,
"Gitea Personal Access Token",
API_TOKEN));
}
}
}

@Test
void withCredentials_success() throws Exception {
WorkflowJob project = jenkins.createProject(WorkflowJob.class);
String pipelineText = IOUtils.toString(
getClass().getResourceAsStream("pipeline/withCredentials-pipeline.groovy"), StandardCharsets.UTF_8);
project.setDefinition(new CpsFlowDefinition(pipelineText, false));
Run<?, ?> build = jenkins.buildAndAssertSuccess(project);
// Pipeline script outputs a substring of credential so that it will not be masked
jenkins.assertLogContains("Token1 is ecret", build);
jenkins.assertLogContains("Token2 is ecret", build);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
node {
withCredentials([[
$class: 'PersonalAccessTokenBinding',
credentialsId: 'personalAccessTokenId',
variable: 'API_TOKEN1'
]]) {
echo "Token1 is ${API_TOKEN1.substring(1)}"
}
withCredentials([giteaPersonalAccessToken(
credentialsId: 'personalAccessTokenId',
variable: 'API_TOKEN2'
)]) {
echo "Token2 is ${API_TOKEN2.substring(1)}"
}
}
Loading