Java Code Examples for com.cloudbees.plugins.credentials.CredentialsProvider#lookupStores()

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsProvider#lookupStores() . 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: 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 2
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 3
Source File: UserSSHKeyManager.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the user's CredentialStore
 * @param user user to find a store for
 * @return the credential store or null if not found
 */
private static @CheckForNull CredentialsStore getUserStore(User user){
    for(CredentialsStore s : CredentialsProvider.lookupStores(user)) {
        if(s.hasPermission(CredentialsProvider.CREATE) && s.hasPermission(CredentialsProvider.UPDATE)){
            return s;
        }
    }
    return null;
}
 
Example 4
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Nonnull
public <C extends Credentials> List<C> getCredentials(@Nonnull final Class<C> type,
                                                      @Nullable ItemGroup itemGroup,
                                                      @Nullable
                                                          Authentication authentication,
                                                      @Nonnull List<DomainRequirement> domainRequirements) {
    final List<C> result = new ArrayList<>();
    final FolderPropertyImpl prop = propertyOf(itemGroup);
    if (prop != null && prop.domain.test(domainRequirements)) {
        final User proxyUser = User.get(prop.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)) {
                            for (Credentials c : filter(s.getCredentials(d), withId(prop.getId()))) {
                                if (type.isInstance(c)) {
                                    result.add((C) c);
                                }
                            }
                        }
                    }
                }
            } catch (UsernameNotFoundException ex) {
                logger.warn("BlueOceanCredentialsProvider#getCredentials(): Username attached to credentials can not be found");
            }
        }
    }
    return result;
}
 
Example 5
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private static @CheckForNull CredentialsStore findUserStoreFirstOrNull(User user){
    for(CredentialsStore s: CredentialsProvider.lookupStores(user)){
        if(s.hasPermission(CredentialsProvider.CREATE) && s.hasPermission(CredentialsProvider.UPDATE)){
            return s;
        }
    }
    return null;
}
 
Example 6
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private CredentialsStore getFolderStore(AbstractFolder 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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
Source File: UsernamePasswordBindingTest.java    From credentials-binding-plugin with MIT License 4 votes vote down vote up
@Test
public void theSecretBuildWrapperTracksUsage() throws Exception {
    SystemCredentialsProvider.getInstance().setDomainCredentialsMap(
    Collections.singletonMap(Domain.global(), Collections.<Credentials>emptyList()));
    for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (s.getProvider() instanceof SystemCredentialsProvider.ProviderImpl) {
            store = s;
            break;
        }
    }
    assertThat("The system credentials provider is enabled", store, notNullValue());

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

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

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

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

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

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

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

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

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

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

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