Java Code Examples for hudson.security.ACL

The following examples show how to use hudson.security.ACL. These examples are extracted from open source projects. 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
/**
 * Saves given credentials in jenkins for domain extracted from server url Adds them to domain
 * extracted from server url (will be generated if no any exists before). Domain will have
 * domain requirements consists of scheme and host from serverUrl arg
 *
 * @param serverUrl to extract (and create if no any) domain
 * @param credentials to save credentials
 */
private void saveCredentials(String serverUrl, final PersonalAccessToken credentials) {
    URI serverUri = URI.create(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL));

    List<DomainSpecification> specifications = asList(
        new SchemeSpecification(serverUri.getScheme()),
        new HostnameSpecification(serverUri.getHost(), null)
    );

    final Domain domain = new Domain(serverUri.getHost(), "GitLab domain (autogenerated)",
        specifications);
    try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
        new SystemCredentialsProvider.StoreImpl().addDomain(domain, credentials);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Can't add credentials for domain", e);
    }
}
 
Example 2
Source Project: gitlab-branch-source-plugin   Source File: GitLabServer.java    License: MIT License 6 votes vote down vote up
/**
 * Stapler form completion.
 *
 * @param serverUrl the server URL.
 * @param credentialsId the credentials Id
 * @return the available credentials.
 */
@Restricted(NoExternalUse.class) // stapler
@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 StandardListBoxModel()
        .includeEmptyValue()
        .includeMatchingAs(ACL.SYSTEM,
            jenkins,
            StandardCredentials.class,
            fromUri(serverUrl).build(),
            CREDENTIALS_MATCHER
        );
}
 
Example 3
@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 4
public AbstractIdCredentialsListBoxModel<?, ?> doFillCredentialIdItems(
        @AncestorInPath Item owner) {
    if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
        return new AWSCredentialsListBoxModel();
    }

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

    return new AWSCredentialsListBoxModel()
            .withEmptySelection()
            .withAll(creds);
}
 
Example 5
@Test
public void should_support_configuration_as_code() {
    List<GitLabServer> servers = GitLabServers.get().getServers();
    assertThat(servers.size(), is(1));
    GitLabServer server = servers.get(0);
    assertThat(server.getServerUrl(), is("https://gitlab.com"));
    assertThat(server.getName(), matchesPattern("gitlab-[0-9]{4}"));
    assertThat(server.isManageWebHooks(), is(true));
    assertThat(server.isManageSystemHooks(), is(true));
    assertThat(server.getHooksRootUrl(), is("https://jenkins.intranet/"));

    List<PersonalAccessTokenImpl> credentials = CredentialsProvider.lookupCredentials(
        PersonalAccessTokenImpl.class, j.jenkins, ACL.SYSTEM,
        Collections.emptyList()
    );
    assertThat(credentials, hasSize(1));
    final PersonalAccessTokenImpl credential = credentials.get(0);
    assertThat(credential.getToken().getPlainText(), is("XfsqZvVtAx5YCph5bq3r"));
    assertThat(credential.getToken().getEncryptedValue(), is(not("XfsqZvVtAx5YCph5bq3r")));
}
 
Example 6
Source Project: docker-swarm-plugin   Source File: DockerSwarmComputerLauncher.java    License: 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 7
Source Project: warnings-ng-plugin   Source File: AxivionSuite.java    License: 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 8
Source Project: kubernetes-plugin   Source File: KubernetesCloud.java    License: 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 9
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 10
public ListBoxModel fillCredentialsIdItems(Item context, String remote) {
    List<DomainRequirement> domainRequirements;
    if (remote == null) {
        domainRequirements = Collections.emptyList();
    } else {
        domainRequirements = URIRequirementBuilder.fromUri(remote.trim()).build();
    }

    return new StandardListBoxModel()
            .includeEmptyValue()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                            CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
                            CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
                    ),
                    CredentialsProvider.lookupCredentials(StandardCredentials.class,
                            context,
                            ACL.SYSTEM,
                            domainRequirements)
            );
}
 
Example 11
Source Project: yet-another-docker-plugin   Source File: DockerConnector.java    License: 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 12
Source Project: docker-plugin   Source File: DockerComputerSSHConnector.java    License: MIT License 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, @QueryParameter String credentialsId) {
    if ( !hasPermission(context)) {
        return new StandardUsernameListBoxModel()
                .includeCurrentValue(credentialsId);
    }
    // Functionally the same as SSHLauncher's descriptor method, but without
    // filtering by host/port as we don't/can't know those yet.
    return new StandardUsernameListBoxModel()
            .includeMatchingAs(
                    ACL.SYSTEM,
                    context,
                    StandardUsernameCredentials.class,
                    Collections.emptyList(),
                    SSHAuthenticator.matcher(Connection.class))
            .includeCurrentValue(credentialsId);
}
 
Example 13
Source Project: remoting-kafka-plugin   Source File: GlobalKafkaConfiguration.java    License: MIT License 6 votes vote down vote up
private ListBoxModel fillCredentialsIdItems(@AncestorInPath Item item, @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(credentialsId);
        }
    }
    return result
            .includeMatchingAs(
                    ACL.SYSTEM,
                    Jenkins.get(),
                    StandardUsernamePasswordCredentials.class,
                    Collections.singletonList(KAFKA_SCHEME),
                    CredentialsMatchers.always()
            )
            .includeCurrentValue(credentialsId);
}
 
Example 14
Source Project: github-branch-source-plugin   Source File: Connector.java    License: 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 15
/**
 * Initiate background work that should not block the CPS VM thread.
 * Call this from a CPS VM thread, such as from {@link #start} or {@link BodyExecutionCallback#onSuccess}.
 * The block may finish by calling {@link BodyInvoker#start}, {@link StepContext#onSuccess}, etc.
 * @param block some code to run in a utility thread
 */
protected final void run(Block block) {
    if (stopping) {
        return;
    }
    final Authentication auth = Jenkins.getAuthentication();
    task = GeneralNonBlockingStepExecutionUtils.getExecutorService().submit(() -> {
        threadName = Thread.currentThread().getName();
        try {
            try (ACLContext acl = ACL.as(auth)) {
                block.run();
            }
        } catch (Throwable e) {
            if (!stopping) {
                getContext().onFailure(e);
            }
        } finally {
            threadName = null;
            task = null;
        }
    });
}
 
Example 16
Source Project: pipeline-aws-plugin   Source File: WithAWSStep.java    License: 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 17
Source Project: blueocean-plugin   Source File: BlueOceanCredentialsProvider.java    License: MIT License 6 votes vote down vote up
@Nonnull
@Override
public List<Credentials> getCredentials(@Nonnull Domain domain) {
    final List<Credentials> result = new ArrayList<>(1);
    if (domain.equals(FolderPropertyImpl.this.domain)) {
        final User proxyUser = User.get(getUser(), false, Collections.emptyMap());
        if (proxyUser != null) {
            try (ACLContext ignored = ACL.as(proxyUser.impersonate())) {
                for (CredentialsStore s : CredentialsProvider.lookupStores(proxyUser)) {
                    for (Domain d : s.getDomains()) {
                        if (d.test(PROXY_REQUIREMENT)) {
                            result.addAll(filter(s.getCredentials(d), withId(getId())));
                        }
                    }
                }
            } catch (UsernameNotFoundException ex) {
                logger.warn("BlueOceanCredentialsProvider.StoreImpl#getCredentials(): Username attached to credentials can not be found");
            }
        }
    }
    return result;
}
 
Example 18
Source Project: gitea-plugin   Source File: GiteaServer.java    License: 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 19
Source Project: gitea-plugin   Source File: GiteaServer.java    License: MIT License 6 votes vote down vote up
/**
 * Stapler form completion.
 *
 * @param serverUrl the server URL.
 * @return the available credentials.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    StandardListBoxModel result = new StandardListBoxModel();
    serverUrl = GiteaServers.normalizeServerUrl(serverUrl);
    result.includeMatchingAs(
            ACL.SYSTEM,
            Jenkins.get(),
            StandardCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            AuthenticationTokens.matcher(GiteaAuth.class)
    );
    return result;
}
 
Example 20
Source Project: hashicorp-vault-plugin   Source File: VaultHelper.java    License: 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 21
Source Project: configuration-as-code-plugin   Source File: ConfigurationAsCode.java    License: MIT License 6 votes vote down vote up
private void configureWith(Mapping entries,
    ConfigurationContext context) throws ConfiguratorException {
    // Initialize secret sources
    SecretSource.all().forEach(SecretSource::init);

    // Check input before actually applying changes,
    // so we don't let master in a weird state after some ConfiguratorException has been thrown
    final Mapping clone = entries.clone();
    checkWith(clone, context);

    final ObsoleteConfigurationMonitor monitor = ObsoleteConfigurationMonitor.get();
    monitor.reset();
    context.clearListeners();
    context.addListener(monitor::record);
    try (ACLContext acl = ACL.as(ACL.SYSTEM)) {
        invokeWith(entries, (configurator, config) -> configurator.configure(config, context));
    }
}
 
Example 22
Source Project: jenkins-status-badges-plugin   Source File: BuildStatus.java    License: MIT License 6 votes vote down vote up
public Job<?, ?> getProject( String job, StaplerRequest req, StaplerResponse rsp )
    throws HttpResponses.HttpResponseException
{
    Job<?, ?> p;

    SecurityContext orig = ACL.impersonate( ACL.SYSTEM );
    try
    {
        p = Jenkins.getInstance().getItemByFullName( job, Job.class );
    }
    finally
    {
        SecurityContextHolder.setContext( orig );
    }

    if ( p == null )
    {
        throw org.kohsuke.stapler.HttpResponses.notFound();
    }

    return p;
}
 
Example 23
Source Project: jenkins-test-harness   Source File: HudsonTestCase.java    License: MIT License 6 votes vote down vote up
@Override
protected void runTest() throws Throwable {
    System.out.println("=== Starting "+ getClass().getSimpleName() + "." + getName());
    // so that test code has all the access to the system
    ACL.impersonate(ACL.SYSTEM);

    try {
        super.runTest();
    } catch (Throwable t) {
        // allow the late attachment of a debugger in case of a failure. Useful
        // for diagnosing a rare failure
        try {
            throw new BreakException();
        } catch (BreakException e) {}

        // dump threads
        ThreadInfo[] threadInfos = Functions.getThreadInfos();
        ThreadGroupMap m = Functions.sortThreadsAndGetGroupMap(threadInfos);
        for (ThreadInfo ti : threadInfos) {
            System.err.println(Functions.dumpThreadInfo(ti, m));
        }
        throw t;
    }
}
 
Example 24
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 25
Source Project: gitlab-plugin   Source File: ActionResolver.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Item resolveProject(final String projectName, final Iterator<String> restOfPathParts) {
    return ACLUtil.impersonate(ACL.SYSTEM, new ACLUtil.Function<Item>() {
        public Item invoke() {
            final Jenkins jenkins = Jenkins.getInstance();
            if (jenkins != null) {
                Item item = jenkins.getItemByFullName(projectName);
                while (item instanceof ItemGroup<?> && !(item instanceof Job<?, ?> || item instanceof SCMSourceOwner) && restOfPathParts.hasNext()) {
                    item = jenkins.getItem(restOfPathParts.next(), (ItemGroup<?>) item);
                }
                if (item instanceof Job<?, ?> || item instanceof SCMSourceOwner) {
                    return item;
                }
            }
            LOGGER.log(Level.FINE, "No project found: {0}, {1}", toArray(projectName, Joiner.on('/').join(restOfPathParts)));
            return null;
        }
    });
}
 
Example 26
@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 27
Source Project: acunetix-plugin   Source File: BuildScanner.java    License: 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 28
Source Project: acunetix-plugin   Source File: BuildScanner.java    License: 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 29
@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
@Restricted(NoExternalUse.class)
public ListBoxModel doFillCheckoutCredentialsIdItems(@AncestorInPath SCMSourceOwner context, @QueryParameter String connectionName, @QueryParameter String checkoutCredentialsId) {
    if (context == null && !Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) ||
            context != null && !context.hasPermission(Item.EXTENDED_READ)) {
        return new StandardListBoxModel().includeCurrentValue(checkoutCredentialsId);
    }

    StandardListBoxModel result = new StandardListBoxModel();
    result.add("- anonymous -", CHECKOUT_CREDENTIALS_ANONYMOUS);
    return result.includeMatchingAs(
            context instanceof Queue.Task
                    ? Tasks.getDefaultAuthenticationOf((Queue.Task) context)
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            SettingsUtils.gitLabConnectionRequirements(connectionName),
            GitClient.CREDENTIALS_MATCHER
    );
}