Skip to content
Permalink
Browse files

JENKINS-38831 add support for credential tracking in SecretBuildWrapp…

…er and BindingStep
  • Loading branch information...
iwarapter committed Oct 18, 2016
1 parent 686a29f commit f220b8a363f2e951a52002d09af01758a61a1a44
@@ -52,7 +52,7 @@
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>credentials</artifactId>
<version>1.23</version>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.jenkins-ci.plugins</groupId>
@@ -90,6 +90,12 @@
<version>1.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-matchers</artifactId>
<version>2.2.0</version>
<scope>test</scope>
</dependency>
<!-- For some reason this is otherwise missing and causes many verbose errors: -->
<dependency>
<groupId>org.jenkins-ci.modules</groupId>
@@ -62,7 +62,7 @@ protected MultiBinding(String credentialsId) {
}

/** Type token. */
protected abstract Class<C> type();
public abstract Class<C> type();

/** Identifier of the credentials to be bound. */
public final String getCredentialsId() {
@@ -24,6 +24,8 @@

package org.jenkinsci.plugins.credentialsbinding.impl;

import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.IdCredentials;
import com.google.inject.Inject;
import hudson.EnvVars;
import hudson.Extension;
@@ -92,6 +94,8 @@
MultiBinding.MultiEnvironment environment = binding.bind(run, workspace, launcher, listener);
unbinders.add(environment.getUnbinder());
overrides.putAll(environment.getValues());
IdCredentials id = CredentialsProvider.findCredentialById(binding.getCredentialsId(), binding.type(), run);
CredentialsProvider.track(run, id);
}
getContext().newBodyInvoker().
withContext(EnvironmentExpander.merge(getContext().get(EnvironmentExpander.class), new Overrider(overrides))).
@@ -44,7 +44,7 @@
super(variable, credentialsId);
}

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

@@ -24,6 +24,8 @@

package org.jenkinsci.plugins.credentialsbinding.impl;

import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.IdCredentials;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.AbstractBuild;
@@ -57,6 +59,8 @@
final List<MultiBinding.MultiEnvironment> m = new ArrayList<MultiBinding.MultiEnvironment>();
for (MultiBinding binding : bindings) {
m.add(binding.bind(build, build.getWorkspace(), launcher, listener));
IdCredentials id = CredentialsProvider.findCredentialById(binding.getCredentialsId(), binding.type(), build);
CredentialsProvider.track(build, id);
}
return new Environment() {
@Override public void buildEnvVars(Map<String,String> env) {
@@ -42,7 +42,7 @@
super(variable, credentialsId);
}

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

@@ -42,7 +42,7 @@
super(variable, credentialsId);
}

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

@@ -60,7 +60,7 @@ public String getPasswordVariable() {
return passwordVariable;
}

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

@@ -30,6 +30,7 @@
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;

import hudson.model.Fingerprint;
import jenkins.security.QueueItemAuthenticatorConfiguration;

import hudson.FilePath;
@@ -68,6 +69,10 @@
import org.jenkinsci.plugins.workflow.steps.StepConfigTester;
import org.jenkinsci.plugins.workflow.test.steps.SemaphoreStep;

import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.*;
import org.junit.ClassRule;

@@ -309,6 +314,42 @@ public void testGlobalBindingWithAuthorization() {
});
}

@Issue("JENKINS-38831")
@Test
public void testTrackingOfCredential() {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
String credentialsId = "creds";
String secret = "s3cr3t";
StringCredentialsImpl credentials = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret));
Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credentials);

CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), credentials);
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(""
+ "def extract(id) {\n"
+ " def v\n"
+ " withCredentials([[$class: 'StringBinding', credentialsId: id, variable: 'temp']]) {\n"
+ " v = env.temp\n"
+ " }\n"
+ " v\n"
+ "}\n"
+ "node {\n"
+ " echo \"got: ${extract('" + credentialsId + "')}\"\n"
+ "}", true));

assertThat("No fingerprint created until first use", fingerprint, nullValue());

story.j.assertLogContains("got: " + secret, story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get()));

fingerprint = CredentialsProvider.getFingerprintOf(credentials);

assertThat(fingerprint, notNullValue());
assertThat(fingerprint.getJobs(), hasItem(is(p.getFullName())));
}
});
}

private static Set<String> grep(File dir, String text) throws IOException {
Set<String> matches = new TreeSet<String>();
grep(dir, text, "", matches);
@@ -24,31 +24,39 @@

package org.jenkinsci.plugins.credentialsbinding.impl;

import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.CredentialsScope;
import com.cloudbees.plugins.credentials.*;
import com.cloudbees.plugins.credentials.domains.Domain;
import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl;

import hudson.model.FreeStyleBuild;
import hudson.model.Item;
import hudson.model.FreeStyleProject;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import hudson.Util;
import hudson.model.*;
import hudson.remoting.Future;
import hudson.tasks.Shell;

import java.util.Collections;
import java.util.List;

import jenkins.model.Jenkins;
import org.jenkinsci.plugins.credentialsbinding.Binding;
import org.jenkinsci.plugins.credentialsbinding.MultiBinding;
import org.junit.Test;

import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;

import org.junit.Rule;
import org.jvnet.hudson.test.JenkinsRule;
import org.xmlunit.matchers.CompareMatcher;

public class UsernamePasswordBindingTest {

@Rule public JenkinsRule r = new JenkinsRule();
private CredentialsStore store = null;

@Test public void basics() throws Exception {
String username = "bob";
@@ -73,4 +81,82 @@
assertEquals("[AUTH]", b.getSensitiveBuildVariables().toString());
}

@Test
public void theSecretBuildWrapperTracksUsage() throws Exception {
SystemCredentialsProvider.getInstance().setDomainCredentialsMap(
Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList()));
for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) {
store = s;
break;
}
}
assertThat("The system credentials provider is enabled", store, notNullValue());

UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob",
"secret");
store.addCredentials(Domain.global(), credentials);

Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credentials);
assertThat("No fingerprint created until first use", fingerprint, nullValue());

JenkinsRule.WebClient wc = r.createWebClient();
HtmlPage page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id");
assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue());
assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue());
assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue());

FreeStyleProject job = r.createFreeStyleProject();
// add a parameter
job.addProperty(new ParametersDefinitionProperty(
new CredentialsParameterDefinition(
"SECRET",
"The secret",
"secret-id",
Credentials.class.getName(),
false
)));

r.assertBuildStatusSuccess((Future) job.scheduleBuild2(0,
new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))));

fingerprint = CredentialsProvider.getFingerprintOf(credentials);
assertThat("A job that does nothing does not use parameterized credentials", fingerprint, nullValue());

page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id");
assertThat("Have usage tracking reported", page.getElementById("usage"), notNullValue());
assertThat("No fingerprint created until first use", page.getElementById("usage-missing"), notNullValue());
assertThat("No fingerprint created until first use", page.getElementById("usage-present"), nullValue());

// check that the wrapper works as expected
job.getBuildWrappersList().add(new SecretBuildWrapper(Collections.<Binding<?>>singletonList(new UsernamePasswordBinding("AUTH", credentials.getId()))));

r.assertBuildStatusSuccess((Future) job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))));

fingerprint = CredentialsProvider.getFingerprintOf(credentials);
assertThat(fingerprint, notNullValue());
assertThat(fingerprint.getJobs(), hasItem(is(job.getFullName())));
Fingerprint.RangeSet rangeSet = fingerprint.getRangeSet(job);
assertThat(rangeSet, notNullValue());
assertThat(rangeSet.includes(job.getLastBuild().getNumber()), is(true));

page = wc.goTo("credentials/store/system/domain/_/credentials/secret-id");
assertThat(page.getElementById("usage-missing"), nullValue());
assertThat(page.getElementById("usage-present"), notNullValue());
assertThat(page.getAnchorByText(job.getFullDisplayName()), notNullValue());

// check the API
WebResponse response = wc.goTo(
"credentials/store/system/domain/_/credentials/secret-id/api/xml?depth=1&xpath=*/fingerprint/usage",
"application/xml").getWebResponse();
assertThat(response.getContentAsString(), CompareMatcher.isSimilarTo("<usage>"
+ "<name>"+ Util.xmlEscape(job.getFullName())+"</name>"
+ "<ranges>"
+ "<range>"
+ "<end>"+(job.getLastBuild().getNumber()+1)+"</end>"
+ "<start>" + job.getLastBuild().getNumber()+"</start>"
+ "</range>"
+ "</ranges>"
+ "</usage>").ignoreWhitespace().ignoreComments());
}
}

0 comments on commit f220b8a

Please sign in to comment.
You can’t perform that action at this time.