下面列出了hudson.model.ModelObject#com.cloudbees.plugins.credentials.domains.Domain 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Saves given credentials in jenkins for domain extracted from server url Adds them to domain
* extracted from server url (will be generated if no any exists before). Domain will have
* domain requirements consists of scheme and host from serverUrl arg
*
* @param serverUrl to extract (and create if no any) domain
* @param credentials to save credentials
*/
private void saveCredentials(String serverUrl, final PersonalAccessToken credentials) {
URI serverUri = URI.create(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL));
List<DomainSpecification> specifications = asList(
new SchemeSpecification(serverUri.getScheme()),
new HostnameSpecification(serverUri.getHost(), null)
);
final Domain domain = new Domain(serverUri.getHost(), "GitLab domain (autogenerated)",
specifications);
try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
new SystemCredentialsProvider.StoreImpl().addDomain(domain, credentials);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Can't add credentials for domain", e);
}
}
@SuppressWarnings({"PMD.AvoidCatchingThrowable", "IllegalCatch"})
protected DumbSlave createDockerContainerAgent(final DockerContainer dockerContainer) {
try {
SystemCredentialsProvider.getInstance().getDomainCredentialsMap().put(Domain.global(),
Collections.singletonList(
new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, "dummyCredentialId",
null, "test", "test")
)
);
DumbSlave agent = new DumbSlave("docker", "/home/test",
new SSHLauncher(dockerContainer.ipBound(22), dockerContainer.port(22), "dummyCredentialId"));
agent.setNodeProperties(Collections.singletonList(new EnvironmentVariablesNodeProperty(
new Entry("JAVA_HOME", "/usr/lib/jvm/java-8-openjdk-amd64/jre"))));
getJenkins().jenkins.addNode(agent);
getJenkins().waitOnline(agent);
return agent;
}
catch (Throwable e) {
throw new AssumptionViolatedException("Failed to create docker container", e);
}
}
@Issue("ISSUE-35")
@Test
public void testOnCredentialsUsage() throws Exception {
UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob","secret");
CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), credentials);
JenkinsRule.WebClient wc = j.createWebClient();
FreeStyleProject job = j.createFreeStyleProject();
job.addProperty(new ParametersDefinitionProperty(
new CredentialsParameterDefinition(
"SECRET",
"The secret",
"secret-id",
Credentials.class.getName(),
false
)));
job.getBuildersList().add(new CaptureEnvironmentBuilder());
job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))).get();
List<LogEvent> events = app.getEvents();
assertThat(events).hasSize(4);
assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).containsSequence("createItem", "buildStart", "useCredentials", "buildFinish");
}
@Initializer(after = InitMilestone.PLUGINS_STARTED)
public static void migrate() throws IOException {
GitLabConnectionConfig descriptor = (GitLabConnectionConfig) Jenkins.get().getDescriptor(GitLabConnectionConfig.class);
if (descriptor == null) return;
for (GitLabConnection connection : descriptor.getConnections()) {
if (connection.apiTokenId == null && connection.apiToken != null) {
for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
List<Domain> domains = credentialsStore.getDomains();
connection.apiTokenId = UUID.randomUUID().toString();
credentialsStore.addCredentials(domains.get(0),
new GitLabApiTokenImpl(CredentialsScope.SYSTEM, connection.apiTokenId, "GitLab API Token", Secret.fromString(connection.apiToken)));
}
}
}
}
descriptor.save();
}
@Test public void basics() throws Exception {
String username = "bob";
String password = "s3cr3t";
UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "sample", username, password);
CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildWrappersList().add(new SecretBuildWrapper(Collections.<Binding<?>>singletonList(new UsernamePasswordBinding("AUTH", c.getId()))));
p.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %AUTH% > auth.txt") : new Shell("echo $AUTH > auth.txt"));
r.configRoundtrip(p);
SecretBuildWrapper wrapper = p.getBuildWrappersList().get(SecretBuildWrapper.class);
assertNotNull(wrapper);
List<? extends MultiBinding<?>> bindings = wrapper.getBindings();
assertEquals(1, bindings.size());
MultiBinding<?> binding = bindings.get(0);
assertEquals(c.getId(), binding.getCredentialsId());
assertEquals(UsernamePasswordBinding.class, binding.getClass());
assertEquals("AUTH", ((UsernamePasswordBinding) binding).getVariable());
FreeStyleBuild b = r.buildAndAssertSuccess(p);
r.assertLogNotContains(password, b);
assertEquals(username + ':' + password, b.getWorkspace().child("auth.txt").readToString().trim());
assertEquals("[AUTH]", b.getSensitiveBuildVariables().toString());
}
/**
* Verifies doFillCredentialsIdItems adds values from the credentials store
* @throws IOException
*/
@Test
public void testDoFillCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);
BuildStatusConfig instance = new BuildStatusConfig();
instance.setCredentialsId(testCredentials);
ListBoxModel model = instance.doFillCredentialsIdItems(testCredentials);
assertEquals(2, model.size());
ListBoxModel.Option item1 = model.get(0);
assertEquals("", item1.value);
assertEquals("- none -", item1.name);
ListBoxModel.Option item2 = model.get(1);
assertEquals(testCredentials, item2.value);
}
/**
* Verifies doFillCredentialsIdItems adds values from the credentials store
* @throws IOException
*/
@Test
public void testDoFillHttpCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);
BuildStatusConfig instance = new BuildStatusConfig();
instance.setCredentialsId(testCredentials);
ListBoxModel model = instance.doFillHttpCredentialsIdItems(testCredentials);
assertEquals(2, model.size());
ListBoxModel.Option item1 = model.get(0);
assertEquals("", item1.value);
assertEquals("- none -", item1.name);
ListBoxModel.Option item2 = model.get(1);
assertEquals(testCredentials, item2.value);
}
private MultiBranchProject mockMbp(String credentialId, User user) {
MultiBranchProject mbp = mock(MultiBranchProject.class);
when(mbp.getName()).thenReturn("pipeline1");
when(mbp.getParent()).thenReturn(j.jenkins);
BitbucketSCMSource scmSource = mock(BitbucketSCMSource.class);
when(scmSource.getServerUrl()).thenReturn(apiUrl);
when(scmSource.getCredentialsId()).thenReturn(credentialId);
when(scmSource.getRepoOwner()).thenReturn("TESTP");
when(scmSource.getRepository()).thenReturn("pipeline-demo-test");
when(mbp.getSCMSources()).thenReturn(Lists.<SCMSource>newArrayList(scmSource));
//mock blueocean credential provider stuff
BlueOceanCredentialsProvider.FolderPropertyImpl folderProperty = mock(BlueOceanCredentialsProvider.FolderPropertyImpl.class);
DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor> properties = new DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor>(mbp);
properties.add(new BlueOceanCredentialsProvider.FolderPropertyImpl(
user.getId(), credentialId,
BlueOceanCredentialsProvider.createDomain(apiUrl)
));
Domain domain = mock(Domain.class);
when(domain.getName()).thenReturn(BitbucketServerScm.DOMAIN_NAME);
when(folderProperty.getDomain()).thenReturn(domain);
when(mbp.getProperties()).thenReturn(properties);
return mbp;
}
private static Domain getDomain(CredentialsStore store) {
Domain domain = store.getDomainByName(BLUEOCEAN_DOMAIN_NAME);
if (domain == null) {
try {
//create new one
boolean result = store.addDomain(new Domain(BLUEOCEAN_DOMAIN_NAME, null, null));
if (!result) {
throw new ServiceException.UnexpectedErrorException(String.format("Failed to create credential domain: %s", BLUEOCEAN_DOMAIN_NAME));
}
domain = store.getDomainByName(BLUEOCEAN_DOMAIN_NAME);
if (domain == null) {
throw new ServiceException.UnexpectedErrorException(String.format("Domain %s created but not found", BLUEOCEAN_DOMAIN_NAME));
}
} catch (IOException ex) {
throw new ServiceException.UnexpectedErrorException("Failed to save the Blue Ocean domain.", ex);
}
}
return domain;
}
@Nonnull
@Override
public List<Credentials> getCredentials(@Nonnull Domain domain) {
final List<Credentials> result = new ArrayList<>(1);
if (domain.equals(FolderPropertyImpl.this.domain)) {
final User proxyUser = User.get(getUser(), false, Collections.emptyMap());
if (proxyUser != null) {
try (ACLContext ignored = ACL.as(proxyUser.impersonate())) {
for (CredentialsStore s : CredentialsProvider.lookupStores(proxyUser)) {
for (Domain d : s.getDomains()) {
if (d.test(PROXY_REQUIREMENT)) {
result.addAll(filter(s.getCredentials(d), withId(getId())));
}
}
}
} catch (UsernameNotFoundException ex) {
logger.warn("BlueOceanCredentialsProvider.StoreImpl#getCredentials(): Username attached to credentials can not be found");
}
}
}
return result;
}
@Test
public void configRoundTripUpdateCertificates() throws Exception {
CredentialsStore store = CredentialsProvider.lookupStores(j.getInstance()).iterator().next();
assertThat(store, instanceOf(SystemCredentialsProvider.StoreImpl.class));
Domain domain = new Domain("docker", "A domain for docker credentials", Collections.singletonList(new DockerServerDomainSpecification()));
DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("key"), "client-cert", "ca-cert");
store.addDomain(domain, credentials);
HtmlForm form = getUpdateForm(domain, credentials);
for (HtmlElement button : form.getElementsByAttribute("input", "class", "secret-update-btn")) {
button.click();
}
form.getTextAreaByName("_.clientKeySecret").setText("new key");
form.getTextAreaByName("_.clientCertificate").setText("new cert");
form.getTextAreaByName("_.serverCaCertificate").setText("new ca cert");
j.submit(form);
DockerServerCredentials expected = new DockerServerCredentials(
credentials.getScope(), credentials.getId(), credentials.getDescription(),
Secret.fromString("new key"), "new cert", "new ca cert");
j.assertEqualDataBoundBeans(expected, findFirstWithId(credentials.getId()));
}
public static void createCredentialsInUserStore(@Nonnull Credentials credential, @Nonnull User user,
@Nonnull String domainName, @Nonnull List<DomainSpecification> domainSpecifications)
throws IOException {
CredentialsStore store= findUserStoreFirstOrNull(user);
if(store == null){
throw new ServiceException.ForbiddenException(String.format("Logged in user: %s doesn't have writable credentials store", user.getId()));
}
Domain domain = findOrCreateDomain(store, domainName, domainSpecifications);
if(!store.addCredentials(domain, credential)){
throw new ServiceException.UnexpectedErrorException("Failed to add credential to domain");
}
}
@BeforeClass
public static void setUpAgent() throws Exception {
s = j.createOnlineSlave();
s.setLabelString("some-label docker");
s.getNodeProperties().add(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("ONAGENT", "true"),
new EnvironmentVariablesNodeProperty.Entry("WHICH_AGENT", "first")));
s.setNumExecutors(2);
s2 = j.createOnlineSlave();
s2.setLabelString("other-docker");
s2.getNodeProperties().add(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("ONAGENT", "true"),
new EnvironmentVariablesNodeProperty.Entry("WHICH_AGENT", "second")));
//setup credentials for docker registry
CredentialsStore store = CredentialsProvider.lookupStores(j.jenkins).iterator().next();
password = System.getProperty("docker.password");
if(password != null) {
UsernamePasswordCredentialsImpl globalCred =
new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
"dockerhub", "real", "jtaboada", password);
store.addCredentials(Domain.global(), globalCred);
}
}
private static @Nonnull Domain findOrCreateDomain(@Nonnull CredentialsStore store,
@Nonnull String domainName,
@Nonnull List<DomainSpecification> domainSpecifications)
throws IOException {
Domain domain = store.getDomainByName(domainName);
if (domain == null) { //create new one
boolean result = store.addDomain(new Domain(domainName,
domainName+" to store credentials by BlueOcean", domainSpecifications)
);
if (!result) {
throw new ServiceException.BadRequestException("Failed to create credential domain: " + domainName);
}
domain = store.getDomainByName(domainName);
if (domain == null) {
throw new ServiceException.UnexpectedErrorException("Domain %s created but not found");
}
}
return domain;
}
@Test
public void basicsPipeline() throws Exception {
// create the Credentials
String alias = "androiddebugkey";
String password = "android";
StandardCertificateCredentials c = new CertificateCredentialsImpl(CredentialsScope.GLOBAL, "my-certificate", alias,
password, new CertificateCredentialsImpl.FileOnMasterKeyStoreSource(certificate.getAbsolutePath()));
CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
// create the Pipeline job
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
String pipelineScript = IOUtils.toString(getTestResourceInputStream("basicsPipeline-Jenkinsfile"));
p.setDefinition(new CpsFlowDefinition(pipelineScript, true));
// copy resources into workspace
FilePath workspace = r.jenkins.getWorkspaceFor(p);
copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.bat", 0755);
copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.bat", 0755);
copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.sh", 0755);
copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.sh", 0755);
// execute the pipeline
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
r.waitForCompletion(b);
r.assertBuildStatusSuccess(b);
}
@Test
public void listAllCredentials() throws IOException {
SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
CredentialsStore systemStore = system.getStore(j.getInstance());
systemStore.addDomain(new Domain("domain1", null, null));
systemStore.addDomain(new Domain("domain2", null, null));
systemStore.addCredentials(systemStore.getDomainByName("domain1"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "admin", "pass$wd"));
systemStore.addCredentials(systemStore.getDomainByName("domain2"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "joe", "pass$wd"));
CredentialsStoreAction credentialsStoreAction = ExtensionList.lookup(ViewCredentialsAction.class).get(0).getStore("system");
CredentialsStoreAction.DomainWrapper domain1 = credentialsStoreAction.getDomain("domain1");
CredentialsStoreAction.DomainWrapper domain2 = credentialsStoreAction.getDomain("domain2");
CredentialsStoreAction.CredentialsWrapper credentials1 = domain1.getCredentialsList().get(0);
CredentialsStoreAction.CredentialsWrapper credentials2 = domain2.getCredentialsList().get(0);
List<Map> creds = get("/search?q=type:credential;organization:jenkins", List.class);
Assert.assertEquals(2, creds.size());
Assert.assertEquals(credentials1.getId(), creds.get(0).get("id"));
Assert.assertEquals(credentials2.getId(), creds.get(1).get("id"));
creds = get("/search?q=type:credential;organization:jenkins;domain:domain2", List.class);
Assert.assertEquals(1, creds.size());
Assert.assertEquals(credentials2.getId(), creds.get(0).get("id"));
}
@Test
public void createSshCredentialUsingDirectSsh() throws IOException {
SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
CredentialsStore systemStore = system.getStore(j.getInstance());
systemStore.addDomain(new Domain("domain1", null, null));
Map<String, Object> resp = post("/organizations/jenkins/credentials/system/domains/domain1/credentials/",
ImmutableMap.of("credentials",
new ImmutableMap.Builder<String,Object>()
.put("privateKeySource", ImmutableMap.of(
"privateKey", "abcabc1212",
"stapler-class", "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey$DirectEntryPrivateKeySource"))
.put("passphrase", "ssh2")
.put("scope", "GLOBAL")
.put("description", "ssh2 desc")
.put("$class", "com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey")
.put("username", "ssh2").build()
)
, 201);
Assert.assertEquals("SSH Username with private key", resp.get("typeName"));
Assert.assertEquals("domain1", resp.get("domain"));
}
@Issue("JENKINS-27486")
@Test public void masking() {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
String credentialsId = "creds";
String secret = "s3cr3t";
CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)));
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'SECRET')]) {\n"
// forgot set +x, ran /usr/bin/env, etc.
+ " if (isUnix()) {sh 'echo $SECRET > oops'} else {bat 'echo %SECRET% > oops'}\n"
+ " }\n"
+ "}", true));
WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get());
story.j.assertLogNotContains(secret, b);
story.j.assertLogContains("echo ****", b);
}
});
}
@Issue("SECURITY-1374")
@Test public void maskingPostBuild() throws Exception {
String credentialsId = "creds_1";
String password = "p4$$";
StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample1", Secret.fromString(password));
CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);
SecretBuildWrapper wrapper = new SecretBuildWrapper(Collections.singletonList(new StringBinding("PASS_1", credentialsId)));
FreeStyleProject f = r.createFreeStyleProject();
f.setConcurrentBuild(true);
f.getBuildWrappersList().add(wrapper);
Publisher publisher = new PasswordPublisher(password);
f.getPublishersList().add(publisher);
FreeStyleBuild b = r.buildAndAssertSuccess(f);
r.assertLogNotContains(password, b);
r.assertLogContains("****", b);
}
@Test
public void grandParentOverride() throws Exception {
Folder grandParent = j.createProject(Folder.class);
getFolderStore(grandParent).addCredentials(Domain.global(), grandParentCred);
grandParent.addProperty(new FolderConfig("parent_docker", "https://parent.registry", grandParentCred.getId()));
Folder parent = grandParent.createProject(Folder.class, "testParent"); //Can be static since grandParent should be unique
getFolderStore(parent).addCredentials(Domain.global(), folderCred);
parent.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(parent)
.runFromRepo(false)
.logContains("Docker Label is: folder_docker",
"Registry URL is: https://folder.registry",
"Registry Creds ID is: " + folderCred.getId())
.logNotContains("Docker Label is: parent_docker",
"Registry URL is: https://parent.registry",
"Registry Creds ID is: " + grandParentCred.getId()).go();
}
@Issue("JENKINS-42999")
@Test
public void widerRequiredContext() throws Exception {
final String credentialsId = "creds";
final String credsFile = "credsFile";
final String credsContent = "s3cr3t";
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
FileCredentialsImpl c = new FileCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", credsFile, SecretBytes.fromBytes(credsContent.getBytes()));
CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c);
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(""
+ "withCredentials([file(variable: 'targetFile', credentialsId: '" + credentialsId + "')]) {\n"
+ " echo 'We should fail before getting here'\n"
+ "}", true));
WorkflowRun b = story.j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0));
story.j.assertLogNotContains("We should fail before getting here", b);
story.j.assertLogContains("Required context class hudson.FilePath is missing", b);
story.j.assertLogContains("Perhaps you forgot to surround the code with a step that provides this, such as: node", b);
}
});
}
@Issue("JENKINS-30941")
@Test
public void cleanUpSucceeds() throws Exception {
/** Issue was just present on Linux not windows - but the test will run on both */
final String credentialsId = "zipfile";
FileCredentialsImpl fc = new FileCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "Just a zip file", "a.zip", SecretBytes.fromBytes(IOUtils.toByteArray(ZipFileBindingTest.class.getResource("a.zip"))));
CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), fc);
final String contents = "Test of ZipFileBinding\n";
WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " withCredentials([[$class: 'ZipFileBinding', credentialsId: '"+ credentialsId +"', variable: 'ziploc']]) {\n"
+ " echo readFile(encoding: 'UTF-8', file: \"${env.ziploc}/dir/testfile.txt\")\n"
+ " }\n"
+ "}\n"
, true));
WorkflowRun run = p.scheduleBuild2(0).get();
j.assertBuildStatusSuccess(run);
j.assertLogContains(contents, run);
}
@Test public void configRoundTrip() {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate");
CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials);
StepConfigTester sct = new StepConfigTester(story.j);
Map<String,Object> serverConfig = new TreeMap<String,Object>();
serverConfig.put("uri", "tcp://host:2375");
serverConfig.put("credentialsId", serverCredentials.getId());
Map<String,Object> config = Collections.<String,Object>singletonMap("server", serverConfig);
ServerEndpointStep step = DescribableHelper.instantiate(ServerEndpointStep.class, config);
step = sct.configRoundTrip(step);
DockerServerEndpoint server = step.getServer();
assertNotNull(server);
assertEquals("tcp://host:2375", server.getUri());
assertEquals(serverCredentials.getId(), server.getCredentialsId());
assertEquals(config, DescribableHelper.uninstantiate(step));
}
});
}
@Test
public void directParent() throws Exception {
Folder folder = j.createProject(Folder.class);
getFolderStore(folder).addCredentials(Domain.global(), folderCred);
folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
.inFolder(folder)
.runFromRepo(false)
.logContains("Docker Label is: folder_docker",
"Registry URL is: https://folder.registry",
"Registry Creds ID is: " + folderCred.getId()).go();
}
private void setupCredentials(String credentialId, String secret) throws Exception {
final CredentialsStore credentialsStore =
CredentialsProvider.lookupStores(jRule.jenkins).iterator().next();
final Domain domain = Domain.global();
final Credentials credentials =
new StringCredentialsImpl(
CredentialsScope.GLOBAL, credentialId, "", Secret.fromString(secret));
credentialsStore.addCredentials(domain, credentials);
}
private void setupCredentials(String credentialId, String secret) throws Exception {
final CredentialsStore credentialsStore =
CredentialsProvider.lookupStores(jRule.jenkins).iterator().next();
final Domain domain = Domain.global();
final Credentials credentials =
new StringCredentialsImpl(
CredentialsScope.GLOBAL, credentialId, "", Secret.fromString(secret));
credentialsStore.addCredentials(domain, credentials);
}
@Before
public void setup() throws Exception {
UsernamePasswordCredentialsImpl c =
new UsernamePasswordCredentialsImpl(
CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
CredentialsProvider.lookupStores(j.jenkins)
.iterator()
.next()
.addCredentials(Domain.global(), c);
g.getClient()
.when(
HttpRequest.request("/a/plugins/checks/checks.pending/")
.withQueryStringParameters(query)
.withMethod("GET"))
.respond(
HttpResponse.response()
.withStatusCode(200)
.withBody(JsonBody.json(pendingChecksInfos)));
GerritSCMSource source =
new GerritSCMSource(
String.format(
"https://%s:%s/a/test",
g.getClient().remoteAddress().getHostName(),
g.getClient().remoteAddress().getPort()));
source.setInsecureHttps(true);
source.setCredentialsId("cid");
request = context.newRequest(source, new StreamTaskListener());
}
@Test
public void smokes() throws Exception {
DumbSlave slave = j.createOnlineSlave();
VirtualChannel channel = slave.getChannel();
FreeStyleProject item = j.createFreeStyleProject();
CredentialsStore store = CredentialsProvider.lookupStores(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 credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString("a"), "b", "c");
store.addDomain(domain, credentials);
DockerServerEndpoint endpoint = new DockerServerEndpoint("tcp://localhost:2736", credentials.getId());
FilePath dotDocker = DockerServerEndpoint.dotDocker(channel);
List<FilePath> dotDockerKids = dotDocker.list();
int initialSize = dotDockerKids == null ? 0 : dotDockerKids.size();
KeyMaterialFactory factory = endpoint.newKeyMaterialFactory(item, channel);
KeyMaterial keyMaterial = factory.materialize();
FilePath path = null;
try {
assertThat(keyMaterial.env().get("DOCKER_HOST", "missing"), is("tcp://localhost:2736"));
assertThat(keyMaterial.env().get("DOCKER_TLS_VERIFY", "missing"), is("1"));
assertThat(keyMaterial.env().get("DOCKER_CERT_PATH", "missing"), not("missing"));
path = new FilePath(channel, keyMaterial.env().get("DOCKER_CERT_PATH", "missing"));
if (!Functions.isWindows()) {
assertThat(path.mode() & 0777, is(0700));
}
assertThat(path.child("key.pem").readToString(), is("a"));
assertThat(path.child("cert.pem").readToString(), is("b"));
assertThat(path.child("ca.pem").readToString(), is("c"));
} finally {
keyMaterial.close();
}
assertThat(path.child("key.pem").exists(), is(false));
assertThat(path.child("cert.pem").exists(), is(false));
assertThat(path.child("ca.pem").exists(), is(false));
assertThat(dotDocker.list().size(), is(initialSize));
}
@Test
@ConfiguredWithReadme("gitlab/README.md")
public void configure_gitlab_api_token() throws Exception {
SystemCredentialsProvider systemCreds = SystemCredentialsProvider.getInstance();
List<DomainCredentials> domainCredentials = systemCreds.getDomainCredentials();
assertEquals(1, domainCredentials.size());
final DomainCredentials gitLabCredential = domainCredentials.get(0);
assertEquals(Domain.global(), gitLabCredential.getDomain());
assertEquals(1, gitLabCredential.getCredentials().size());
final GitLabApiToken apiToken = (GitLabApiToken)gitLabCredential.getCredentials().get(0);
assertEquals("gitlab_token", apiToken.getId());
assertEquals("qwertyuiopasdfghjklzxcvbnm", apiToken.getApiToken().getPlainText());
assertEquals("Gitlab Token", apiToken.getDescription());
}
@Test public void configRoundTrip() throws Exception {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
SSHUserPrivateKey c = new DummyPrivateKey("creds", "bob", "secret", "the-key");
CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c);
SSHUserPrivateKeyBinding binding = new SSHUserPrivateKeyBinding("keyFile", "creds");
binding.setPassphraseVariable("passphrase");
binding.setUsernameVariable("user");
BindingStep s = new StepConfigTester(story.j).configRoundTrip(new BindingStep(
Collections.<MultiBinding>singletonList(binding)));
story.j.assertEqualDataBoundBeans(s.getBindings(), Collections.singletonList(binding));
}
});
}