com.cloudbees.plugins.credentials.CredentialsStore Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsStore. 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 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 #2
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 #3
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 #4
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 #5
Source File: UserSSHKeyManager.java    From blueocean-plugin with MIT License 6 votes vote down vote up
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;
}
 
Example #6
Source File: DockerAgentTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@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);

    }
}
 
Example #7
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
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;
}
 
Example #8
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 #9
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 #10
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 #11
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@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;
}
 
Example #12
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
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");
    }

}
 
Example #13
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public static void updateCredentialsInUserStore(@Nonnull Credentials current, @Nonnull Credentials replacement,
                                                @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.updateCredentials(domain, current, replacement)){
        throw new ServiceException.UnexpectedErrorException("Failed to update credential to domain");
    }
}
 
Example #14
Source File: DockerServerEndpointTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@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));
}
 
Example #15
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 #16
Source File: ConfigTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@Test public void configRoundTrip() throws Exception {
    CredentialsStore store = CredentialsProvider.lookupStores(r.jenkins).iterator().next();
    IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, Secret.fromString("clientKey"), "clientCertificate", "serverCaCertificate");
    store.addCredentials(Domain.global(), serverCredentials);
    IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
    store.addCredentials(Domain.global(), registryCredentials);
    SampleDockerBuilder b1 = new SampleDockerBuilder(new DockerServerEndpoint("", ""), new DockerRegistryEndpoint("http://dhe.mycorp.com/", registryCredentials.getId()));
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
    b1 = new SampleDockerBuilder(new DockerServerEndpoint("tcp://192.168.1.104:8333", serverCredentials.getId()), new DockerRegistryEndpoint("", ""));
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
    r.jenkins.getDescriptorByType(DockerTool.DescriptorImpl.class).setInstallations(new DockerTool("Docker 1.5", "/usr/local/docker15", Collections.<ToolProperty<?>>emptyList()));
    b1.setToolName("Docker 1.5");
    r.assertEqualDataBoundBeans(b1, r.configRoundtrip(b1));
}
 
Example #17
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
private CredentialsStore getFolderStore(Folder f) {
    Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(f);
    CredentialsStore folderStore = null;
    for (CredentialsStore s : stores) {
        if (s.getProvider() instanceof FolderCredentialsProvider && s.getContext() == f) {
            folderStore = s;
            break;
        }
    }
    return folderStore;
}
 
Example #18
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 #19
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 #20
Source File: DockerServerCredentialsTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
@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())));
}
 
Example #21
Source File: SecretRetrieverTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
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);
}
 
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: 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 #24
Source File: TestUtility.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
static void setupGitLabConnections(JenkinsRule jenkins, MockServerRule mockServer) throws IOException {
    GitLabConnectionConfig connectionConfig = jenkins.get(GitLabConnectionConfig.class);
    String apiTokenId = "apiTokenId";
    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, apiTokenId, "GitLab API Token", Secret.fromString(TestUtility.API_TOKEN)));
        }
    }
    connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V3, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V3GitLabClientBuilder(), false, 10, 10));
    connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V4, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V4GitLabClientBuilder(), false, 10, 10));

}
 
Example #25
Source File: GitLabConnectionConfigSSLTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setup() 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_ID)));
        }
    }
}
 
Example #26
Source File: GitLabConnectionConfigTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
    gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab";
    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 #27
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 #28
Source File: DockerCloudTest.java    From docker-plugin with MIT License 5 votes vote down vote up
@Test
public void globalConfigRoundtrip() throws Exception {

    // Create fake credentials, so they are selectable on configuration for during configuration roundtrip
    final CredentialsStore store = CredentialsProvider.lookupStores(jenkins.getInstance()).iterator().next();
    DockerServerCredentials dc = new DockerServerCredentials(SYSTEM, "credentialsId", "test", null, null, null);
    store.addCredentials(Domain.global(), dc);
    UsernamePasswordCredentials rc = new UsernamePasswordCredentialsImpl(SYSTEM, "pullCredentialsId", null, null, null);
    store.addCredentials(Domain.global(), rc);

    final DockerTemplateBase templateBase = new DockerTemplateBase("image", "pullCredentialsId", "dnsString", "network",
            "dockerCommand", "volumesString", "volumesFromString", "environmentString",
            "hostname", "user1", "", 128, 256, 42, 102, "bindPorts", true, true, true, "macAddress", "extraHostsString");
    templateBase.setCapabilitiesToAddString("SYS_ADMIN");
    templateBase.setCapabilitiesToDropString("CHOWN");
    templateBase.setSecurityOptsString("seccomp=unconfined");
    final DockerTemplate template = new DockerTemplate(
            templateBase,
            new DockerComputerAttachConnector("jenkins"),
            "labelString", "remoteFs", "10");
    template.setPullStrategy(DockerImagePullStrategy.PULL_NEVER);
    template.setMode(Node.Mode.NORMAL);
    template.setRemoveVolumes(true);
    template.setStopTimeout(42);
    template.setRetentionStrategy(new DockerOnceRetentionStrategy(33));

    DockerCloud cloud = new DockerCloud("docker", new DockerAPI(new DockerServerEndpoint("uri", "credentialsId")),
            Collections.singletonList(template));

    jenkins.getInstance().clouds.replaceBy(Collections.singleton(cloud));

    jenkins.configRoundtrip();

    Assert.assertEquals(cloud, jenkins.getInstance().clouds.get(0));
}
 
Example #29
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
private CredentialsStore getFolderStore(Folder f) {
    Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(f);
    CredentialsStore folderStore = null;
    for (CredentialsStore s : stores) {
        if (s.getProvider() instanceof FolderCredentialsProvider && s.getContext() == f) {
            folderStore = s;
            break;
        }
    }
    return folderStore;
}
 
Example #30
Source File: JiraCloudSiteConfigDescriptorTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
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);
}