Java Code Examples for com.cloudbees.plugins.credentials.CredentialsMatchers#firstOrNull()

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsMatchers#firstOrNull() . 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: VaultBuildWrapper.java    From hashicorp-vault-plugin with MIT License 6 votes vote down vote up
protected VaultCredential retrieveVaultCredentials(Run build) {
    String id = getConfiguration().getVaultCredentialId();
    if (StringUtils.isBlank(id)) {
        throw new VaultPluginException(
            "The credential id was not configured - please specify the credentials to use.");
    }
    List<VaultCredential> credentials = CredentialsProvider
        .lookupCredentials(VaultCredential.class, build.getParent(), ACL.SYSTEM,
            Collections.emptyList());
    VaultCredential credential = CredentialsMatchers
        .firstOrNull(credentials, new IdMatcher(id));

    if (credential == null) {
        throw new CredentialsUnavailableException(id);
    }

    return credential;
}
 
Example 2
Source File: DockerServerEndpoint.java    From docker-commons-plugin with MIT License 6 votes vote down vote up
/**
 * Makes the key materials available locally and returns {@link KeyMaterialFactory} that gives you the parameters
 * needed to access it.
 * 
 * @deprecated Call {@link #newKeyMaterialFactory(Run, VirtualChannel)}
 */
@Deprecated
public KeyMaterialFactory newKeyMaterialFactory(@Nonnull Item context, @Nonnull VirtualChannel target) throws IOException, InterruptedException {
    // as a build step, your access to credentials are constrained by what the build
    // can access, hence Jenkins.getAuthentication()
    DockerServerCredentials creds=null;
    if (credentialsId!=null) {
        List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(getUri()).build();
        domainRequirements.add(new DockerServerDomainRequirement());
        creds = CredentialsMatchers.firstOrNull(
                CredentialsProvider.lookupCredentials(
                        DockerServerCredentials.class, context, Jenkins.getAuthentication(),
                        domainRequirements),
                CredentialsMatchers.withId(credentialsId)
        );
    }

    // the directory needs to be outside workspace to avoid prying eyes
    FilePath dotDocker = dotDocker(target);
    dotDocker.mkdirs();
    // ServerKeyMaterialFactory.materialize creates a random subdir if one is needed:
    return newKeyMaterialFactory(dotDocker, creds);
}
 
Example 3
Source File: DockerSwarmComputerLauncher.java    From docker-swarm-plugin with MIT License 6 votes vote down vote up
private void setAuthHeaders(DockerSwarmAgentTemplate dockerSwarmAgentTemplate, ServiceSpec crReq) {
    String credentialsId = dockerSwarmAgentTemplate.getPullCredentialsId();

    // Exit if no credentials are provided
    if (credentialsId == null || credentialsId.length() == 0) {
        return;
    }

    // Get the credentials
    StandardUsernamePasswordCredentials credentials = CredentialsMatchers
            .firstOrNull(lookupCredentials(StandardUsernamePasswordCredentials.class, (Item) null, ACL.SYSTEM,
                    Collections.<DomainRequirement>emptyList()), CredentialsMatchers.withId(credentialsId));

    // Add the credentials to the header
    crReq.setAuthHeader(credentials.getUsername(), credentials.getPassword().getPlainText(),
            dockerSwarmAgentTemplate.getEmail(), dockerSwarmAgentTemplate.getServerAddress());
}
 
Example 4
Source File: AWSClientFactory.java    From awseb-deployment-plugin with Apache License 2.0 6 votes vote down vote up
private static AmazonWebServicesCredentials lookupNamedCredential(String credentialsId)
        throws CredentialNotFoundException {
    final Jenkins jenkins = Jenkins.getInstanceOrNull();

    if (jenkins == null)
        throw new RuntimeException("Missing Jenkins Instance");

    List<AmazonWebServicesCredentials> credentialList =
            CredentialsProvider.lookupCredentials(
                    AmazonWebServicesCredentials.class, jenkins, ACL.SYSTEM,
                    Collections.<DomainRequirement>emptyList());

    AmazonWebServicesCredentials cred =
            CredentialsMatchers.firstOrNull(credentialList,
                    CredentialsMatchers.allOf(
                            CredentialsMatchers.withId(credentialsId)));

    if (cred == null) {
        throw new CredentialNotFoundException(credentialsId);
    }
    return cred;
}
 
Example 5
Source File: AxivionSuite.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
private UsernamePasswordCredentials withValidCredentials() {
    final List<StandardUsernamePasswordCredentials> all =
            CredentialsProvider.lookupCredentials(
                    StandardUsernamePasswordCredentials.class,
                    (Item) null,
                    ACL.SYSTEM,
                    Collections.emptyList());

    StandardUsernamePasswordCredentials jenkinsCredentials =
            CredentialsMatchers.firstOrNull(all,
                    CredentialsMatchers.withId(credentialsId));

    if (jenkinsCredentials == null) {
        throw new ParsingException("Could not find the credentials for " + credentialsId);
    }

    return new UsernamePasswordCredentials(
            jenkinsCredentials.getUsername(),
            Secret.toString(jenkinsCredentials.getPassword()));
}
 
Example 6
Source File: VaultHelper.java    From hashicorp-vault-plugin with MIT License 6 votes vote down vote up
private static VaultCredential retrieveVaultCredentials(String id) {
    if (StringUtils.isBlank(id)) {
        throw new VaultPluginException(
            "The credential id was not configured - please specify the credentials to use.");
    } else {
        LOGGER.log(Level.INFO, "Retrieving vault credential ID : " + id);
    }
    List<VaultCredential> credentials = CredentialsProvider
        .lookupCredentials(VaultCredential.class,
            Jenkins.get(),
            ACL.SYSTEM,
            Collections.<DomainRequirement>emptyList());
    VaultCredential credential = CredentialsMatchers
        .firstOrNull(credentials, new IdMatcher(id));

    if (credential == null) {
        throw new CredentialsUnavailableException(id);
    }

    return credential;
}
 
Example 7
Source File: Connector.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Resolves the specified scan credentials in the specified context for use against the specified API endpoint.
 *
 * @param context           the context.
 * @param apiUri            the API endpoint.
 * @param scanCredentialsId the credentials to resolve.
 * @return the {@link StandardCredentials} or {@code null}
 */
@CheckForNull
public static StandardCredentials lookupScanCredentials(@CheckForNull Item context,
                                                        @CheckForNull String apiUri,
                                                        @CheckForNull String scanCredentialsId) {
    if (Util.fixEmpty(scanCredentialsId) == null) {
        return null;
    } else {
        return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                StandardUsernameCredentials.class,
                context,
                context instanceof Queue.Task
                        ? ((Queue.Task) context).getDefaultAuthentication()
                        : ACL.SYSTEM,
                githubDomainRequirements(apiUri)
            ),
            CredentialsMatchers.allOf(CredentialsMatchers.withId(scanCredentialsId), githubScanCredentialsMatcher())
        );
    }
}
 
Example 8
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public static @CheckForNull <C extends Credentials> C findCredential(@Nonnull String credentialId, @Nonnull Class<C> type, @Nonnull DomainRequirement... domainRequirements){
    return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    type,
                    Jenkins.getInstance(),
                    Jenkins.getAuthentication(),
                    domainRequirements),
            CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialId))
    );
}
 
Example 9
Source File: GitLabServer.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * Looks up for Personal Access Token
 *
 * @return {@link PersonalAccessToken}
 */
public PersonalAccessToken getCredentials() {
    Jenkins jenkins = Jenkins.get();
    jenkins.checkPermission(CredentialsProvider.USE_OWN);
    return StringUtils.isBlank(credentialsId) ? null : CredentialsMatchers.firstOrNull(
        lookupCredentials(
            PersonalAccessToken.class,
            jenkins,
            ACL.SYSTEM,
            fromUri(defaultIfBlank(serverUrl, GITLAB_SERVER_URL)).build()
        ), withId(credentialsId));
}
 
Example 10
Source File: AwsCredentialsHelper.java    From aws-codecommit-trigger-plugin with Apache License 2.0 5 votes vote down vote up
@CheckForNull
public static <T extends Credentials> T getCredentials(Class<T> clz, @Nullable String credentialsId) {
    if (StringUtils.isBlank(credentialsId)) {
        return null;
    }

    return CredentialsMatchers.firstOrNull(
        CredentialsProvider.lookupCredentials(clz, (Item) null, ACL.SYSTEM, null, null),
        CredentialsMatchers.withId(credentialsId)
    );
}
 
Example 11
Source File: MarathonBuilderUtils.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Get the credentials identified by the given id from the Jenkins credential store.
 *
 * @param <T>              credential type
 * @param credentialsId    The id for the credentials
 * @param credentialsClass The class of credentials to return
 * @return Jenkins credentials
 */
public static <T extends Credentials> T getJenkinsCredentials(final String credentialsId, final Class<T> credentialsClass) {
    if (StringUtils.isEmpty(credentialsId))
        return null;
    return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(credentialsClass,
                    Jenkins.getInstance(), ACL.SYSTEM, Collections.<DomainRequirement>emptyList()),
            CredentialsMatchers.withId(credentialsId)
    );
}
 
Example 12
Source File: CredentialsUtil.java    From service-now-plugin with MIT License 5 votes vote down vote up
public static Credentials findCredentials(String url, String credentialId, VaultConfiguration vaultConfiguration, Item project) {
    Credentials credentials = null;
    if(vaultConfiguration != null) {
        credentials = CredentialsMatchers.firstOrNull(
                getCredentials(url, VaultAppRoleCredential.class,project),
                CredentialsMatchers.withId(credentialId));
    }
    if(credentials == null) {
        credentials = CredentialsMatchers.firstOrNull(
                getCredentials(url, StandardUsernamePasswordCredentials.class,project),
                CredentialsMatchers.withId(credentialId));
    }
    return credentials;
}
 
Example 13
Source File: GithubNotificationConfig.java    From github-autostatus-plugin with MIT License 5 votes vote down vote up
private static <T extends Credentials> T getCredentials(@Nonnull Class<T> type, @Nonnull String credentialsId, Item context) {
    return CredentialsMatchers.firstOrNull(lookupCredentials(
            type, context, ACL.SYSTEM,
            Collections.<DomainRequirement>emptyList()), CredentialsMatchers.allOf(
            CredentialsMatchers.withId(credentialsId),
            CredentialsMatchers.instanceOf(type)));
}
 
Example 14
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
static StandardCredentials getCredentials(ItemGroup owner, String uri, String credentialId){
    StandardCredentials standardCredentials =  CredentialsUtils.findCredential(credentialId, StandardCredentials.class, new BlueOceanDomainRequirement());
    if(standardCredentials == null){
        standardCredentials = CredentialsMatchers
                .firstOrNull(
                        CredentialsProvider.lookupCredentials(StandardCredentials.class, owner,
                                ACL.SYSTEM, URIRequirementBuilder.fromUri(uri).build()),
                        CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialId),
                                GitClient.CREDENTIALS_MATCHER));
    }

    return standardCredentials;
}
 
Example 15
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
private static <T extends Credentials> T getCredentials(@Nonnull Class<T> type, @Nonnull String credentialsId, Item context) {
    return CredentialsMatchers.firstOrNull(lookupCredentials(
            type, context, ACL.SYSTEM,
            Collections.<DomainRequirement>emptyList()), CredentialsMatchers.allOf(
            CredentialsMatchers.withId(credentialsId),
            CredentialsMatchers.instanceOf(type)));
}
 
Example 16
Source File: GitLabProject.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private <T extends StandardCredentials> T credentials(AbstractGitSCMSource source, @Nonnull Class<T> type) {
    String credentialsId = source.getCredentialsId();
    if (credentialsId == null) {
        return null;
    }

    return CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(
            type, source.getOwner(), ACL.SYSTEM,
            Collections.<DomainRequirement>emptyList()), CredentialsMatchers.allOf(
            CredentialsMatchers.withId(credentialsId),
            CredentialsMatchers.instanceOf(type)));
}
 
Example 17
Source File: DockerServerCredentialsTest.java    From docker-commons-plugin with MIT License 4 votes vote down vote up
private IdCredentials findFirstWithId(String credentialsId) {
    return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(IdCredentials.class, j.getInstance(), ACL.SYSTEM, new DockerServerDomainRequirement()),
            CredentialsMatchers.withId(credentialsId));
}
 
Example 18
Source File: GiteaSCMBuilder.java    From gitea-plugin with MIT License 4 votes vote down vote up
/**
 * Returns a {@link UriTemplate} for checkout according to credentials configuration.
 * Expects the parameters {@code owner} and {@code repository} to be populated before expansion.
 *
 * @param context       the context within which to resolve the credentials.
 * @param serverUrl     the server url
 * @param sshRemote     any valid SSH remote URL for the server.
 * @param credentialsId the credentials.
 * @return a {@link UriTemplate}
 */
public static UriTemplate checkoutUriTemplate(@CheckForNull Item context,
                                              @NonNull String serverUrl,
                                              @CheckForNull String sshRemote,
                                              @CheckForNull String credentialsId) {
    if (credentialsId != null && sshRemote != null) {
        URIRequirementBuilder builder = URIRequirementBuilder.create();
        URI serverUri = URI.create(serverUrl);
        if (serverUri.getHost() != null) {
            builder.withHostname(serverUri.getHost());
        }
        StandardCredentials credentials = CredentialsMatchers.firstOrNull(
                CredentialsProvider.lookupCredentials(
                        StandardCredentials.class,
                        context,
                        context instanceof Queue.Task
                                ? ((Queue.Task) context).getDefaultAuthentication()
                                : ACL.SYSTEM,
                        builder.build()
                ),
                CredentialsMatchers.allOf(
                        CredentialsMatchers.withId(credentialsId),
                        CredentialsMatchers.instanceOf(StandardCredentials.class)
                )
        );
        if (credentials instanceof SSHUserPrivateKey) {
            int atIndex = sshRemote.indexOf('@');
            int colonIndex = sshRemote.indexOf(':');
            if (atIndex != -1 && colonIndex != -1 && atIndex < colonIndex) {
                // this is an scp style url, we will translate to ssh style
                return UriTemplate.buildFromTemplate("ssh://"+sshRemote.substring(0, colonIndex))
                        .path(UriTemplateBuilder.var("owner"))
                        .path(UriTemplateBuilder.var("repository"))
                        .literal(".git")
                        .build();
            }
            URI sshUri = URI.create(sshRemote);
            return UriTemplate.buildFromTemplate(
                    "ssh://git@" + sshUri.getHost() + (sshUri.getPort() != 22 && sshUri.getPort() != -1 ? ":" + sshUri.getPort() : "")
            )
                    .path(UriTemplateBuilder.var("owner"))
                    .path(UriTemplateBuilder.var("repository"))
                    .literal(".git")
                    .build();
        }
        if (credentials instanceof PersonalAccessToken) {
            try {
                // TODO is there a way we can get git plugin to redact the secret?
                URI tokenUri = new URI(
                        serverUri.getScheme(),
                        ((PersonalAccessToken) credentials).getToken().getPlainText(),
                        serverUri.getHost(),
                        serverUri.getPort(),
                        serverUri.getPath(),
                        serverUri.getQuery(),
                        serverUri.getFragment()
                );
                return UriTemplate.buildFromTemplate(tokenUri.toASCIIString())
                        .path(UriTemplateBuilder.var("owner"))
                        .path(UriTemplateBuilder.var("repository"))
                        .literal(".git")
                        .build();
            } catch (URISyntaxException e) {
                // ok we are at the end of the road
            }
        }
    }
    return UriTemplate.buildFromTemplate(serverUrl)
            .path(UriTemplateBuilder.var("owner"))
            .path(UriTemplateBuilder.var("repository"))
            .literal(".git")
            .build();
}
 
Example 19
Source File: GiteaSCMSource.java    From gitea-plugin with MIT License 4 votes vote down vote up
public ListBoxModel doFillRepositoryItems(@AncestorInPath SCMSourceOwner context,
                                          @QueryParameter String serverUrl,
                                          @QueryParameter String credentialsId,
                                          @QueryParameter String repoOwner,
                                          @QueryParameter String repository) throws IOException,
        InterruptedException {
    ListBoxModel result = new ListBoxModel();
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            result.add(repository);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you want the list
            result.add(repository);
            return result;
        }
    }
    if (StringUtils.isBlank(repoOwner)) {
        result.add(repository);
        return result;
    }
    GiteaServer server = GiteaServers.get().findServer(serverUrl);
    if (server == null) {
        // you can only get the list for registered servers
        result.add(repository);
        return result;
    }
    StandardCredentials credentials = CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    context,
                    context instanceof Queue.Task
                            ? ((Queue.Task) context).getDefaultAuthentication()
                            : ACL.SYSTEM,
                    URIRequirementBuilder.fromUri(serverUrl).build()
            ),
            CredentialsMatchers.allOf(
                    AuthenticationTokens.matcher(GiteaAuth.class),
                    CredentialsMatchers.withId(credentialsId)
            )
    );
    try (GiteaConnection c = Gitea.server(serverUrl)
            .as(AuthenticationTokens.convert(GiteaAuth.class, credentials))
            .open()) {
        GiteaOwner owner = c.fetchOwner(repoOwner);
        List<GiteaRepository> repositories = c.fetchRepositories(owner);
        for (GiteaRepository r : repositories) {
            result.add(r.getName());
        }
        return result;
    } catch (IOException e) {
        // TODO once enhanced <f:select> that can handle error responses, just throw
        LOGGER.log(Level.FINE, "Could not populate repositories", e);
        if (result.isEmpty()) {
            result.add(repository);
        }
        return result;
    }
}
 
Example 20
Source File: AWSClientFactory.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 4 votes vote down vote up
public AWSClientFactory(String credentialsType, String credentialsId, String proxyHost, String proxyPort, String awsAccessKey, Secret awsSecretKey, String awsSessionToken,
                   String region, Run<?, ?> build, StepContext stepContext) {

    this.awsAccessKey = sanitize(awsAccessKey);
    this.awsSecretKey = awsSecretKey;
    this.awsSessionToken = sanitize(awsSessionToken);
    this.region = sanitize(region);
    this.properties = new Properties();

    CodeBuilderValidation.checkAWSClientFactoryRegionConfig(this.region);
    this.credentialsDescriptor = "";

    if(credentialsType.equals(CredentialsType.Jenkins.toString())) {
        credentialsId = sanitize(credentialsId);
        CodeBuilderValidation.checkAWSClientFactoryJenkinsCredentialsConfig(credentialsId);
        com.amazonaws.codebuild.jenkinsplugin.CodeBuildBaseCredentials codeBuildCredentials;

        codeBuildCredentials = (CodeBuildBaseCredentials) CredentialsMatchers.firstOrNull(SystemCredentialsProvider.getInstance().getCredentials(),
                CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId)));

        if(codeBuildCredentials == null) {
            Item folder;
            Jenkins instance = Jenkins.getInstance();
            if(instance != null) {
                folder = instance.getItemByFullName(build.getParent().getParent().getFullName());
                codeBuildCredentials = (CodeBuildBaseCredentials) CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(Credentials.class, folder),
                        CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsId)));
            }
        }

        if(codeBuildCredentials != null) {
            this.awsCredentialsProvider = codeBuildCredentials;
            this.proxyHost = codeBuildCredentials.getProxyHost();
            this.proxyPort = parseInt(codeBuildCredentials.getProxyPort());
            this.credentialsDescriptor = codeBuildCredentials.getCredentialsDescriptor() + " (provided from Jenkins credentials " + credentialsId + ")";
        } else {
            throw new InvalidInputException(CodeBuilderValidation.invalidCredentialsIdError);
        }
    } else if(credentialsType.equals(CredentialsType.Keys.toString())) {
        if(this.awsSecretKey == null) {
            throw new InvalidInputException(invalidSecretKeyError);
        }

        if(stepContext != null && awsAccessKey.isEmpty() && awsSecretKey.getPlainText().isEmpty()) {
            try {
                EnvVars stepEnvVars = stepContext.get(EnvVars.class);
                awsCredentialsProvider = getStepCreds(stepEnvVars);
            } catch (IOException|InterruptedException e) {}
        }

        if(awsCredentialsProvider == null) {
            awsCredentialsProvider = getBasicCredentialsOrDefaultChain(sanitize(awsAccessKey), awsSecretKey.getPlainText(), sanitize(awsSessionToken));
        }
        this.proxyHost = sanitize(proxyHost);
        this.proxyPort = parseInt(proxyPort);
    } else {
        throw new InvalidInputException(invalidCredTypeError);
    }
}