Skip to content

Commit

Permalink
Merge pull request #27 from iwarapter/master
Browse files Browse the repository at this point in the history
[JENKINS-38831] Add support for credential tracking in SecretBuildWrapper and BindingStep
  • Loading branch information
jglick committed Nov 1, 2016
2 parents d4b7fc6 + 2a07412 commit 737a0f7
Show file tree
Hide file tree
Showing 4 changed files with 146 additions and 6 deletions.
8 changes: 7 additions & 1 deletion pom.xml
Expand Up @@ -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>
Expand Down Expand Up @@ -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>
Expand Down
Expand Up @@ -24,7 +24,6 @@

package org.jenkinsci.plugins.credentialsbinding;

import com.cloudbees.plugins.credentials.CredentialsDescriptor;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.IdCredentials;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
Expand Down Expand Up @@ -131,8 +130,10 @@ protected static final class NullUnbinder implements Unbinder {
if (cred==null)
throw new CredentialNotFoundException(credentialsId);

if (type().isInstance(cred))
if (type().isInstance(cred)) {
CredentialsProvider.track(build, cred);
return type().cast(cred);
}


Descriptor expected = Jenkins.getActiveInstance().getDescriptor(type());
Expand Down
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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);
Expand Down
Expand Up @@ -24,31 +24,45 @@

package org.jenkinsci.plugins.credentialsbinding.impl;

import com.cloudbees.plugins.credentials.Credentials;
import com.cloudbees.plugins.credentials.CredentialsParameterDefinition;
import com.cloudbees.plugins.credentials.CredentialsParameterValue;
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.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";
Expand All @@ -73,4 +87,82 @@ public class UsernamePasswordBindingTest {
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 737a0f7

Please sign in to comment.