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

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsProvider#findCredentialById() . 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: 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.
 */
public KeyMaterialFactory newKeyMaterialFactory(@Nonnull Run context, @Nonnull VirtualChannel target) throws IOException, InterruptedException {
    DockerServerCredentials creds=null;
    if (credentialsId!=null) {
        List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(getUri()).build();
        domainRequirements.add(new DockerServerDomainRequirement());
        creds = CredentialsProvider.findCredentialById(credentialsId, DockerServerCredentials.class, context,
                domainRequirements);
    }

    // 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 2
Source File: MultiBinding.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
/**
 * Looks up the actual credentials.
 * @param build the build.
 * @return the credentials
 * @throws FileNotFoundException if the credentials could not be found (for convenience, rather than returning null)
 */
protected final @Nonnull C getCredentials(@Nonnull Run<?,?> build) throws IOException {
    IdCredentials cred = CredentialsProvider.findCredentialById(credentialsId, IdCredentials.class, build);
    if (cred==null)
        throw new CredentialNotFoundException("Could not find credentials entry with ID '" + credentialsId + "'");

    if (type().isInstance(cred)) {
        CredentialsProvider.track(build, cred);
        return type().cast(cred);
    }

    
    Descriptor expected = Jenkins.getActiveInstance().getDescriptor(type());
    throw new CredentialNotFoundException("Credentials '"+credentialsId+"' is of type '"+
            cred.getDescriptor().getDisplayName()+"' where '"+
            (expected!=null ? expected.getDisplayName() : type().getName())+
            "' was expected");
}
 
Example 3
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
private void withCredentials(@Nonnull Run<?, ?> run, @Nonnull EnvVars localEnv) throws IOException, InterruptedException {
	if (!StringUtils.isNullOrEmpty(this.step.getCredentials())) {
		StandardUsernamePasswordCredentials usernamePasswordCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				StandardUsernamePasswordCredentials.class, run, Collections.emptyList());

		AmazonWebServicesCredentials amazonWebServicesCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(),
				AmazonWebServicesCredentials.class, run, Collections.emptyList());
		if (usernamePasswordCredentials != null) {
			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, usernamePasswordCredentials.getUsername());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, usernamePasswordCredentials.getPassword().getPlainText());
		} else if (amazonWebServicesCredentials != null) {
			AWSCredentials awsCredentials;

			if (StringUtils.isNullOrEmpty(this.step.getIamMfaToken())) {
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials");
				awsCredentials = amazonWebServicesCredentials.getCredentials();
			} else {
				// Since the getCredentials does its own roleAssumption, this is all it takes to get credentials
				// with this token.
				this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials utilizing MFA Token");
				awsCredentials = amazonWebServicesCredentials.getCredentials(this.step.getIamMfaToken());
				BasicSessionCredentials basicSessionCredentials = (BasicSessionCredentials) awsCredentials;
				localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, basicSessionCredentials.getSessionToken());
			}

			localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, awsCredentials.getAWSAccessKeyId());
			localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, awsCredentials.getAWSSecretKey());
		} else {
			throw new RuntimeException("Cannot find a Username with password credential with the ID " + this.step.getCredentials());
		}
	} else if (!StringUtils.isNullOrEmpty(this.step.getSamlAssertion())) {
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, "access_key_not_used_will_pass_through_SAML_assertion");
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, "secret_access_key_not_used_will_pass_through_SAML_assertion");
	}
	this.envVars.overrideAll(localEnv);
}
 
Example 4
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
/**
 *
 * @param serverCredentialMappings
 * @param logMessagePrefix
 * @return credentials by Maven server Id
 */
@Nonnull
public Map<String, StandardUsernameCredentials> resolveCredentials(@Nullable final List<ServerCredentialMapping> serverCredentialMappings, String logMessagePrefix) {
    // CredentialsHelper.removeMavenServerDefinitions() requires a Map implementation that supports `null` values. `HashMap` supports `null` values, `TreeMap` doesn't
    // https://github.com/jenkinsci/config-file-provider-plugin/blob/config-file-provider-2.16.4/src/main/java/org/jenkinsci/plugins/configfiles/maven/security/CredentialsHelper.java#L252
    Map<String, StandardUsernameCredentials> mavenServerIdToCredentials = new HashMap<>();
    if (serverCredentialMappings == null) {
        return mavenServerIdToCredentials;
    }
    List<ServerCredentialMapping> unresolvedServerCredentialsMappings = new ArrayList<>();
    for (ServerCredentialMapping serverCredentialMapping : serverCredentialMappings) {

        List<DomainRequirement> domainRequirements = StringUtils.isBlank(serverCredentialMapping.getServerId()) ?  Collections.emptyList(): Collections.singletonList(new MavenServerIdRequirement(serverCredentialMapping.getServerId()));
        @Nullable
        final StandardUsernameCredentials credentials = CredentialsProvider.findCredentialById(serverCredentialMapping.getCredentialsId(), StandardUsernameCredentials.class, build, domainRequirements);

        if (credentials == null) {
            unresolvedServerCredentialsMappings.add(serverCredentialMapping);
        } else {
            mavenServerIdToCredentials.put(serverCredentialMapping.getServerId(), credentials);
        }
    }
    if (!unresolvedServerCredentialsMappings.isEmpty()) {
        /*
         * we prefer to print a warning message rather than failing the build with an AbortException if some credentials are NOT found for backward compatibility reasons.
         * The behaviour of o.j.p.configfiles.m.s.CredentialsHelper.resolveCredentials(model.Run, List<ServerCredentialMapping>, TaskListener)` is to just print a warning message
         */
        console.println("[withMaven] WARNING " + logMessagePrefix + " - Silently skip Maven server Ids with missing associated Jenkins credentials: " +
                unresolvedServerCredentialsMappings.stream().map(new ServerCredentialMappingToStringFunction()).collect(Collectors.joining(", ")));
    }
    return mavenServerIdToCredentials;
}
 
Example 5
Source File: KubectlBuildWrapper.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp(Context context, Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener, EnvVars initialEnvironment) throws IOException, InterruptedException {
    if (credentialsId == null) {
        throw new AbortException("No credentials defined to setup Kubernetes CLI");
    }
    workspace.mkdirs();
    FilePath configFile = workspace.createTempFile(".kube", "config");
    Set<String> tempFiles = newHashSet(configFile.getRemote());

    context.env("KUBECONFIG", configFile.getRemote());
    context.setDisposer(new CleanupDisposer(tempFiles));

    StandardCredentials credentials = CredentialsProvider.findCredentialById(credentialsId, StandardCredentials.class, build, Collections.emptyList());
    if (credentials == null) {
        throw new AbortException("No credentials found for id \"" + credentialsId + "\"");
    }
    KubernetesAuth auth = AuthenticationTokens.convert(KubernetesAuth.class, credentials);
    if (auth == null) {
        throw new AbortException("Unsupported Credentials type " + credentials.getClass().getName());
    }
    try (Writer w = new OutputStreamWriter(configFile.write(), StandardCharsets.UTF_8)) {
        w.write(auth.buildKubeConfig(new KubernetesAuthConfig(getServerUrl(), getCaCertificate(), getCaCertificate() == null)));
    } catch (KubernetesAuthException e) {
        throw new AbortException(e.getMessage());
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    String cmd = "kubectl version";
    int status = launcher.launch().cmdAsSingleString(cmd).stdout(out).stderr(err).quiet(true).envs("KUBECONFIG="+configFile.getRemote()).join();
    if (status != 0) {
        StringBuilder msgBuilder = new StringBuilder("Failed to run \"").append(cmd).append("\". Returned status code ").append(status).append(".\n");
        msgBuilder.append("stdout:\n").append(out).append("\n");
        msgBuilder.append("stderr:\n").append(err);
        throw new AbortException(msgBuilder.toString());
    }
}
 
Example 6
Source File: JiraStepExecution.java    From jira-steps-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies the common input for all the stesp.
 *
 * @return response if JIRA_SITE is empty or if there is no site configured with JIRA_SITE.
 * @throws AbortException when failOnError is true and JIRA_SITE is missing.
 */
@SuppressWarnings("hiding")
protected <T> ResponseData<T> verifyCommon(final BasicJiraStep step) throws AbortException {

  logger = listener.getLogger();

  String errorMessage = null;
  siteName = empty(step.getSite()) ? envVars.get("JIRA_SITE") : step.getSite();
  final Site site = Site.get(siteName);
  final String failOnErrorStr = Util.fixEmpty(envVars.get("JIRA_FAIL_ON_ERROR"));

  if (failOnErrorStr == null) {
    failOnError = step.isFailOnError();
  } else {
    failOnError = Boolean.parseBoolean(failOnErrorStr);
  }

  if (empty(siteName)) {
    errorMessage = "JIRA_SITE is empty or null.";
  }

  if (site == null) {
    errorMessage = "No JIRA site configured with " + siteName + " name.";
  } else {
    if (jiraService == null) {
      if (LoginType.CREDENTIAL.name().equals(site.getLoginType())) {
        // at build time use of credentials must be checked against the user who run the build, see https://plugins.jenkins.io/authorize-project
        StandardUsernameCredentials credentialsId = CredentialsProvider.findCredentialById(site.getCredentialsId(), StandardUsernameCredentials.class, run, Collections.emptyList());
        if (credentialsId == null) {
          throw new AbortException(Messages.Site_invalidCredentialsId());
        }
      }
      jiraService = site.getService();
    }
  }

  if (errorMessage != null) {
    return buildErrorResponse(new RuntimeException(errorMessage));
  }

  buildUserId = prepareBuildUserId(run.getCauses());
  buildUrl = envVars.get("BUILD_URL");

  return null;
}