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;
}
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);
}
});
}
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();
}
Aggregations