com.cloudbees.plugins.credentials.CredentialsMatchers Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsMatchers. 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: SSHCheckoutTrait.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Form completion.
 *
 * @param context       the context.
 * @param apiUri        the server url.
 * @param credentialsId the current selection.
 * @return the form items.
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillCredentialsIdItems(@CheckForNull @AncestorInPath Item context,
                                             @QueryParameter String apiUri,
                                             @QueryParameter String credentialsId) {
    if (context == null
            ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
            : !context.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    StandardListBoxModel result = new StandardListBoxModel();
    result.add(Messages.SSHCheckoutTrait_useAgentKey(), "");
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            Connector.githubDomainRequirements(apiUri),
            CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
    );
}
 
Example #2
Source File: ListGitBranchesParameterDefinition.java    From list-git-branches-parameter-plugin with MIT License 6 votes vote down vote up
private GitClient createGitClient(Job job) throws IOException, InterruptedException {
    EnvVars env = Objects.requireNonNull(Objects.requireNonNull(Jenkins.getInstance()).toComputer()).getEnvironment();
    Git git = Git.with(TaskListener.NULL, env);

    GitClient c = git.getClient();
    List<StandardUsernameCredentials> urlCredentials = CredentialsProvider.lookupCredentials(
            StandardUsernameCredentials.class, job, ACL.SYSTEM, URIRequirementBuilder.fromUri(remoteURL).build()
    );
    CredentialsMatcher ucMatcher = CredentialsMatchers.withId(credentialsId);
    CredentialsMatcher idMatcher = CredentialsMatchers.allOf(ucMatcher, GitClient.CREDENTIALS_MATCHER);
    StandardUsernameCredentials credentials = CredentialsMatchers.firstOrNull(urlCredentials, idMatcher);

    if (credentials != null) {
        c.addCredentials(remoteURL, credentials);
        if (job != null && job.getLastBuild() != null) {
            CredentialsProvider.track(job.getLastBuild(), credentials);
        }
    }
    return c;
}
 
Example #3
Source File: GlobalKafkaConfiguration.java    From remoting-kafka-plugin with MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillKubernetesCredentialsIdItems() {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    return new StandardListBoxModel().withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                            CredentialsMatchers.instanceOf(FileCredentials.class),
                            CredentialsMatchers.instanceOf(TokenProducer.class),
                            CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
                            CredentialsMatchers.instanceOf(StringCredentials.class)),
                    CredentialsProvider.lookupCredentials(StandardCredentials.class,
                            Jenkins.get(),
                            ACL.SYSTEM,
                            Collections.EMPTY_LIST
                    ));
}
 
Example #4
Source File: GitLabPersonalAccessTokenCreator.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl,
    @QueryParameter String credentialsId) {
    Jenkins jenkins = Jenkins.get();
    if (!jenkins.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }
    return new StandardUsernameListBoxModel()
        .includeEmptyValue()
        .includeMatchingAs(
            ACL.SYSTEM,
            jenkins,
            StandardUsernamePasswordCredentials.class,
            fromUri(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL)).build(),
            CredentialsMatchers.always()
        ).includeMatchingAs(
            Jenkins.getAuthentication(),
            jenkins,
            StandardUsernamePasswordCredentials.class,
            fromUri(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL)).build(),
            CredentialsMatchers.always()
        );
}
 
Example #5
Source File: KubernetesFactoryAdapter.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@CheckForNull
private static StandardCredentials resolveCredentials(@CheckForNull String credentialsId) {
    if (credentialsId == null) {
        return null;
    }
    return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    Jenkins.get(),
                    ACL.SYSTEM,
                    Collections.emptyList()
            ),
            CredentialsMatchers.allOf(
                    AuthenticationTokens.matcher(KubernetesAuth.class),
                    CredentialsMatchers.withId(credentialsId)
            )
    );
}
 
Example #6
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 #7
Source File: GitPushStep.java    From simple-pull-request-job-plugin with Apache License 2.0 6 votes vote down vote up
protected Void run() throws Exception {
    FilePath ws = getContext().get(FilePath.class);
    TaskListener listener = this.getContext().get(TaskListener.class);
    EnvVars envVars = getContext().get(EnvVars.class);
    WorkflowJob job = getContext().get(WorkflowJob.class);
    GitOperations gitOperations = new GitOperations(ws, listener, envVars, url);
    StandardCredentials c = CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    job,
                    Tasks.getAuthenticationOf((Queue.Task) job)),
            CredentialsMatchers.withId(credentialId));

    gitOperations.setUsernameAndPasswordCredential((StandardUsernameCredentials) c);
    gitOperations.setCurrentBranch(branch);
    gitOperations.push(true);
    return null;
}
 
Example #8
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 #9
Source File: DockerConnector.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance());
    if (!ac.hasPermission(Jenkins.ADMINISTER)) {
        return new ListBoxModel();
    }

    List<StandardCredentials> credentials =
            CredentialsProvider.lookupCredentials(StandardCredentials.class,
                    context,
                    ACL.SYSTEM,
                    Collections.emptyList());

    return new CredentialsListBoxModel()
            .includeEmptyValue()
            .withMatching(CredentialsMatchers.always(), credentials);
}
 
Example #10
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 #11
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 #12
Source File: GlobalKafkaConfiguration.java    From remoting-kafka-plugin with MIT License 6 votes vote down vote up
private FormValidation checkCredentialsId(@AncestorInPath Item item, @QueryParameter String value) {
    if (item == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            return FormValidation.ok();
        }
    }
    if (value.startsWith("${") && value.endsWith("}")) {
        return FormValidation.warning("Cannot validate expression based credentials");
    }
    if (CredentialsProvider.listCredentials(
            StandardUsernamePasswordCredentials.class,
            Jenkins.get(),
            ACL.SYSTEM,
            Collections.singletonList(KAFKA_SCHEME),
            CredentialsMatchers.withId(value)
    ).isEmpty()) {
        return FormValidation.error("Cannot find currently selected credentials");
    }
    return FormValidation.ok();
}
 
Example #13
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@RequirePOST
@SuppressWarnings("unused") // used by jelly
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context, @QueryParameter String serverUrl) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    StandardListBoxModel result = new StandardListBoxModel();
    result.includeEmptyValue();
    result.includeMatchingAs(
        ACL.SYSTEM,
        context,
        StandardCredentials.class,
        serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
                    : Collections.EMPTY_LIST,
        CredentialsMatchers.anyOf(
            AuthenticationTokens.matcher(KubernetesAuth.class)
        )
    );
    return result;
}
 
Example #14
Source File: KafkaKubernetesCloud.java    From remoting-kafka-plugin with MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    return new StandardListBoxModel().withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                            CredentialsMatchers.instanceOf(FileCredentials.class),
                            CredentialsMatchers.instanceOf(TokenProducer.class),
                            CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
                            CredentialsMatchers.instanceOf(StringCredentials.class)),
                    CredentialsProvider.lookupCredentials(StandardCredentials.class,
                            Jenkins.get(),
                            ACL.SYSTEM,
                            serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
                                    : Collections.EMPTY_LIST
                    ));
}
 
Example #15
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 #16
Source File: GitLabConnection.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Restricted(NoExternalUse.class)
private String getApiToken(String apiTokenId, Item item) {
    ItemGroup<?> context = null != item ? item.getParent() : Jenkins.get();
    StandardCredentials credentials = CredentialsMatchers.firstOrNull(
        lookupCredentials(
                StandardCredentials.class,
                context, 
                ACL.SYSTEM,
                URIRequirementBuilder.fromUri(url).build()),
        CredentialsMatchers.withId(apiTokenId));
    if (credentials != null) {
        if (credentials instanceof GitLabApiToken) {
            return ((GitLabApiToken) credentials).getApiToken().getPlainText();
        }
        if (credentials instanceof StringCredentials) {
            return ((StringCredentials) credentials).getSecret().getPlainText();
        }
    }
    throw new IllegalStateException("No credentials found for credentialsId: " + apiTokenId);
}
 
Example #17
Source File: ConduitCredentialsDescriptor.java    From phabricator-jenkins-plugin with MIT License 6 votes vote down vote up
public static ListBoxModel doFillCredentialsIDItems(@AncestorInPath Jenkins context) {
    if (context == null || !context.hasPermission(Item.CONFIGURE)) {
        return new StandardListBoxModel();
    }

    List<DomainRequirement> domainRequirements = new ArrayList<DomainRequirement>();
    return new StandardListBoxModel()
            .withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(ConduitCredentials.class)),
                    CredentialsProvider.lookupCredentials(
                            StandardCredentials.class,
                            context,
                            ACL.SYSTEM,
                            domainRequirements));
}
 
Example #18
Source File: ConduitCredentialsDescriptor.java    From phabricator-jenkins-plugin with MIT License 6 votes vote down vote up
public static ConduitCredentials getCredentials(Job owner, String credentialsID) {
    List<ConduitCredentials> available = availableCredentials(owner);
    if (available.size() == 0) {
        return null;
    }
    CredentialsMatcher matcher;
    if (credentialsID != null) {
        matcher = CredentialsMatchers.allOf(CredentialsMatchers.withId(credentialsID));
    } else {
        matcher = CredentialsMatchers.always();
    }
    return CredentialsMatchers.firstOrDefault(
            available,
            matcher,
            available.get(0)
    );
}
 
Example #19
Source File: GiteaServer.java    From gitea-plugin with MIT License 6 votes vote down vote up
/**
 * Looks up the {@link StandardCredentials} to use for auto-management of hooks.
 *
 * @return the credentials or {@code null}.
 */
@CheckForNull
public StandardCredentials credentials() {
    return StringUtils.isBlank(credentialsId) ? null : CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    Jenkins.get(),
                    ACL.SYSTEM,
                    URIRequirementBuilder.fromUri(serverUrl).build()
            ),
            CredentialsMatchers.allOf(
                    AuthenticationTokens.matcher(GiteaAuth.class),
                    CredentialsMatchers.withId(credentialsId)
            )
    );
}
 
Example #20
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 6 votes vote down vote up
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
 
Example #21
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
    final Item item, final String credentialsId, final String uri) {
  final StandardListBoxModel result = new StandardListBoxModel();
  if (item == null) {
    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ)
        && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }
  return result //
      .includeEmptyValue() //
      .includeMatchingAs(
          item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
          item,
          StandardCredentials.class,
          URIRequirementBuilder.fromUri(uri).build(),
          CredentialsMatchers.anyOf(
              CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
              CredentialsMatchers.instanceOf(StringCredentials.class)))
      .includeCurrentValue(credentialsId);
}
 
Example #22
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
public ListBoxModel doFillCredentialsItems(@AncestorInPath Item context) {

			if (context == null || !context.hasPermission(Item.CONFIGURE)) {
				return new ListBoxModel();
			}

			return new StandardListBoxModel()
					.includeEmptyValue()
					.includeMatchingAs(
							context instanceof Queue.Task
									? Tasks.getAuthenticationOf((Queue.Task) context)
									: ACL.SYSTEM,
							context,
							StandardUsernamePasswordCredentials.class,
							Collections.emptyList(),
							CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class))
					.includeMatchingAs(context instanceof Queue.Task
									? Tasks.getAuthenticationOf((Queue.Task) context)
									: ACL.SYSTEM,
							context,
							AmazonWebServicesCredentials.class,
							Collections.emptyList(),
							CredentialsMatchers.instanceOf(AmazonWebServicesCredentials.class));
		}
 
Example #23
Source File: BuildScanner.java    From acunetix-plugin with MIT License 6 votes vote down vote up
private String getgApiKey() {
    StandardCredentials credentials = null;
    try {
        credentials = CredentialsMatchers.firstOrNull(
                lookupCredentials(StandardCredentials.class, (Item) null, ACL.SYSTEM, new ArrayList<DomainRequirement>()),
                CredentialsMatchers.withId(gApiKeyID));
    }
    catch (NullPointerException e) {
        throw new ConnectionException(SR.getString("api.key.not.set"));
    }
    if (credentials != null) {
        if (credentials instanceof StringCredentials) {
            return ((StringCredentials) credentials).getSecret().getPlainText();
        }
    }
    throw new IllegalStateException("Could not find Acunetix API Key ID: " + gApiKeyID);
}
 
Example #24
Source File: BuildScanner.java    From acunetix-plugin with MIT License 6 votes vote down vote up
public ListBoxModel doFillGApiKeyIDItems(
        @AncestorInPath Item item) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(gApiKeyID);
        }
    } else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return result.includeCurrentValue(gApiKeyID);
        }
    }
    if (gApiKeyID != null) {
        result.includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
                Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.withId(gApiKeyID)));
    }
    return result
            .includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
                    Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.instanceOf(StringCredentials.class)));
}
 
Example #25
Source File: Site.java    From jira-steps-plugin with Apache License 2.0 6 votes vote down vote up
public FormValidation doCheckCredentialsId(@AncestorInPath Item item,
    final @QueryParameter String credentialsId,
    final @QueryParameter String url) {

  if (item == null) {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
      return FormValidation.ok();
    }
  } else if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
    return FormValidation.ok();
  }
  if (StringUtils.isBlank(credentialsId)) {
    return FormValidation.warning(Messages.Site_emptyCredentialsId());
  }

  List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(url).build();
  if (CredentialsProvider.listCredentials(StandardUsernameCredentials.class, item, getAuthentication(item), domainRequirements, CredentialsMatchers.withId(credentialsId)).isEmpty()) {
    return FormValidation.error(Messages.Site_invalidCredentialsId());
  }
  return FormValidation.ok();
}
 
Example #26
Source File: JiraCloudSiteConfig.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter final String credentialsId) {
    Jenkins instance = Jenkins.get();
    if (!instance.hasPermission(Jenkins.ADMINISTER)) {
        return new StandardListBoxModel().includeCurrentValue(credentialsId);
    }

    return new StandardListBoxModel()
            .includeEmptyValue()
            .includeMatchingAs(
                    ACL.SYSTEM,
                    instance,
                    StringCredentials.class,
                    URIRequirementBuilder.fromUri(ATLASSIAN_API_URL).build(),
                    CredentialsMatchers.always());
}
 
Example #27
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 #28
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 #29
Source File: CredentialsHelper.java    From violation-comments-to-github-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
    final Item item, final String credentialsId, final String uri) {
  final StandardListBoxModel result = new StandardListBoxModel();
  if (item == null) {
    if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ)
        && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }
  return result //
      .includeEmptyValue() //
      .includeMatchingAs(
          item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
          item,
          StandardCredentials.class,
          URIRequirementBuilder.fromUri(uri).build(),
          CredentialsMatchers.anyOf(
              CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
              CredentialsMatchers.instanceOf(StringCredentials.class)))
      .includeCurrentValue(credentialsId);
}
 
Example #30
Source File: CredentialsHelper.java    From violation-comments-to-github-plugin with MIT License 6 votes vote down vote up
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}