com.cloudbees.plugins.credentials.SystemCredentialsProvider Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.SystemCredentialsProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testStepWithGlobalCredentials() throws Exception {

	String globalCredentialsId = "global-aws-creds";

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(globalCredentialsId);

	StandardUsernamePasswordCredentials key = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			globalCredentialsId, "test-global-creds", "global-aws-access-key-id", "global-aws-secret-access-key");
	SystemCredentialsProvider.getInstance().getCredentials().add(key);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + globalCredentialsId + "') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
}
 
Example #2
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void createUsingUsernamePassword() 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("password", "abcd")
                            .put("stapler-class", "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl")
                            .put("scope", "GLOBAL")
                            .put("description", "joe desc")
                            .put("$class", "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl")
                            .put("username", "joe").build()
            )
            , 201);
    Assert.assertEquals("Username with password", resp.get("typeName"));
    Assert.assertEquals("domain1", resp.get("domain"));
}
 
Example #3
Source File: SiteTest.java    From jira-steps-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void test_credentials() throws Exception {
  String username = "user1";
  String password = "mypassword";
  String issueId = "ISSUE-1";
  String commentId = "1";

  UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test1", null, username, password);
  SystemCredentialsProvider.getInstance().getCredentials().add(c);

  Site site = new Site("TEST", new URL(wireMockRule.baseUrl()), LoginType.CREDENTIAL.name(), 10000);
  site.setCredentialsId(c.getId());

  String url = "/rest/api/2/issue/" + issueId + "/comment/" + commentId;
  wireMockRule.stubFor(get(url).willReturn(aResponse().withBody("{}")));
  site.getService().getComment(issueId, commentId);

  String token = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
  wireMockRule.verify(getRequestedFor(urlEqualTo(url)).withHeader("Authorization", equalTo("Basic " + token)));
}
 
Example #4
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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"));
}
 
Example #5
Source File: DockerComputerSSHConnectorTest.java    From docker-plugin with MIT License 6 votes vote down vote up
@Test
public void connectAgentViaSSHUsingCredentialsKey() throws Exception {
    final InstanceIdentity id = InstanceIdentity.get();
    final String privateKey = PEMEncodable.create(id.getPrivate()).encode();
    final String publicKey = "ssh-rsa " + encode(new RSAKeyAlgorithm().encodePublicKey(id.getPublic()));
    final String credentialsId = "tempCredId";
    final StandardUsernameCredentials credentials = DockerComputerSSHConnector.makeCredentials(credentialsId, COMMON_IMAGE_USERNAME, privateKey);
    SystemCredentialsProvider.getInstance().getCredentials().add(credentials);
    final DockerComputerSSHConnector.SSHKeyStrategy sshKeyStrategy = new DockerComputerSSHConnector.ManuallyConfiguredSSHKey(credentialsId, new NonVerifyingKeyVerificationStrategy());
    final DockerComputerSSHConnector connector = new DockerComputerSSHConnector(sshKeyStrategy);
    connector.setJavaPath(SSH_SLAVE_IMAGE_JAVAPATH);
    final DockerTemplate template = new DockerTemplate(
            new DockerTemplateBase(SSH_SLAVE_IMAGE_IMAGENAME),
            connector,
            LABEL, COMMON_IMAGE_HOMEDIR, INSTANCE_CAP
    );
    template.getDockerTemplateBase().setEnvironmentsString("JENKINS_SLAVE_SSH_PUBKEY=" + publicKey);
    template.setName("connectAgentViaSSHUsingCredentialsKey");
    should_connect_agent(template);
}
 
Example #6
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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"));
}
 
Example #7
Source File: VaultConfigurationIT.java    From hashicorp-vault-plugin with MIT License 6 votes vote down vote up
@Before
public void setupJenkins() throws IOException {
    GlobalVaultConfiguration globalConfig = GlobalConfiguration.all()
        .get(GlobalVaultConfiguration.class);
    assertThat(globalConfig, is(notNullValue()));
    VaultConfiguration vaultConfig = new VaultConfiguration();
    vaultConfig.setVaultUrl("http://global-vault-url.com");
    vaultConfig.setVaultCredentialId(GLOBAL_CREDENTIALS_ID_1);
    vaultConfig.setFailIfNotFound(false);
    vaultConfig.setEngineVersion(GLOBAL_ENGINE_VERSION_2);
    vaultConfig.setVaultNamespace("mynamespace");
    vaultConfig.setTimeout(TIMEOUT);
    globalConfig.setConfiguration(vaultConfig);

    globalConfig.save();

    GLOBAL_CREDENTIAL_1 = createTokenCredential(GLOBAL_CREDENTIALS_ID_1);
    GLOBAL_CREDENTIAL_2 = createTokenCredential(GLOBAL_CREDENTIALS_ID_2);

    SystemCredentialsProvider.getInstance()
        .setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Arrays
            .asList(GLOBAL_CREDENTIAL_1, GLOBAL_CREDENTIAL_2)));

    this.project = jenkins.createFreeStyleProject("test");
}
 
Example #8
Source File: IntegrationTest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
@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);
    }
}
 
Example #9
Source File: GitLabConnection.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
@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();
}
 
Example #10
Source File: GHRule.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: DockerServerCredentialsTest.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
@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()));
}
 
Example #12
Source File: DockerServerCredentialsBindingTest.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
@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", Secret.fromString("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")));
        }
    });
}
 
Example #13
Source File: S3UploadStepIntegrationTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #14
Source File: ContainerExecDecoratorPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void docker() throws Exception {
    StandardUsernamePasswordCredentials credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
            "ContainerExecDecoratorPipelineTest-docker", "bob", "myusername", "secret_password");
    SystemCredentialsProvider.getInstance().getCredentials().add(credentials);

    containerExecLogs.capture(1000);
    assertNotNull(createJobThenScheduleRun());
    r.waitForCompletion(b);
    // docker login will fail but we can check that it runs the correct command
    r.assertLogContains("Executing command: \"docker\" \"login\" \"-u\" \"myusername\" \"-p\" ******** \"https://index.docker.io/v1/\"", b);
    // check that we don't accidentally start exporting sensitive info to the build log
    r.assertLogNotContains("secret_password", b);
    // check that we don't accidentally start exporting sensitive info to the Jenkins log
    assertFalse("credential leaked to log",
            containerExecLogs.getMessages().stream().anyMatch(msg -> msg.contains("secret_password")));
}
 
Example #15
Source File: ContainerExecDecoratorPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Issue({ "JENKINS-47225", "JENKINS-42582" })
@Test
public void sshagent() throws Exception {
    PrivateKeySource source = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(
            new String(IOUtils.toByteArray(getClass().getResourceAsStream("id_rsa"))));
    BasicSSHUserPrivateKey credentials = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL,
            "ContainerExecDecoratorPipelineTest-sshagent", "bob", source, "secret_passphrase", "test credentials");
    SystemCredentialsProvider.getInstance().getCredentials().add(credentials);

    assertNotNull(createJobThenScheduleRun());
    r.waitForCompletion(b);
    r.assertLogContains("Identity added:", b);
    //Assert that ssh-agent provided envVar is now properly contributed and set.
    r.assertLogContains("SSH_AGENT_PID=", b);
    //assert that our private key was loaded and is visible within the ssh-agent scope
    r.assertLogContains("ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDhvmTBXRnSbtpnkt/Ldw7ws4LFdoX9oI+5NexgpBC4Otqbn8+Ui6FGWeYflOQUcl3rgmBxsHIeFnPr9qSvgME1TWPIyHSQh2kPMd3NQgkEvioBxghnWRy7sal4KBr2P8m7Iusm8j0aCNLZ3nYjJSywWZxiqqrcpnhFuTD//FPIEhXOu2sk2FEP7YsA9TdL8mAruxy/6Ys2pRC2dQhBtmkEOyEGiBnk3ioT5iCw/Qqe+pU0yaYu69vPyAFCuazBMopPcOuRxFgKvrfCPVqcQb3HERJh5eiW5+5Vg3RwoByQUtQMK5PDBVWPo9srB0Q9Aw9DXmeJCgdtFJqhhh4SR+al /home/jenkins/agent/workspace/sshagent@tmp/private_key",b);
     //check that we don't accidentally start exporting sensitive info to the log
    r.assertLogNotContains("secret_passphrase", b);
}
 
Example #16
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 6 votes vote down vote up
@Test
public void buildWithWrongCredentialsMustFail() throws Exception {

    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'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.CREDENTIALS_LOGIN_INVALID, b1);
}
 
Example #17
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 6 votes vote down vote up
@Test
public void buildWithWrongCredentialsMustFailEnterprise() throws Exception {

    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.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.CREDENTIALS_LOGIN_INVALID, b1);
}
 
Example #18
Source File: GitHubAppCredentialsJCasCCompatibilityTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void should_support_configuration_as_code() {
    List<DomainCredentials> domainCredentials = SystemCredentialsProvider.getInstance()
            .getDomainCredentials();

    assertThat(domainCredentials.size(), is(1));
    List<Credentials> credentials = domainCredentials.get(0).getCredentials();
    assertThat(credentials.size(), is(1));

    Credentials credential = credentials.get(0);
    assertThat(credential, instanceOf(GitHubAppCredentials.class));
    GitHubAppCredentials gitHubAppCredentials = (GitHubAppCredentials) credential;

    assertThat(gitHubAppCredentials.getAppID(), is("1111"));
    assertThat(gitHubAppCredentials.getDescription(), is("GitHub app 1111"));
    assertThat(gitHubAppCredentials.getId(), is("github-app"));
    assertThat(gitHubAppCredentials.getPrivateKey(), hasPlainText(GITHUB_APP_KEY));
}
 
Example #19
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #20
Source File: GitLabPersonalAccessTokenCreator.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #21
Source File: DockerServerCredentialsTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test
public void configRoundTripData() 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("a"), "b", "c");
    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())));
}
 
Example #22
Source File: DockerServerDomainSpecificationTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test
public void configRoundTrip() 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()));
    store.addDomain(domain);

    j.submit(j.createWebClient().goTo("credentials/store/system/domain/" + domain.getName() + "/configure")
            .getFormByName("config"));
    
    j.assertEqualDataBoundBeans(domain, byName(store.getDomains(),domain.getName()));
}
 
Example #23
Source File: GitLabRule.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public GitLabConnectionProperty createGitLabConnectionProperty() 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(getApiToken())));
        }
    }

    GitLabConnectionConfig config = Jenkins.getInstance().getDescriptorByType(GitLabConnectionConfig.class);
    GitLabConnection connection = new GitLabConnection("test", url, API_TOKEN_ID, new V3GitLabClientBuilder(), true,10, 10);
    config.addConnection(connection);
    config.save();
    return new GitLabConnectionProperty(connection.getName());
}
 
Example #24
Source File: KubernetesTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
@LocalData()
public void upgradeFrom_1_1() throws Exception {
    List<Credentials> credentials = SystemCredentialsProvider.getInstance().getCredentials();
    assertEquals(3, credentials.size());
    UsernamePasswordCredentialsImpl cred0 = (UsernamePasswordCredentialsImpl) credentials.get(0);
    assertEquals("token", cred0.getId());
    assertEquals("myusername", cred0.getUsername());
    FileSystemServiceAccountCredential cred1 = (FileSystemServiceAccountCredential) credentials.get(1);
    StringCredentialsImpl cred2 = (StringCredentialsImpl) credentials.get(2);
    assertEquals("mytoken", Secret.toString(cred2.getSecret()));
    assertThat(cloud.getLabels(), hasEntry("jenkins", "slave"));
    assertEquals(cloud.DEFAULT_WAIT_FOR_POD_SEC, cloud.getWaitForPodSec());
}
 
Example #25
Source File: GitHubSCMBuilderTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    owner = j.createProject(WorkflowMultiBranchProject.class);
    Credentials userPasswordCredential = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "user-pass", null, "git-user", "git-secret");
    Credentials sshPrivateKeyCredential = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, "user-key", "git",
            new BasicSSHUserPrivateKey.UsersPrivateKeySource(), null, null);
    SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.singletonMap(Domain.global(),
            Arrays.asList(userPasswordCredential, sshPrivateKeyCredential)));
}
 
Example #26
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 5 votes vote down vote up
public static String migrateCredentials(final String username, final String password) {
  String credentialsId = null;
  final DomainRequirement domainRequirement = null;
  final List<StandardUsernamePasswordCredentials> credentials =
      CredentialsMatchers.filter(
          CredentialsProvider.lookupCredentials(
              StandardUsernamePasswordCredentials.class,
              Jenkins.getInstance(),
              ACL.SYSTEM,
              domainRequirement),
          CredentialsMatchers.withUsername(username));
  for (final StandardUsernamePasswordCredentials cred : credentials) {
    if (StringUtils.equals(password, Secret.toString(cred.getPassword()))) {
      // If some credentials have the same username/password, use those.
      credentialsId = cred.getId();
      break;
    }
  }
  if (StringUtils.isBlank(credentialsId)) {
    // If we couldn't find any existing credentials,
    // create new credentials with the principal and secret and use it.
    final StandardUsernamePasswordCredentials newCredentials =
        new UsernamePasswordCredentialsImpl(
            CredentialsScope.SYSTEM,
            null,
            "Migrated by Violation comments to bitbucket plugin",
            username,
            password);
    SystemCredentialsProvider.getInstance().getCredentials().add(newCredentials);
    credentialsId = newCredentials.getId();
  }
  if (StringUtils.isNotEmpty(credentialsId)) {
    return credentialsId;
  } else {
    return null;
  }
}
 
Example #27
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Test that a JSON credential with "jenkins_token" uses the token value as the authentication token.
 *
 * @throws Exception
 */
@Test
public void testRecorderJSONToken() throws Exception {
    final FreeStyleProject                       project         = j.createFreeStyleProject();
    final String                                 responseStr     = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
    final SystemCredentialsProvider.ProviderImpl system          = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore     = system.getStore(j.getInstance());
    final String                                 tokenValue      = "my secret token";
    final String                                 credentialValue = "{\"field1\":\"some value\", \"jenkins_token\":\"" + tokenValue + "\"}";
    final Secret                                 secret          = Secret.fromString(credentialValue);
    final StringCredentials                      credential      = new StringCredentialsImpl(CredentialsScope.GLOBAL, "jsontoken", "a token for JSON token test", secret);
    TestUtils.enqueueJsonResponse(httpServer, responseStr);
    systemStore.addCredentials(Domain.global(), credential);

    // add builders
    addBuilders(TestUtils.loadFixture("idonly.json"), project);

    // add post-builder
    addPostBuilders(project, "jsontoken");

    final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon]", build);

    // handler assertions
    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request           = httpServer.takeRequest();
    final String    authorizationText = request.getHeader("Authorization");
    assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}
 
Example #28
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void build() 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.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'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #29
Source File: TestUtility.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
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)));
        }
    }
}
 
Example #30
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Test a basic API token using StringCredentials.
 *
 * @throws Exception
 */
@Test
public void testRecorderBasicToken() throws Exception {
    final FreeStyleProject                       project     = j.createFreeStyleProject();
    final String                                 responseStr = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
    final SystemCredentialsProvider.ProviderImpl system      = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore = system.getStore(j.getInstance());
    final String                                 tokenValue  = "my secret token";
    final Secret                                 secret      = Secret.fromString(tokenValue);
    final StringCredentials                      credential  = new StringCredentialsImpl(CredentialsScope.GLOBAL, "basictoken", "a token for basic token test", secret);
    TestUtils.enqueueJsonResponse(httpServer, responseStr);
    systemStore.addCredentials(Domain.global(), credential);

    // add builders
    addBuilders(TestUtils.loadFixture("idonly.json"), project);
    // add post-builder
    addPostBuilders(project, "basictoken");

    final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon]", build);

    // handler assertions
    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request = httpServer.takeRequest();

    final String authorizationText = request.getHeader("Authorization");
    assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}