Skip to content
Closed
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
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@
<classifier>tests</classifier>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>docker-commons</artifactId>
<version>1.0</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins.workflow</groupId>
<artifactId>workflow-support</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package org.jenkinsci.plugins.credentialsbinding.impl;

import java.io.IOException;
import java.util.UUID;

import org.jenkinsci.plugins.credentialsbinding.Binding;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials;
import org.kohsuke.stapler.DataBoundConstructor;

import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.TaskListener;
import hudson.model.Run;

import static org.jenkinsci.plugins.credentialsbinding.impl.TempDirUtils.*;

public class DockerServerCredentialsBinding extends Binding<DockerServerCredentials> {

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

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

@Override
public SingleEnvironment bindSingle(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener)
throws IOException, InterruptedException {
DockerServerCredentials credentials = getCredentials(build);
FilePath secrets = secretsDir(workspace);
String dirName = UUID.randomUUID().toString();
final FilePath dir = secrets.child(dirName);
dir.mkdirs();
secrets.chmod(0700);
dir.chmod(0700);

FilePath clientKey = dir.child("key.pem");
clientKey.write(credentials.getClientKey(), null);
clientKey.chmod(0600);

FilePath clientCert = dir.child("cert.pem");
clientCert.write(credentials.getClientCertificate(), null);
clientCert.chmod(0600);

FilePath serverCACert = dir.child("ca.pem");
serverCACert.write(credentials.getServerCaCertificate(), null);
serverCACert.chmod(0600);

return new SingleEnvironment(dir.getRemote(), new UnbinderImpl(dirName));
}

@Extension(optional = true)
public static class DescriptorImpl extends BindingDescriptor<DockerServerCredentials> {

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

@Override
public String getDisplayName() {
return Messages.DockerServerCredentialsBinding_docker_client_certificate();
}

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.slaves.WorkspaceList;
import java.io.IOException;
import java.util.UUID;

Expand All @@ -38,6 +37,8 @@
import org.jenkinsci.plugins.plaincredentials.FileCredentials;
import org.kohsuke.stapler.DataBoundConstructor;

import static org.jenkinsci.plugins.credentialsbinding.impl.TempDirUtils.*;

public class FileBinding extends Binding<FileCredentials> {

@DataBoundConstructor public FileBinding(String variable, String credentialsId) {
Expand Down Expand Up @@ -68,30 +69,6 @@ public class FileBinding extends Binding<FileCredentials> {
return new SingleEnvironment(secret.getRemote(), new UnbinderImpl(dirName));
}

private static class UnbinderImpl implements Unbinder {

private static final long serialVersionUID = 1;

private final String dirName;

UnbinderImpl(String dirName) {
this.dirName = dirName;
}

@Override public void unbind(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
secretsDir(workspace).child(dirName).deleteRecursive();
}

}

private static FilePath secretsDir(FilePath workspace) {
return tempDir(workspace).child("secretFiles");
}

// TODO 1.652 use WorkspaceList.tempDir
private static FilePath tempDir(FilePath ws) {
return ws.sibling(ws.getName() + System.getProperty(WorkspaceList.class.getName(), "@") + "tmp");
}

protected void copy(FilePath secret, FileCredentials credentials) throws IOException, InterruptedException {
secret.copyFrom(credentials.getContent());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package org.jenkinsci.plugins.credentialsbinding.impl;

import java.io.IOException;

import org.jenkinsci.plugins.credentialsbinding.MultiBinding.Unbinder;

import hudson.FilePath;
import hudson.Launcher;
import hudson.model.TaskListener;
import hudson.model.Run;
import hudson.slaves.WorkspaceList;

/*package*/abstract class TempDirUtils {

/* package */static FilePath secretsDir(FilePath workspace) {
return tempDir(workspace).child("secretFiles");
}

// TODO 1.652 use WorkspaceList.tempDir
/* package */static FilePath tempDir(FilePath ws) {
return ws.sibling(ws.getName() + System.getProperty(WorkspaceList.class.getName(), "@") + "tmp");
}

/* package */static class UnbinderImpl implements Unbinder {

private static final long serialVersionUID = 1;

private final String dirName;

UnbinderImpl(String dirName) {
this.dirName = dirName;
}

@Override
public void unbind(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener)
throws IOException, InterruptedException {
secretsDir(workspace).child(dirName).deleteRecursive();
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License

Copyright 2013 jglick.

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.
-->
<?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 default="DOCKER_CERT_PATH"/>
</f:entry>
</j:jelly>
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<div>
Name of an environment variable to be set during the build.<br>
Its value will be the absolute path of the directory where the <code>{ca,cert,key}.pem</code> files will be created.<br>
You probably want to call this variable <code>DOCKER_CERT_PATH</code>, which will be undestood by the docker client binary.<br>
</div>
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ StringBinding.secret_text=Secret text
UsernamePasswordBinding.username_and_password=Username and password (conjoined)
UsernamePasswordMultiBinding.username_and_password=Username and password (separated)
ZipFileBinding.secret_zip_file=Secret ZIP file
DockerServerCredentialsBinding.docker_client_certificate=Docker client certificate
Original file line number Diff line number Diff line change
Expand Up @@ -310,12 +310,12 @@ public void testGlobalBindingWithAuthorization() {
});
}

private static Set<String> grep(File dir, String text) throws IOException {
/* package */static Set<String> grep(File dir, String text) throws IOException {
Set<String> matches = new TreeSet<String>();
grep(dir, text, "", matches);
return matches;
}
private static void grep(File dir, String text, String prefix, Set<String> matches) throws IOException {
/* package */static void grep(File dir, String text, String prefix, Set<String> matches) throws IOException {
File[] kids = dir.listFiles();
if (kids == null) {
return;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
/*
* The MIT License
*
* Copyright 2015 Jesse Glick.
*
* 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.credentialsbinding.impl;

import java.util.Collections;

import org.jenkinsci.plugins.credentialsbinding.MultiBinding;
import org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials;
import org.jenkinsci.plugins.docker.commons.credentials.DockerServerDomainSpecification;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.jenkinsci.plugins.workflow.steps.StepConfigTester;
import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runners.model.Statement;
import org.jvnet.hudson.test.RestartableJenkinsRule;

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 com.cloudbees.plugins.credentials.domains.DomainSpecification;

import hudson.FilePath;

import static org.hamcrest.Matchers.instanceOf;
import static org.jenkinsci.plugins.credentialsbinding.impl.BindingStepTest.grep;
import static org.junit.Assert.*;

public class DockerServerCredentialsBindingTest {

@Rule
public RestartableJenkinsRule story = new RestartableJenkinsRule();

@Test
public void configRoundTrip() throws Exception {
story.addStep(new Statement() {
@SuppressWarnings("rawtypes")
@Override
public void evaluate() throws Throwable {
CredentialsStore store = CredentialsProvider.lookupStores(story.j.getInstance()).iterator().next();
assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class));
Domain domain = new Domain("docker", "A domain for docker credentials",
Collections.<DomainSpecification> singletonList(new DockerServerDomainSpecification()));
DockerServerCredentials c = new DockerServerCredentials(CredentialsScope.GLOBAL,
"docker-client-cert", "desc", "clientKey", "clientCertificate", "serverCaCertificate");
store.addDomain(domain, c);
BindingStep s = new StepConfigTester(story.j)
.configRoundTrip(new BindingStep(Collections.<MultiBinding> singletonList(
new DockerServerCredentialsBinding("DOCKER_CERT_PATH", "docker-client-cert"))));
story.j.assertEqualDataBoundBeans(s.getBindings(), Collections.singletonList(
new DockerServerCredentialsBinding("DOCKER_CERT_PATH", "docker-client-cert")));
}
});
}

@Test
public void basics() throws Exception {
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
DockerServerCredentials c = new DockerServerCredentials(CredentialsScope.GLOBAL,
"docker-client-cert", "desc", "clientKey", "clientCertificate", "serverCaCertificate");
CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c);
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " withCredentials([[$class: 'DockerServerCredentialsBinding',\n"
+ " variable: 'DOCKER_CERT_PATH',\n"
+ " credentialsId: 'docker-client-cert']]) {\n"
+ " semaphore 'basics'\n"
+ "\n"
+ " sh '''\n"
+ " set -e -x\n"
+ " # check permissions on the credentials dir and its parent\n"
+ " [ $(stat -c %a \"$DOCKER_CERT_PATH\") = 700 ]\n"
+ " [ $(stat -c %a \"$DOCKER_CERT_PATH\"/..) = 700 ]\n"
+ "\n"
+ " # check permissions and content of the certificate files\n"
+ " [ $(stat -c %a \"$DOCKER_CERT_PATH/key.pem\") = 600 ]\n"
+ " [ $(stat -c %a \"$DOCKER_CERT_PATH/cert.pem\") = 600 ]\n"
+ " [ $(stat -c %a \"$DOCKER_CERT_PATH/ca.pem\") = 600 ]\n"
+ " [ $(stat -c %s \"$DOCKER_CERT_PATH/key.pem\") = 9 ]\n"
+ " [ $(stat -c %s \"$DOCKER_CERT_PATH/cert.pem\") = 17 ]\n"
+ " [ $(stat -c %s \"$DOCKER_CERT_PATH/ca.pem\") = 19 ]\n"
+ "\n"
+ " # keep location of the certificate dir for the next step\n"
+ " echo \"$DOCKER_CERT_PATH\" > cert-path"
+ " '''\n"
+ " }\n"
+ "\n"
+ " sh '''\n"
+ " set -e +x\n"
+ " # make sure the credentials dir have been deleted\n"
+ " cert_path=$(cat cert-path)\n"
+ " if [ -e \"$cert_path\" ] ; then\n"
+ " echo \"$cert_path still exists!!!\" >&2\n"
+ " exit 1\n"
+ " fi\n"
+ " '''\n"
+ "}", true));
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
SemaphoreStep.waitForStart("basics/1", b);
}
});
story.addStep(new Statement() {
@Override
public void evaluate() throws Throwable {
WorkflowJob p = story.j.jenkins.getItemByFullName("p", WorkflowJob.class);
assertNotNull(p);
WorkflowRun b = p.getBuildByNumber(1);
assertNotNull(b);
SemaphoreStep.success("basics/1", null);
while (b.isBuilding()) { // TODO 1.607+ use waitForCompletion
Thread.sleep(100);
}
story.j.assertBuildStatusSuccess(b);
FilePath certPathFile = story.j.jenkins.getWorkspaceFor(p).child("cert-path");
assertTrue(certPathFile.exists());
String certPath = certPathFile.readToString().trim();
// expected .../workspace/p@tmp/secretFiles/<36-chars-UUID>
assertTrue(certPath.matches(".*/workspace/p@tmp/secretFiles/[-a-f0-9]{36}"));
// this path is a secret, it shouldn't appear in the logs (although it doesn't really matter)
assertEquals(Collections.<String> emptySet(), grep(b.getRootDir(), certPath));
}
});
}

}