Java Code Examples for com.cloudbees.plugins.credentials.SystemCredentialsProvider#ProviderImpl

The following examples show how to use com.cloudbees.plugins.credentials.SystemCredentialsProvider#ProviderImpl . 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: 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 2
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 3
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 4
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 5
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void listCredentials() 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.addCredentials(systemStore.getDomainByName("domain1"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "admin", "pass$wd"));


    CredentialsStoreAction credentialsStoreAction = ExtensionList.lookup(ViewCredentialsAction.class).get(0).getStore("system");
    CredentialsStoreAction.DomainWrapper domainWrapper = credentialsStoreAction.getDomain("domain1");
    CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredentialsList().get(0);


    List<Map>  creds = get("/organizations/jenkins/credentials/system/domains/domain1/credentials/", List.class);
    Assert.assertEquals(1, creds.size());
    Map cred = creds.get(0);
    Assert.assertNotNull(cred.get("id"));

    Map cred1 = get("/organizations/jenkins/credentials/system/domains/domain1/credentials/"+cred.get("id")+"/");

    Assert.assertEquals(credentialsWrapper.getId(),cred1.get("id"));
    Assert.assertEquals(credentialsWrapper.getTypeName(),cred1.get("typeName"));
    Assert.assertEquals(credentialsWrapper.getDisplayName(),cred1.get("displayName"));
    Assert.assertEquals(credentialsWrapper.getFullName(),cred1.get("fullName"));
    Assert.assertEquals(String.format("%s:%s:%s", credentialsWrapper.getDisplayName(), credentialsWrapper.getDomain().getUrlName(), credentialsWrapper.getTypeName()),cred1.get("description"));
    Assert.assertEquals(credentialsWrapper.getDomain().getUrlName(),cred1.get("domain"));
}
 
Example 6
Source File: TokenAuthProvider.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to update tokenCredentials with contents of creds.
 * <p>
 * This searches all domains for the id associated with tokenCredentials and updates the first credential it finds.
 *
 * @param tokenId Existing credentials that should be updated.
 * @param creds   New credentials
 * @throws IOException If problems reading or writing to Jenkins Credential Store
 */
boolean doTokenUpdate(final String tokenId, final Credentials creds) throws IOException {
    final SystemCredentialsProvider.ProviderImpl systemProvider = ExtensionList.lookup(CredentialsProvider.class)
            .get(SystemCredentialsProvider.ProviderImpl.class);
    if (systemProvider == null) return false;

    final CredentialsStore credentialsStore = systemProvider.getStore(Jenkins.getInstance());
    if (credentialsStore == null) return false;

    /*
        Walk through all domains and credentials for each domain to find a credential with the matching id.
     */
    for (final Domain d : credentialsStore.getDomains()) {
        for (Credentials c : credentialsStore.getCredentials(d)) {
            if (!(c instanceof StringCredentials)) continue;

            final StringCredentials stringCredentials = (StringCredentials) c;
            if (stringCredentials.getId().equals(tokenId)) {
                final boolean wasUpdated = credentialsStore.updateCredentials(d, c, creds);
                if (!wasUpdated) {
                    LOGGER.warning("Updating Token credential failed during update call.");
                }
                return wasUpdated;
            }
        }
    }

    // if the credential was not found, then put a warning in the console log.
    LOGGER.warning("Token credential was not found in the Credentials Store.");
    return false;
}
 
Example 7
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);
}
 
Example 8
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 9
Source File: UsernamePasswordBindingTest.java    From credentials-binding-plugin with MIT License 4 votes vote down vote up
@Test
public void theSecretBuildWrapperTracksUsage() throws Exception {
    SystemCredentialsProvider.getInstance().setDomainCredentialsMap(
    Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList()));
    for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) {
            store = s;
            break;
        }
    }
    assertThat("The system credentials provider is enabled", store, notNullValue());

    UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob",
                            "secret");
    store.addCredentials(Domain.global(), credentials);
    
    Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credentials);
    assertThat("No fingerprint created until first use", fingerprint, nullValue());

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

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

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

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

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

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

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

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

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

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