org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials Java Examples

The following examples show how to use org.jenkinsci.plugins.docker.commons.credentials.DockerServerCredentials. 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: ServerEndpointStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test public void configRoundTrip() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate");
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials);
            StepConfigTester sct = new StepConfigTester(story.j);
            Map<String,Object> serverConfig = new TreeMap<String,Object>();
            serverConfig.put("uri", "tcp://host:2375");
            serverConfig.put("credentialsId", serverCredentials.getId());
            Map<String,Object> config = Collections.<String,Object>singletonMap("server", serverConfig);
            ServerEndpointStep step = DescribableHelper.instantiate(ServerEndpointStep.class, config);
            step = sct.configRoundTrip(step);
            DockerServerEndpoint server = step.getServer();
            assertNotNull(server);
            assertEquals("tcp://host:2375", server.getUri());
            assertEquals(serverCredentials.getId(), server.getCredentialsId());
            assertEquals(config, DescribableHelper.uninstantiate(step));
       }
    });
}
 
Example #2
Source File: ServerEndpointStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test public void stepExecutionWithCredentials() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            assumeNotWindows();
            IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate");
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                    "node {\n" +
                            "  withDockerServer(server: [uri: 'tcp://host:1234', credentialsId: 'serverCreds']) {\n" +
                            "    sh 'echo would be connecting to $DOCKER_HOST'\n" +
                            "    sh 'echo DOCKER_TLS_VERIFY=$DOCKER_TLS_VERIFY'\n" +
                            "    sh 'echo DOCKER_CERT_PATH=$DOCKER_CERT_PATH is not empty'\n" +
                            "  }\n" +
                            "}", true));
            WorkflowRun b = story.j.buildAndAssertSuccess(p);
            story.j.assertLogContains("would be connecting to tcp://host:1234", b);
            story.j.assertLogContains("DOCKER_TLS_VERIFY=1", b);
            story.j.assertLogNotContains("DOCKER_CERT_PATH= is not empty", b);
        }
    });
}
 
Example #3
Source File: DockerRule.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
public DockerServerCredentials getDockerServerCredentials() throws IOException {
    final LocalDirectorySSLConfig sslContext = (LocalDirectorySSLConfig) clientConfig.getSSLConfig();

    assertThat("DockerCli must be connected via SSL", sslContext, notNullValue());

    String certPath = sslContext.getDockerCertPath();

    final String keypem = FileUtils.readFileToString(new File(certPath + "/" + "key.pem"));
    final String certpem = FileUtils.readFileToString(new File(certPath + "/" + "cert.pem"));
    final String capem = FileUtils.readFileToString(new File(certPath + "/" + "ca.pem"));

    return new DockerServerCredentials(
            CredentialsScope.GLOBAL, // scope
            null, // name
            null, //desc
            keypem,
            certpem,
            capem
    );
}
 
Example #4
Source File: DockerDaemonFileCredentials.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
private void resolveCredentialsOnSlave() {
    if (nonNull(credentials)) {
        return;
    }
    File credDir = new File(dockerCertPath);
    if (!credDir.isDirectory()) {
        throw new IllegalStateException(dockerCertPath + " isn't directory!");
    }
    try {
        String caPem = FileUtils.readFileToString(new File(credDir, "ca.pem"));
        String keyPem = FileUtils.readFileToString(new File(credDir, "key.pem"));
        String certPem = FileUtils.readFileToString(new File(credDir, "cert.pem"));
        this.credentials = new DockerServerCredentials(null, "remote-docker", null, caPem, keyPem, certPem);
    } catch (IOException ex) {
        LOG.error("", ex);
        Throwables.propagate(ex);
    }
}
 
Example #5
Source File: DockerSwarmCloud.java    From docker-swarm-plugin with MIT License 5 votes vote down vote up
private static SSLConfig toSSlConfig(String credentialsId) {
    if (credentialsId == null)
        return null;

    DockerServerCredentials credentials = firstOrNull(lookupCredentials(DockerServerCredentials.class,
            Jenkins.getInstance(), ACL.SYSTEM, Collections.<DomainRequirement>emptyList()), withId(credentialsId));
    return credentials == null ? null : new DockerServerCredentialsSSLConfig(credentials);
}
 
Example #6
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 #7
Source File: DockerAPI.java    From docker-plugin with MIT License 5 votes vote down vote up
private static SSLConfig toSSlConfig(String credentialsId) {
    if (credentialsId == null) return null;

    DockerServerCredentials credentials = firstOrNull(
        lookupCredentials(
            DockerServerCredentials.class,
            Jenkins.getInstance(),
            ACL.SYSTEM,
            Collections.<DomainRequirement>emptyList()),
        withId(credentialsId));
    return credentials == null ? null :
        new DockerServerCredentialsSSLConfig(credentials);
}
 
Example #8
Source File: DockerDirectoryCredentials.java    From docker-plugin with MIT License 5 votes vote down vote up
private Object readResolve() throws IOException {
    final File f = new File(path);

    return new DockerServerCredentials(getScope(), getId(), getDescription(),
            FileUtils.readFileToString(new File(f, "key.pem")),
            FileUtils.readFileToString(new File(f, "cert.pem")),
            FileUtils.readFileToString(new File(f, "ca.pem")));
}
 
Example #9
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 #10
Source File: ServerKeyMaterialFactory.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
public ServerKeyMaterialFactory(@CheckForNull final DockerServerCredentials credentials) {
    if (credentials != null) {
        key = Secret.toString(credentials.getClientKeySecret());
        cert = credentials.getClientCertificate();
        ca = credentials.getServerCaCertificate();
    } else {
        key = null;
        cert = null;
        ca = null;
    }
}
 
Example #11
Source File: FreestyleTest.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public PrepareCloudCallable(int jenkinsPort, DockerServerCredentials credentials,
                            URI dockerUri, String slaveImage, ConnectorType connectorType) {
    this.connectorType = connectorType;
    assertThat("jenkinsPort", jenkinsPort, notNullValue());
    assertThat("credentials", credentials, notNullValue());
    assertThat("dockerUri", dockerUri, notNullValue());
    assertThat("slaveImage", slaveImage, notNullValue());
    assertThat("connectorType", connectorType, notNullValue());

    this.jenkinsPort = jenkinsPort;
    this.dockerServerCredentials = credentials;
    this.dockerUri = dockerUri;
    this.slaveImage = slaveImage;
}
 
Example #12
Source File: DockerSwarmCloud.java    From docker-swarm-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String value) {
    AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context
            : Jenkins.getInstance());
    if (!ac.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(value);
    }
    return new StandardListBoxModel().includeAs(ACL.SYSTEM, context, DockerServerCredentials.class,
            Collections.<DomainRequirement>emptyList());
}
 
Example #13
Source File: ServerKeyMaterialFactoryFromDockerCredentials.java    From docker-commons-plugin with MIT License 4 votes vote down vote up
public ServerKeyMaterialFactoryFromDockerCredentials() {
    super(KeyMaterialFactory.class, DockerServerCredentials.class);
}
 
Example #14
Source File: ServerKeyMaterialFactoryFromDockerCredentials.java    From docker-commons-plugin with MIT License 4 votes vote down vote up
@NonNull
@Override
public KeyMaterialFactory convert(@NonNull DockerServerCredentials credential) throws AuthenticationTokenException {
    return new ServerKeyMaterialFactory(Secret.toString(credential.getClientKeySecret()), credential.getClientCertificate(), credential.getServerCaCertificate());
}
 
Example #15
Source File: DockerCloudTest.java    From yet-another-docker-plugin with MIT License 4 votes vote down vote up
@Override
public void before() throws Exception {
    final DockerServerCredentials dockerServerCredentials = new DockerServerCredentials(
            CredentialsScope.GLOBAL, // scope
            null, // id
            "description", //desc
            "keypem",
            "certpem",
            "capem"
    );
    SystemCredentialsProvider.getInstance().getCredentials().add(dockerServerCredentials);

    final EnvironmentVariablesNodeProperty.Entry entry = new EnvironmentVariablesNodeProperty.Entry("kee", "vasdfs");
    final EnvironmentVariablesNodeProperty variablesNodeProperty = new EnvironmentVariablesNodeProperty(singletonList(entry));

    final DockerConnector connector = new DockerConnector("http://sdfs.com:234");
    connector.setCredentialsId(dockerServerCredentials.getId());
    connector.setConnectTimeout(1001);
    connector.setReadTimeout(1002);

    final DockerPullImage pullImage = new DockerPullImage();
    pullImage.setCredentialsId("");
    pullImage.setPullStrategy(DockerImagePullStrategy.PULL_ALWAYS);

    final DockerComputerJNLPLauncher launcher = new DockerComputerJNLPLauncher();
    launcher.setLaunchTimeout(100);
    launcher.setUser("jenkins");
    launcher.setJenkinsUrl("http://jenkins");
    launcher.setJvmOpts("-blah");
    launcher.setSlaveOpts("-more");
    launcher.setNoCertificateCheck(true);
    launcher.setNoReconnect(false);

    final DockerCreateContainer createContainer = new DockerCreateContainer();
    createContainer.setBindAllPorts(true);
    createContainer.setBindPorts("234");
    createContainer.setCommand("sdfff");
    createContainer.setCpuShares(3);
    createContainer.setDnsHosts(singletonList("dsf"));
    createContainer.setEnvironment(singletonList("sdf"));
    createContainer.setExtraHosts(singletonList("hoststs"));
    createContainer.setHostname("hostname.local");
    createContainer.setMacAddress("33:44:33:66:66:33");
    createContainer.setMemoryLimit(33333333L);
    createContainer.setPrivileged(false);
    createContainer.setTty(false);
    createContainer.setVolumes(singletonList("ssdf:/sdfsdf/sdf"));
    createContainer.setVolumesFrom(singletonList("sdfsd:/sdfsdf"));
    createContainer.setDevices(singletonList("/dev/sdc:/dev/sdc:rw"));
    createContainer.setCpusetCpus("1");
    createContainer.setCpusetMems("2");
    createContainer.setLinksString("some");
    createContainer.setShmSize(102L);
    createContainer.setRestartPolicy(new DockerContainerRestartPolicy(NO, 0));
    createContainer.setWorkdir("workdir");
    createContainer.setUser("user");
    createContainer.setDockerLabels(singletonList("testlabel=testvalue"));

    final DockerStopContainer stopContainer = new DockerStopContainer();
    stopContainer.setTimeout(100);

    final DockerRemoveContainer removeContainer = new DockerRemoveContainer();
    removeContainer.setForce(true);
    removeContainer.setRemoveVolumes(true);


    final DockerContainerLifecycle containerLifecycle = new DockerContainerLifecycle();
    containerLifecycle.setImage("sdf/sdf:df");
    containerLifecycle.setPullImage(pullImage);
    containerLifecycle.setCreateContainer(createContainer);
    containerLifecycle.setStopContainer(stopContainer);
    containerLifecycle.setRemoveContainer(removeContainer);

    final DockerSlaveTemplate dockerSlaveTemplate = new DockerSlaveTemplate();
    dockerSlaveTemplate.setDockerContainerLifecycle(containerLifecycle);
    dockerSlaveTemplate.setLabelString("some-label");
    dockerSlaveTemplate.setLauncher(launcher);
    dockerSlaveTemplate.setMaxCapacity(233);
    dockerSlaveTemplate.setMode(Node.Mode.EXCLUSIVE);
    dockerSlaveTemplate.setNodeProperties(singletonList(variablesNodeProperty));
    dockerSlaveTemplate.setRemoteFs("/remotefs");
    dockerSlaveTemplate.setNumExecutors(1); // need to be verified with other retention strategy
    dockerSlaveTemplate.setRetentionStrategy(new DockerOnceRetentionStrategy(30));

    final ArrayList<DockerSlaveTemplate> dockerSlaveTemplates = new ArrayList<>();
    dockerSlaveTemplates.add(dockerSlaveTemplate);
    before = new DockerCloud("docker-cloud", dockerSlaveTemplates, 17, connector);

    j.getInstance().clouds.add(before);
    j.getInstance().save();

    j.configRoundtrip();

    after = (DockerCloud) j.getInstance().getCloud("docker-cloud");
}
 
Example #16
Source File: ServerEndpointStepTest.java    From docker-workflow-plugin with MIT License 4 votes vote down vote up
@Test public void stepExecutionWithCredentialsAndQueueItemAuthenticator() throws Exception {
    assumeNotWindows();
    story.then(r -> {
        story.j.getInstance().setSecurityRealm(story.j.createDummySecurityRealm());
        MockAuthorizationStrategy auth = new MockAuthorizationStrategy()
                .grant(Jenkins.READ).everywhere().to("alice", "bob")
                .grant(Computer.BUILD).everywhere().to("alice", "bob")
                // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById
                // uses when determining whether to include item-scope credentials in the search.
                .grant(Item.CONFIGURE).everywhere().to("alice");
        story.j.getInstance().setAuthorizationStrategy(auth);

        IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate");
        CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials);

        String script = "node {\n" +
                "  withDockerServer(server: [uri: 'tcp://host:1234', credentialsId: 'serverCreds']) {\n" +
                "    sh 'echo would be connecting to $DOCKER_HOST'\n" +
                "    sh 'echo DOCKER_TLS_VERIFY=$DOCKER_TLS_VERIFY'\n" +
                "    sh 'echo DOCKER_CERT_PATH=$DOCKER_CERT_PATH is not empty'\n" +
                "  }\n" +
                "}";
        WorkflowJob p1 = story.j.jenkins.createProject(WorkflowJob.class, "prj1");
        p1.setDefinition(new CpsFlowDefinition(script, true));
        WorkflowJob p2 = story.j.jenkins.createProject(WorkflowJob.class, "prj2");
        p2.setDefinition(new CpsFlowDefinition(script, true));

        Map<String, Authentication> jobsToAuths = new HashMap<>();
        jobsToAuths.put(p1.getFullName(), User.getById("alice", true).impersonate());
        jobsToAuths.put(p2.getFullName(), User.getById("bob", true).impersonate());
        QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(jobsToAuths));

        // Alice has Credentials.USE_ITEM permission and should be able to use the credential.
        WorkflowRun b1 = story.j.buildAndAssertSuccess(p1);
        story.j.assertLogContains("would be connecting to tcp://host:1234", b1);
        story.j.assertLogContains("DOCKER_TLS_VERIFY=1", b1);
        story.j.assertLogNotContains("DOCKER_CERT_PATH= is not empty", b1);

        // Bob does not have Credentials.USE_ITEM permission and should not be able to use the credential.
        WorkflowRun b2 = story.j.buildAndAssertSuccess(p2);
        story.j.assertLogContains("would be connecting to tcp://host:1234", b2);
        story.j.assertLogContains("DOCKER_TLS_VERIFY=\n", b2);
        story.j.assertLogContains("DOCKER_CERT_PATH= is not empty", b2);
    });
}
 
Example #17
Source File: DockerServerCredentialsSSLConfig.java    From docker-swarm-plugin with MIT License 4 votes vote down vote up
public DockerServerCredentialsSSLConfig(DockerServerCredentials credentials) {
    this.credentials = credentials;
}
 
Example #18
Source File: DockerServerCredentialsSSLConfig.java    From docker-plugin with MIT License 4 votes vote down vote up
public DockerServerCredentialsSSLConfig(DockerServerCredentials credentials) {
    this.credentials = credentials;
}