Search in sources :

Example 1 with DomainRequirement

use of com.cloudbees.plugins.credentials.domains.DomainRequirement in project nodejs-plugin by jenkinsci.

the class RegistryHelper method resolveCredentials.

/**
 * Resolves all registry credentials and returns a map paring registry URL
 * to credential.
 *
 * @param build a build being run
 * @return map of registry URL - credential
 */
public Map<String, StandardUsernameCredentials> resolveCredentials(Run<?, ?> build) {
    Map<String, StandardUsernameCredentials> registry2credential = new HashMap<>();
    for (NPMRegistry registry : registries) {
        String credentialsId = registry.getCredentialsId();
        if (credentialsId != null) {
            // create a domain filter based on registry URL
            final URL registryURL = toURL(registry.getUrl());
            List<DomainRequirement> domainRequirements = Collections.emptyList();
            if (registryURL != null) {
                domainRequirements = Collections.<DomainRequirement>singletonList(new HostnameRequirement(registryURL.getHost()));
            }
            StandardUsernameCredentials c = CredentialsProvider.findCredentialById(credentialsId, StandardUsernameCredentials.class, build, domainRequirements);
            if (c != null) {
                registry2credential.put(registry.getUrl(), c);
            }
        }
    }
    return registry2credential;
}
Also used : HashMap(java.util.HashMap) DomainRequirement(com.cloudbees.plugins.credentials.domains.DomainRequirement) HostnameRequirement(com.cloudbees.plugins.credentials.domains.HostnameRequirement) StandardUsernameCredentials(com.cloudbees.plugins.credentials.common.StandardUsernameCredentials) URL(java.net.URL)

Example 2 with DomainRequirement

use of com.cloudbees.plugins.credentials.domains.DomainRequirement in project jenkins-client-plugin by openshift.

the class BaseStep method runOcCommand.

protected boolean runOcCommand(final AbstractBuild build, final TaskListener listener, final String verb, final List verbArgs, final List userArgs, final List options, final OcProcessRunner runner) throws IOException, InterruptedException {
    final Map<String, String> overrides = consolidateEnvVars(listener, build, null);
    ClusterConfig c = getCluster(overrides);
    final String server, project, token, caContent;
    String selectedCAPath = "";
    boolean shouldSkipTLSVerify = false;
    ArrayList<String> advArgs = new ArrayList<String>();
    if (advancedArguments != null) {
        for (AdvancedArgument advArg : advancedArguments) {
            advArgs.add(advArg.getValue(overrides));
        }
    }
    if (c == null) {
        // if null, we assume the cluster is running the
        // Jenkins node.
        server = ClusterConfig.getHostClusterApiServerUrl();
        selectedCAPath = SERVICE_ACCOUNT_CA_PATH;
        caContent = null;
    } else {
        server = c.getServerUrl();
        if (c.isSkipTlsVerify()) {
            shouldSkipTLSVerify = true;
            caContent = null;
        } else {
            caContent = c.getServerCertificateAuthority();
        }
    }
    if (Strings.isNullOrEmpty(getProject(overrides))) {
        // for this step
        if (c != null) {
            // But a cluster definition was provided
            project = c.getDefaultProject();
            if (Strings.isNullOrEmpty(project)) {
                throw new IOException("No project defined in step or in cluster: " + getClusterName(overrides));
            }
        } else {
            project = new String(Files.readAllBytes(Paths.get(SERVICE_ACCOUNT_NAMESPACE_PATH)), StandardCharsets.UTF_8);
        }
    } else {
        project = this.getProject(overrides);
    }
    String actualCredentialsId = getCredentialsId(overrides);
    if (Strings.isNullOrEmpty(actualCredentialsId)) {
        // step.
        if (c != null) {
            // But a cluster definition was found
            actualCredentialsId = c.getCredentialsId();
            if (Strings.isNullOrEmpty(actualCredentialsId)) {
                throw new IOException("No credentials defined in step or in cluster: " + getClusterName(overrides));
            }
        }
    }
    if (!Strings.isNullOrEmpty(actualCredentialsId)) {
        OpenShiftTokenCredentials tokenSecret = CredentialsProvider.findCredentialById(actualCredentialsId, OpenShiftTokenCredentials.class, build, new ArrayList<DomainRequirement>());
        if (tokenSecret == null) {
            throw new IOException("Unable to find credential in Jenkins credential store: " + actualCredentialsId);
        }
        token = tokenSecret.getToken();
    } else {
        // We are running within a host cluster, so use mounted secret
        token = new String(Files.readAllBytes(Paths.get(SERVICE_ACCOUNT_TOKEN_PATH)), StandardCharsets.UTF_8);
    }
    final String finalSelectedCAPath = selectedCAPath;
    final boolean finalShouldSkipTLSVerify = shouldSkipTLSVerify;
    final List finalAdvArgs = advArgs;
    return withTempInput("serviceca", caContent, new WithTempInputRunnable() {

        @Override
        public boolean perform(String filename) throws IOException, InterruptedException {
            if (filename == null) {
                // this will be null if we are
                // running within the cluster or
                // TLS verify is disabled
                filename = finalSelectedCAPath;
            }
            final ClientCommandBuilder cmdBuilder = new ClientCommandBuilder(server, project, finalShouldSkipTLSVerify, filename, verb, finalAdvArgs, verbArgs, userArgs, options, token, Integer.parseInt(getLogLevel(overrides)));
            ProcessBuilder pb = new ProcessBuilder();
            pb.command(cmdBuilder.buildCommand(false));
            listener.getLogger().println("Executing: " + cmdBuilder.asString(true));
            return runner.perform(pb);
        }
    });
}
Also used : DomainRequirement(com.cloudbees.plugins.credentials.domains.DomainRequirement) ClientCommandBuilder(com.openshift.jenkins.plugins.util.ClientCommandBuilder) ArrayList(java.util.ArrayList) AdvancedArgument(com.openshift.jenkins.plugins.freestyle.model.AdvancedArgument) IOException(java.io.IOException) OpenShiftTokenCredentials(com.openshift.jenkins.plugins.OpenShiftTokenCredentials) ArrayList(java.util.ArrayList) List(java.util.List) ClusterConfig(com.openshift.jenkins.plugins.ClusterConfig)

Example 3 with DomainRequirement

use of com.cloudbees.plugins.credentials.domains.DomainRequirement in project blueocean-plugin by jenkinsci.

the class GitScm method validateAndCreate.

@Override
public HttpResponse validateAndCreate(@JsonBody JSONObject request) {
    boolean requirePush = request.has("requirePush");
    // --[ Grab repo url and SCMSource ]----------------------------------------------------------
    final String repositoryUrl;
    final AbstractGitSCMSource scmSource;
    if (request.has("repositoryUrl")) {
        repositoryUrl = request.getString("repositoryUrl");
        scmSource = new GitSCMSource(repositoryUrl);
    } else {
        try {
            String fullName = request.getJSONObject("pipeline").getString("fullName");
            SCMSourceOwner item = Jenkins.get().getItemByFullName(fullName, SCMSourceOwner.class);
            if (item != null) {
                scmSource = (AbstractGitSCMSource) item.getSCMSources().iterator().next();
                repositoryUrl = scmSource.getRemote();
            } else {
                return HttpResponses.errorJSON("No repository found for: " + fullName);
            }
        } catch (JSONException e) {
            return HttpResponses.errorJSON("No repositoryUrl or pipeline.fullName specified in request.");
        } catch (RuntimeException e) {
            return HttpResponses.errorWithoutStack(ServiceException.INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    // --[ Grab user ]-------------------------------------------------------------------------------------
    User user = User.current();
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Not authenticated");
    }
    // --[ Get credential id from request or create from repo url ]----------------------------------------
    String credentialId = null;
    if (request.has("credentialId")) {
        credentialId = request.getString("credentialId");
    }
    if (credentialId == null) {
        credentialId = makeCredentialId(repositoryUrl);
    }
    if (credentialId == null) {
        // Still null? Must be a bad repoURL
        throw new ServiceException.BadRequestException("Invalid URL \"" + repositoryUrl + "\"");
    }
    // Create new is only for username + password
    if (request.has("userName") || request.has("password")) {
        createPWCredentials(credentialId, user, request, repositoryUrl);
    }
    final StandardCredentials creds = CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(StandardCredentials.class, Jenkins.get(), Jenkins.getAuthentication(), (List<DomainRequirement>) null), CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialId)));
    if (creds == null) {
        throw new ServiceException.NotFoundException("No credentials found for: " + credentialId);
    }
    try {
        if (requirePush) {
            String branch = request.getString("branch");
            if (repositoryUrl != null) {
                ((GitSCMSource) scmSource).setCredentialsId(credentialId);
            }
            new GitBareRepoReadSaveRequest(scmSource, branch, null, branch, null, null).invokeOnScm((GitSCMFileSystem.FSFunction<Void>) repository -> {
                GitUtils.validatePushAccess(repository, repositoryUrl, creds);
                return null;
            });
        } else {
            List<ErrorMessage.Error> errors = GitUtils.validateCredentials(repositoryUrl, creds);
            if (!errors.isEmpty()) {
                throw new ServiceException.UnauthorizedException(errors.get(0).getMessage());
            }
        }
    } catch (Exception e) {
        String message = e.getMessage();
        if (message != null && message.contains("TransportException")) {
            throw new ServiceException.PreconditionRequired("Repository URL unreachable: " + repositoryUrl);
        }
        return HttpResponses.errorWithoutStack(ServiceException.PRECONDITION_REQUIRED, message);
    }
    return HttpResponses.okJSON();
}
Also used : BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) StaplerRequest(org.kohsuke.stapler.StaplerRequest) URISyntaxException(java.net.URISyntaxException) JsonBody(org.kohsuke.stapler.json.JsonBody) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) ScmOrganization(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmOrganization) CredentialsMatchers(com.cloudbees.plugins.credentials.CredentialsMatchers) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) Locale(java.util.Locale) NonNull(edu.umd.cs.findbugs.annotations.NonNull) Extension(hudson.Extension) Container(io.jenkins.blueocean.rest.model.Container) User(hudson.model.User) URI(java.net.URI) CredentialsScope(com.cloudbees.plugins.credentials.CredentialsScope) DomainRequirement(com.cloudbees.plugins.credentials.domains.DomainRequirement) CredentialsUtils(io.jenkins.blueocean.credential.CredentialsUtils) JSONException(net.sf.json.JSONException) GitSCMFileSystem(jenkins.plugins.git.GitSCMFileSystem) ScmServerEndpointContainer(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpointContainer) HttpResponse(org.kohsuke.stapler.HttpResponse) AbstractGitSCMSource(jenkins.plugins.git.AbstractGitSCMSource) Jenkins(jenkins.model.Jenkins) Reachable(io.jenkins.blueocean.rest.Reachable) SCMSourceOwner(jenkins.scm.api.SCMSourceOwner) IOException(java.io.IOException) Scm(io.jenkins.blueocean.rest.impl.pipeline.scm.Scm) ServiceException(io.jenkins.blueocean.commons.ServiceException) HttpResponses(hudson.util.HttpResponses) ScmFactory(io.jenkins.blueocean.rest.impl.pipeline.scm.ScmFactory) Objects(java.util.Objects) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) List(java.util.List) Stapler(org.kohsuke.stapler.Stapler) CredentialsProvider(com.cloudbees.plugins.credentials.CredentialsProvider) DigestUtils(io.jenkins.blueocean.commons.DigestUtils) JSONObject(net.sf.json.JSONObject) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) AbstractScm(io.jenkins.blueocean.rest.impl.pipeline.scm.AbstractScm) Collections(java.util.Collections) Link(io.jenkins.blueocean.rest.hal.Link) GitSCMSource(jenkins.plugins.git.GitSCMSource) User(hudson.model.User) SCMSourceOwner(jenkins.scm.api.SCMSourceOwner) GitSCMFileSystem(jenkins.plugins.git.GitSCMFileSystem) JSONException(net.sf.json.JSONException) AbstractGitSCMSource(jenkins.plugins.git.AbstractGitSCMSource) GitSCMSource(jenkins.plugins.git.GitSCMSource) URISyntaxException(java.net.URISyntaxException) JSONException(net.sf.json.JSONException) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) AbstractGitSCMSource(jenkins.plugins.git.AbstractGitSCMSource) ServiceException(io.jenkins.blueocean.commons.ServiceException) List(java.util.List) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials)

Aggregations

DomainRequirement (com.cloudbees.plugins.credentials.domains.DomainRequirement)3 IOException (java.io.IOException)2 List (java.util.List)2 CredentialsMatchers (com.cloudbees.plugins.credentials.CredentialsMatchers)1 CredentialsProvider (com.cloudbees.plugins.credentials.CredentialsProvider)1 CredentialsScope (com.cloudbees.plugins.credentials.CredentialsScope)1 StandardCredentials (com.cloudbees.plugins.credentials.common.StandardCredentials)1 StandardUsernameCredentials (com.cloudbees.plugins.credentials.common.StandardUsernameCredentials)1 StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)1 HostnameRequirement (com.cloudbees.plugins.credentials.domains.HostnameRequirement)1 UsernamePasswordCredentialsImpl (com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl)1 ClusterConfig (com.openshift.jenkins.plugins.ClusterConfig)1 OpenShiftTokenCredentials (com.openshift.jenkins.plugins.OpenShiftTokenCredentials)1 AdvancedArgument (com.openshift.jenkins.plugins.freestyle.model.AdvancedArgument)1 ClientCommandBuilder (com.openshift.jenkins.plugins.util.ClientCommandBuilder)1 NonNull (edu.umd.cs.findbugs.annotations.NonNull)1 Extension (hudson.Extension)1 User (hudson.model.User)1 HttpResponses (hudson.util.HttpResponses)1 DigestUtils (io.jenkins.blueocean.commons.DigestUtils)1