com.cloudbees.plugins.credentials.domains.Domain Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.domains.Domain. 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: SaveableChangeListenerTest.java    From audit-log-plugin with MIT License 6 votes vote down vote up
@Issue("ISSUE-35")
@Test
public void testOnCredentialsUsage() throws Exception {
    UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob","secret");
    CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), credentials);
    JenkinsRule.WebClient wc = j.createWebClient();
    FreeStyleProject job = j.createFreeStyleProject();
    job.addProperty(new ParametersDefinitionProperty(
            new CredentialsParameterDefinition(
                "SECRET",
                "The secret",
                "secret-id",
                Credentials.class.getName(),
                false
            )));
    job.getBuildersList().add(new CaptureEnvironmentBuilder());
    job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))).get();

    List<LogEvent> events = app.getEvents();
    assertThat(events).hasSize(4);
    assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).containsSequence("createItem", "buildStart", "useCredentials", "buildFinish");
}
 
Example #3
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 #4
Source File: ZipFileBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-30941")
@Test
public void cleanUpSucceeds() throws Exception {
    /** Issue was just present on Linux not windows - but the test will run on both */

    final String credentialsId = "zipfile";

    FileCredentialsImpl fc = new FileCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "Just a zip file", "a.zip", SecretBytes.fromBytes(IOUtils.toByteArray(ZipFileBindingTest.class.getResource("a.zip"))));
    CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), fc);

    final String contents = "Test of ZipFileBinding\n";
    
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(""
                                          + "node {\n"
                                          + "  withCredentials([[$class: 'ZipFileBinding', credentialsId: '"+ credentialsId +"', variable: 'ziploc']]) {\n"
                                          + "    echo readFile(encoding: 'UTF-8', file: \"${env.ziploc}/dir/testfile.txt\")\n"
                                          + "  }\n"
                                          + "}\n"
                                          , true));

    WorkflowRun run = p.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(run);
    j.assertLogContains(contents, run);
}
 
Example #5
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 #6
Source File: UsernamePasswordBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Test public void basics() throws Exception {
    String username = "bob";
    String password = "s3cr3t";
    UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "sample", username, password);
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
    FreeStyleProject p = r.createFreeStyleProject();
    p.getBuildWrappersList().add(new SecretBuildWrapper(Collections.<Binding<?>>singletonList(new UsernamePasswordBinding("AUTH", c.getId()))));
    p.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %AUTH% > auth.txt") : new Shell("echo $AUTH > auth.txt"));
    r.configRoundtrip(p);
    SecretBuildWrapper wrapper = p.getBuildWrappersList().get(SecretBuildWrapper.class);
    assertNotNull(wrapper);
    List<? extends MultiBinding<?>> bindings = wrapper.getBindings();
    assertEquals(1, bindings.size());
    MultiBinding<?> binding = bindings.get(0);
    assertEquals(c.getId(), binding.getCredentialsId());
    assertEquals(UsernamePasswordBinding.class, binding.getClass());
    assertEquals("AUTH", ((UsernamePasswordBinding) binding).getVariable());
    FreeStyleBuild b = r.buildAndAssertSuccess(p);
    r.assertLogNotContains(password, b);
    assertEquals(username + ':' + password, b.getWorkspace().child("auth.txt").readToString().trim());
    assertEquals("[AUTH]", b.getSensitiveBuildVariables().toString());
}
 
Example #7
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 #8
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 #9
Source File: BuildStatusConfigTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Verifies doFillCredentialsIdItems adds values from the credentials store
 * @throws IOException 
 */
@Test
public void testDoFillCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
    StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
    CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);

    BuildStatusConfig instance = new BuildStatusConfig();
    instance.setCredentialsId(testCredentials);
    
    ListBoxModel model = instance.doFillCredentialsIdItems(testCredentials);
    
    assertEquals(2, model.size());
    ListBoxModel.Option item1 = model.get(0);
    assertEquals("", item1.value);
    assertEquals("- none -", item1.name);

    ListBoxModel.Option item2 = model.get(1);
    assertEquals(testCredentials, item2.value);
}
 
Example #10
Source File: BuildStatusConfigTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Verifies doFillCredentialsIdItems adds values from the credentials store
 * @throws IOException
 */
@Test
public void testDoFillHttpCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
    StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
    CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);

    BuildStatusConfig instance = new BuildStatusConfig();
    instance.setCredentialsId(testCredentials);

    ListBoxModel model = instance.doFillHttpCredentialsIdItems(testCredentials);

    assertEquals(2, model.size());
    ListBoxModel.Option item1 = model.get(0);
    assertEquals("", item1.value);
    assertEquals("- none -", item1.name);

    ListBoxModel.Option item2 = model.get(1);
    assertEquals(testCredentials, item2.value);
}
 
Example #11
Source File: BitbucketServerScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private MultiBranchProject mockMbp(String credentialId, User user) {
    MultiBranchProject mbp = mock(MultiBranchProject.class);
    when(mbp.getName()).thenReturn("pipeline1");
    when(mbp.getParent()).thenReturn(j.jenkins);
    BitbucketSCMSource scmSource = mock(BitbucketSCMSource.class);
    when(scmSource.getServerUrl()).thenReturn(apiUrl);
    when(scmSource.getCredentialsId()).thenReturn(credentialId);
    when(scmSource.getRepoOwner()).thenReturn("TESTP");
    when(scmSource.getRepository()).thenReturn("pipeline-demo-test");
    when(mbp.getSCMSources()).thenReturn(Lists.<SCMSource>newArrayList(scmSource));

    //mock blueocean credential provider stuff
    BlueOceanCredentialsProvider.FolderPropertyImpl folderProperty = mock(BlueOceanCredentialsProvider.FolderPropertyImpl.class);
    DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor> properties = new DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor>(mbp);
    properties.add(new BlueOceanCredentialsProvider.FolderPropertyImpl(
            user.getId(), credentialId,
            BlueOceanCredentialsProvider.createDomain(apiUrl)
    ));
    Domain domain = mock(Domain.class);
    when(domain.getName()).thenReturn(BitbucketServerScm.DOMAIN_NAME);
    when(folderProperty.getDomain()).thenReturn(domain);

    when(mbp.getProperties()).thenReturn(properties);
    return mbp;
}
 
Example #12
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 #13
Source File: SecretBuildWrapperTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("SECURITY-1374")
@Test public void maskingPostBuild() throws Exception {
    String credentialsId = "creds_1";
    String password = "p4$$";
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample1", Secret.fromString(password));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Collections.singletonList(new StringBinding("PASS_1", credentialsId)));

    FreeStyleProject f = r.createFreeStyleProject();

    f.setConcurrentBuild(true);
    f.getBuildWrappersList().add(wrapper);
    Publisher publisher = new PasswordPublisher(password);
    f.getPublishersList().add(publisher);

    FreeStyleBuild b = r.buildAndAssertSuccess(f);
    r.assertLogNotContains(password, b);
    r.assertLogContains("****", b);
}
 
Example #14
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-42999")
@Test
public void widerRequiredContext() throws Exception {
    final String credentialsId = "creds";
    final String credsFile = "credsFile";
    final String credsContent = "s3cr3t";
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            FileCredentialsImpl c = new FileCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", credsFile, SecretBytes.fromBytes(credsContent.getBytes()));
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(""
                    + "withCredentials([file(variable: 'targetFile', credentialsId: '" + credentialsId + "')]) {\n"
                    + "  echo 'We should fail before getting here'\n"
                    + "}", true));
            WorkflowRun b = story.j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0));
            story.j.assertLogNotContains("We should fail before getting here", b);
            story.j.assertLogContains("Required context class hudson.FilePath is missing", b);
            story.j.assertLogContains("Perhaps you forgot to surround the code with a step that provides this, such as: node", b);
        }
    });
}
 
Example #15
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 #16
Source File: CertificateMultiBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Test
public void basicsPipeline() throws Exception {
	// create the Credentials
	String alias = "androiddebugkey";
	String password = "android";
	StandardCertificateCredentials c = new CertificateCredentialsImpl(CredentialsScope.GLOBAL, "my-certificate", alias,
			password, new CertificateCredentialsImpl.FileOnMasterKeyStoreSource(certificate.getAbsolutePath()));
	CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
	// create the Pipeline job
	WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
	String pipelineScript = IOUtils.toString(getTestResourceInputStream("basicsPipeline-Jenkinsfile"));
	p.setDefinition(new CpsFlowDefinition(pipelineScript, true));
	// copy resources into workspace
	FilePath workspace = r.jenkins.getWorkspaceFor(p);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.bat", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.bat", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.sh", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.sh", 0755);
	// execute the pipeline
	WorkflowRun b = p.scheduleBuild2(0).waitForStart();
	r.waitForCompletion(b);
	r.assertBuildStatusSuccess(b);
}
 
Example #17
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 #18
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 #19
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 #20
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 #21
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-27486")
@Test public void masking() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            String credentialsId = "creds";
            String secret = "s3cr3t";
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)));
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(""
                    + "node {\n"
                    + "  withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'SECRET')]) {\n"
                    // forgot set +x, ran /usr/bin/env, etc.
                    + "    if (isUnix()) {sh 'echo $SECRET > oops'} else {bat 'echo %SECRET% > oops'}\n"
                    + "  }\n"
                    + "}", true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get());
            story.j.assertLogNotContains(secret, b);
            story.j.assertLogContains("echo ****", b);
        }
    });
}
 
Example #22
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 #23
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test
public void grandParentOverride() throws Exception {
    Folder grandParent = j.createProject(Folder.class);
    getFolderStore(grandParent).addCredentials(Domain.global(), grandParentCred);
    grandParent.addProperty(new FolderConfig("parent_docker", "https://parent.registry", grandParentCred.getId()));
    Folder parent = grandParent.createProject(Folder.class, "testParent"); //Can be static since grandParent should be unique
    getFolderStore(parent).addCredentials(Domain.global(), folderCred);
    parent.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));

    expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
            .inFolder(parent)
            .runFromRepo(false)
            .logContains("Docker Label is: folder_docker",
                    "Registry URL is: https://folder.registry",
                    "Registry Creds ID is: " + folderCred.getId())
            .logNotContains("Docker Label is: parent_docker",
                    "Registry URL is: https://parent.registry",
                    "Registry Creds ID is: " + grandParentCred.getId()).go();
}
 
Example #24
Source File: VaultConfigurationIT.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldDealWithTokenBasedCredential() throws Exception {
    VaultBuildWrapper vaultBuildWrapper = new VaultBuildWrapper(standardSecrets());
    VaultAccessor mockAccessor = mockVaultAccessor(GLOBAL_ENGINE_VERSION_2);
    vaultBuildWrapper.setVaultAccessor(mockAccessor);

    VaultCredential credential = new VaultTokenCredential(CredentialsScope.GLOBAL, "token-1",
        "description", Secret.fromString("test-token"));
    SystemCredentialsProvider.getInstance().setDomainCredentialsMap(
        Collections.singletonMap(Domain.global(), Collections.singletonList(credential)));

    this.project.getBuildWrappersList().add(vaultBuildWrapper);

    VaultConfiguration vaultConfig = new VaultConfiguration();
    vaultConfig.setVaultUrl("http://job-vault-url.com");
    vaultConfig.setVaultCredentialId("token-1");
    vaultConfig.setFailIfNotFound(false);
    vaultConfig.setVaultNamespace("mynamespace");
    vaultConfig.setTimeout(TIMEOUT);
    vaultBuildWrapper.setConfiguration(vaultConfig);
    this.project.getBuildersList().add(echoSecret());

    FreeStyleBuild build = this.project.scheduleBuild2(0).get();

    assertThat(vaultBuildWrapper.getConfiguration().getVaultUrl(),
        is("http://job-vault-url.com"));
    assertThat(vaultBuildWrapper.getConfiguration().getVaultCredentialId(), is("token-1"));

    jenkins.assertBuildStatus(Result.SUCCESS, build);

    VaultConfig config = new VaultConfig().address("http://job-vault-url.com");
    mockAccessor.setConfig(config);
    mockAccessor.setCredential(credential);
    verify(mockAccessor, times(1)).init();
    verify(mockAccessor, times(1)).read("secret/path1", GLOBAL_ENGINE_VERSION_2);
    jenkins.assertLogContains("echo ****", build);
    jenkins.assertLogNotContains("some-secret", build);
}
 
Example #25
Source File: VaultTokenCredentialBindingIT.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldInjectCredentialsForToken() {
    final String credentialsId = "creds";
    final String vaultAddr = "https://localhost:8200";
    final String token = "fakeToken";
    final String jobId = "testJob";
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            VaultTokenCredential c = new VaultTokenCredential(CredentialsScope.GLOBAL,
                credentialsId, "fake description", Secret.fromString(token));
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next()
                .addCredentials(Domain.global(), c);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, jobId);
            p.setDefinition(new CpsFlowDefinition(""
                + "node {\n"
                + "  withCredentials([[$class: 'VaultTokenCredentialBinding', addrVariable: 'VAULT_ADDR', tokenVariable: 'VAULT_TOKEN', credentialsId: '"
                + credentialsId + "', vaultAddr: '" + vaultAddr + "']]) {\n"
                + "      " + getShellString() + " 'echo " + getVariable("VAULT_ADDR") + ":"
                + getVariable("VAULT_TOKEN") + " > script'\n"
                + "  }\n"
                + "}", true));
            WorkflowRun b = p.scheduleBuild2(0).waitForStart();
            story.j.assertBuildStatus(Result.SUCCESS, story.j.waitForCompletion(b));
            story.j.assertLogNotContains(token, b);
            FilePath script = story.j.jenkins.getWorkspaceFor(p).child("script");
            assertEquals(vaultAddr + ":" + token, script.readToString().trim());
        }
    });
}
 
Example #26
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 #27
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 #28
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 #29
Source File: DollarSecretPatternFactoryTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-24805")
@Test
public void maskingFreeStyleSecrets() throws Exception {
    String firstCredentialsId = "creds_1";
    String firstPassword = "a$build";
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, firstCredentialsId, "sample1", Secret.fromString(firstPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    String secondCredentialsId = "creds_2";
    String secondPassword = "a$$b";
    StringCredentialsImpl secondCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, secondCredentialsId, "sample2", Secret.fromString(secondPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), secondCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding("PASS_1", firstCredentialsId),
            new StringBinding("PASS_2", secondCredentialsId)));

    FreeStyleProject project = r.createFreeStyleProject();

    project.setConcurrentBuild(true);
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo \"$PASS_1\""));
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_2%") : new Shell("echo \"$PASS_2\""));
    project.getBuildersList().add(new Maven("$PASS_1 $PASS_2", "default"));
    project.getBuildWrappersList().add(wrapper);

    r.configRoundtrip((Item)project);

    QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0);
    FreeStyleBuild build = future.get();
    r.assertLogNotContains(firstPassword, build);
    r.assertLogNotContains(firstPassword.replace("$", "$$"), build);
    r.assertLogNotContains(secondPassword, build);
    r.assertLogNotContains(secondPassword.replace("$", "$$"), build);
    r.assertLogContains("****", build);
}
 
Example #30
Source File: DockerServerDomainSpecificationTest.java    From docker-commons-plugin with MIT License 5 votes vote down vote up
public Domain byName(List<Domain> domains, String name) {
    for (Domain d: domains) {
        if (name.equals(d.getName())) {
            return d;
        }
    }
    return null;
}