下面列出了hudson.model.ModelObject#com.cloudbees.plugins.credentials.CredentialsScope 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Prepare global GitHub plugin configuration.
* Nothing specific to job.
*/
public static GitHubServerConfig prepareGitHubPlugin() {
// prepare global jRule settings
final StringCredentialsImpl cred = new StringCredentialsImpl(
CredentialsScope.GLOBAL,
null,
"description",
Secret.fromString(GH_TOKEN)
);
SystemCredentialsProvider.getInstance().getCredentials().add(cred);
final GitHubPluginConfig gitHubPluginConfig = GitHubPlugin.configuration();
final List<GitHubServerConfig> gitHubServerConfigs = new ArrayList<>();
final GitHubServerConfig gitHubServerConfig = new GitHubServerConfig(cred.getId());
gitHubServerConfig.setManageHooks(false);
gitHubServerConfig.setClientCacheSize(0);
gitHubServerConfigs.add(gitHubServerConfig);
gitHubPluginConfig.setConfigs(gitHubServerConfigs);
return gitHubServerConfig;
}
@Test public void stepExecutionWithCredentials() {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
assumeNotWindows();
IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate");
CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials);
WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
p.setDefinition(new CpsFlowDefinition(
"node {\n" +
" withDockerServer(server: [uri: 'tcp://host:1234', credentialsId: 'serverCreds']) {\n" +
" sh 'echo would be connecting to $DOCKER_HOST'\n" +
" sh 'echo DOCKER_TLS_VERIFY=$DOCKER_TLS_VERIFY'\n" +
" sh 'echo DOCKER_CERT_PATH=$DOCKER_CERT_PATH is not empty'\n" +
" }\n" +
"}", true));
WorkflowRun b = story.j.buildAndAssertSuccess(p);
story.j.assertLogContains("would be connecting to tcp://host:1234", b);
story.j.assertLogContains("DOCKER_TLS_VERIFY=1", b);
story.j.assertLogNotContains("DOCKER_CERT_PATH= is not empty", b);
}
});
}
@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("JENKINS-27389")
@Test public void grabEnv() {
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(""
+ "def extract(id) {\n"
+ " def v\n"
+ " withCredentials([string(credentialsId: id, variable: 'temp')]) {\n"
+ " v = env.temp\n"
+ " }\n"
+ " v\n"
+ "}\n"
+ "node {\n"
+ " echo \"got: ${extract('" + credentialsId + "')}\"\n"
+ "}", true));
story.j.assertLogContains("got: " + secret, story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get()));
}
});
}
@POST
@SuppressWarnings("unused") // stapler
@Restricted(NoExternalUse.class) // stapler
public FormValidation doTestConnection(
@QueryParameter("appID") final String appID,
@QueryParameter("privateKey") final String privateKey,
@QueryParameter("apiUri") final String apiUri,
@QueryParameter("owner") final String owner
) {
GitHubAppCredentials gitHubAppCredential = new GitHubAppCredentials(
CredentialsScope.GLOBAL, "test-id-not-being-saved", null,
appID, Secret.fromString(privateKey)
);
gitHubAppCredential.setApiUri(apiUri);
gitHubAppCredential.setOwner(owner);
try {
GitHub connect = Connector.connect(apiUri, gitHubAppCredential);
return FormValidation.ok("Success, Remaining rate limit: " + connect.getRateLimit().getRemaining());
} catch (Exception e) {
return FormValidation.error(e, String.format(ERROR_AUTHENTICATING_GITHUB_APP, appID));
}
}
@Issue("JENKINS-37871")
@Test public void secretBuildWrapperRunsBeforeNormalWrapper() throws Exception {
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(Arrays.asList(new StringBinding(bindingKey, credentialsId)));
FreeStyleProject f = r.createFreeStyleProject("buildWrapperOrder");
f.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo $PASS_1"));
f.getBuildWrappersList().add(new BuildWrapperOrder());
f.getBuildWrappersList().add(wrapper);
// configRoundtrip makes sure the ordinal of SecretBuildWrapper extension is applied correctly.
r.configRoundtrip(f);
FreeStyleBuild b = r.buildAndAssertSuccess(f);
r.assertLogContains("Secret found!", b);
}
@Test
public void testBasicAuth() {
UsernamePasswordCredentials credentials
= new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
influxDbCredentialsId,
"Description",
influxDbUser,
influxDbPassword);
when(config.getCredentials())
.thenReturn(credentials);
InfluxDbNotifier instance = new InfluxDbNotifier(config);
assertEquals("http://fake/write?db=mockdb",
instance.influxDbUrlString);
assertEquals(new String(Base64.getDecoder().decode(instance.authorization)),
"mock-user:mock-password");
}
/**
* 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);
}
@Test
public void stepExecutionWithCredentials() throws Exception {
assumeNotWindows();
IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials);
WorkflowJob p = r.createProject(WorkflowJob.class, "prj");
p.setDefinition(new CpsFlowDefinition(
"node {\n" +
" mockDockerLoginWithEcho {\n" +
" withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" +
" }\n" +
" }\n" +
"}", true));
WorkflowRun b = r.buildAndAssertSuccess(p);
r.assertLogContains("docker login -u me -p pass https://my-reg:1234", r.assertBuildStatusSuccess(r.waitForCompletion(b)));
}
@Test public void incorrectType() throws Exception {
story.addStep(new Statement() {
@Override public void evaluate() throws Throwable {
StringCredentialsImpl c = new StringCredentialsImpl(CredentialsScope.GLOBAL, "creds", "sample", Secret.fromString("s3cr3t"));
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([usernamePassword(usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD', credentialsId: 'creds')]) {\n"
+ " }\n"
+ "}", true));
WorkflowRun r = story.j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());
// make sure error message contains information about the actual type and the expected type
story.j.assertLogNotContains("s3cr3t", r);
story.j.assertLogContains(StandardUsernamePasswordCredentials.class.getName(), r); // no descriptor for the interface type
story.j.assertLogContains(stringCredentialsDescriptor.getDisplayName(), r);
story.j.assertLogNotContains("\tat ", r);
}
});
}
@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());
}
@DataBoundConstructor
public KeystoreCredentialsImpl(@CheckForNull CredentialsScope scope, @CheckForNull String id, @CheckForNull String description, @Nonnull FileItem file, @CheckForNull String fileName, @CheckForNull String data, @CheckForNull String passphrase) throws IOException {
super(scope, id, description);
String name = file.getName();
if (name.length() > 0) {
this.fileName = name.replaceFirst("^.+[/\\\\]", "");
byte[] unencrypted = file.get();
try {
this.data = KEY.encrypt().doFinal(unencrypted);
} catch (GeneralSecurityException x) {
throw new IOException2(x);
}
} else {
this.fileName = fileName;
this.data = Base64.decodeBase64(data);
}
this.passphrase = Secret.fromString(passphrase);
}
@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);
}
}
@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);
}
});
}
public DockerServerCredentials getDockerServerCredentials() throws IOException {
final LocalDirectorySSLConfig sslContext = (LocalDirectorySSLConfig) clientConfig.getSSLConfig();
assertThat("DockerCli must be connected via SSL", sslContext, notNullValue());
String certPath = sslContext.getDockerCertPath();
final String keypem = FileUtils.readFileToString(new File(certPath + "/" + "key.pem"));
final String certpem = FileUtils.readFileToString(new File(certPath + "/" + "cert.pem"));
final String capem = FileUtils.readFileToString(new File(certPath + "/" + "ca.pem"));
return new DockerServerCredentials(
CredentialsScope.GLOBAL, // scope
null, // name
null, //desc
keypem,
certpem,
capem
);
}
@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);
}
});
}
@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();
}
@Issue("JENKINS-49025")
@Test
public void smokes() throws Exception {
String globalCredentialsId = "x";
StandardUsernamePasswordCredentials key = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, globalCredentialsId, "x", "x", "x");
SystemCredentialsProvider.getInstance().getCredentials().add(key);
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"node('" + r.createSlave().getNodeName() + "') {\n" +
" withAWS (credentials: '" + globalCredentialsId + "') {\n" +
" writeFile file: 'x', text: ''\n" +
" try {\n" +
" s3Upload bucket: 'x', file: 'x', path: 'x'\n" +
" fail 'should not have worked'\n" +
" } catch (com.amazonaws.services.s3.model.AmazonS3Exception x) {\n" +
" echo(/got $x as expected/)\n" +
" }\n" +
" }\n" +
"}\n", true)
);
r.assertBuildStatusSuccess(p.scheduleBuild2(0));
}
/**
* Test that a JSON credential without a "jenkins_token" field and without a proper DC/OS service account value
* results in a 401 and only 1 web request.
*
* @throws Exception
*/
@Test
public void testRecorderInvalidToken() throws Exception {
final FreeStyleProject project = j.createFreeStyleProject();
final SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
final CredentialsStore systemStore = system.getStore(j.getInstance());
final String credentialValue = "{\"field1\":\"some value\"}";
final Secret secret = Secret.fromString(credentialValue);
final StringCredentials credential = new StringCredentialsImpl(CredentialsScope.GLOBAL, "invalidtoken", "a token for JSON token test", secret);
TestUtils.enqueueFailureResponse(httpServer, 401);
systemStore.addCredentials(Domain.global(), credential);
addBuilders(TestUtils.loadFixture("idonly.json"), project);
// add post-builder
addPostBuilders(project, "invalidtoken");
final FreeStyleBuild build = j.assertBuildStatus(Result.FAILURE, project.scheduleBuild2(0).get());
j.assertLogContains("[Marathon] Authentication to Marathon instance failed:", build);
j.assertLogContains("[Marathon] Invalid DC/OS service account JSON", build);
assertEquals("Only 1 request should have been made.", 1, httpServer.getRequestCount());
}
@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 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
public void configRoundTripEmpty() 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.<DomainSpecification>singletonList(new DockerServerDomainSpecification()));
DockerServerCredentials credentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "foo", "desc", Secret.fromString(""), "", "");
store.addDomain(domain, credentials);
j.submit(j.createWebClient().goTo("credentials/store/system/domain/" + domain.getName() + "/credential/"+credentials.getId()+"/update")
.getFormByName("update"));
j.assertEqualDataBoundBeans(credentials, CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(IdCredentials.class, j.getInstance(),
ACL.SYSTEM, new DockerServerDomainRequirement()), CredentialsMatchers.withId(credentials.getId())));
}
@Test
public void buildEnterprise() throws Exception {
GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
PowerMockito.when(ghb.withEndpoint("https://api.example.com")).thenReturn(ghb);
PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
GitHub gh = PowerMockito.mock(GitHub.class);
PowerMockito.when(ghb.build()).thenReturn(gh);
PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
GHRepository repo = PowerMockito.mock(GHRepository.class);
GHUser user = PowerMockito.mock(GHUser.class);
GHCommit commit = PowerMockito.mock(GHCommit.class);
PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);
Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
SystemCredentialsProvider.getInstance().getCredentials().add(dummy);
WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
"credentialsId: 'dummy', description: 'All tests are OK', " +
"repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
"status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
));
WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
static void addGitLabApiToken() throws IOException {
for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
List<Domain> domains = credentialsStore.getDomains();
credentialsStore.addCredentials(domains.get(0),
new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN)));
}
}
}
@Test
public void testAwsKeyCredentialsWithIdNull() {
final AwsKeyCredentials credentials = new AwsKeyCredentials(CredentialsScope.GLOBAL, null, DESC, ACCESS, SECRET);
assertThat(credentials.key, is(ACCESS));
assertThat(credentials.secret, is(SECRET));
assertThat(credentials.getId(), is(ACCESS));
assertThat(credentials.getScope(), is(CredentialsScope.GLOBAL));
}
@Test
@Issue("SECURITY-1404")
public void checkUsernamePasswordIsSecret() {
Attribute a = getFromDatabound(UsernamePasswordCredentialsImpl.class, "password");
assertTrue("Attribute 'password' should be secret", a.isSecret(
new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "1", "2", "3", "4")));
}
@Issue("JENKINS-41760")
@Test public void emptySecret() throws Exception {
CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, "creds", null, Secret.fromString("")));
FreeStyleProject p = r.createFreeStyleProject();
p.getBuildWrappersList().add(new SecretBuildWrapper(Collections.singletonList(new StringBinding("SECRET", "creds"))));
p.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo PASSES") : new Shell("echo PASSES"));
r.assertLogContains("PASSES", r.buildAndAssertSuccess(p));
}
/**
* Verifies doCheckCredentialsId returns OK for credentials in the store
* @throws IOException
*/
@Test
public void testDoCheckCredentialsFound() 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();
assertEquals(Kind.OK, instance.doCheckCredentialsId(null, testCredentials).kind);
}
/**
* Verifies doCheckCredentialsId returns ERROR for credentials not in the store
* @throws IOException
*/
@Test
public void testDoCheckCredentialsNotFound() 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();
assertEquals(Kind.ERROR, instance.doCheckCredentialsId(null, testInvalidCredentials).kind);
}