Java Code Examples for org.kohsuke.accmod.restrictions.NoExternalUse

The following examples show how to use org.kohsuke.accmod.restrictions.NoExternalUse. 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
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 2
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 3
Source Project: gitea-plugin   Source File: PersonalAccessTokenImpl.java    License: MIT License 6 votes vote down vote up
/**
 * Sanity check for a Gitea access token.
 *
 * @param value the token.
 * @return the resulst of the sanity check.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused") // stapler
public FormValidation doCheckToken(@QueryParameter String value) {
    if (value == null || value.isEmpty()) {
        return FormValidation.error(Messages.PersonalAccessTokenImpl_tokenRequired());
    }
    Secret secret = Secret.fromString(value);
    if (StringUtils.equals(value, secret.getPlainText())) {
        if (value.length() != 40) {
            return FormValidation.error(Messages.PersonalAccessTokenImpl_tokenWrongLength());
        }
    } else if (secret.getPlainText().length() != 40) {
        return FormValidation.warning(Messages.PersonalAccessTokenImpl_tokenWrongLength());
    }
    return FormValidation.ok();
}
 
Example 4
Source Project: configuration-as-code-plugin   Source File: ConfigurationAsCode.java    License: MIT License 6 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doCheck(StaplerRequest req, StaplerResponse res) throws Exception {

    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    final Map<Source, String> issues = checkWith(YamlSource.of(req));
    res.setContentType("application/json");
    final JSONArray warnings = new JSONArray();
    issues.entrySet().stream().map(e -> new JSONObject().accumulate("line", e.getKey().line).accumulate("warning", e.getValue()))
            .forEach(warnings::add);
    warnings.write(res.getWriter());
}
 
Example 5
Source Project: configuration-as-code-plugin   Source File: ConfigurationAsCode.java    License: MIT License 6 votes vote down vote up
/**
 * Recursive search for all {@link #YAML_FILES_PATTERN} in provided base path
 *
 * @param path base path to start (can be file or directory)
 * @return list of all paths matching pattern. Only base file itself if it is a file matching pattern
 */
@Restricted(NoExternalUse.class)
public List<Path> configs(String path) throws ConfiguratorException {
    final Path root = Paths.get(path);

    if (!Files.exists(root)) {
        throw new ConfiguratorException("Invalid configuration: '"+path+"' isn't a valid path.");
    }

    if (Files.isRegularFile(root) && Files.isReadable(root)) {
        return Collections.singletonList(root);
    }

    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(YAML_FILES_PATTERN);
    try (Stream<Path> stream = Files.find(Paths.get(path), Integer.MAX_VALUE,
            (next, attrs) -> !attrs.isDirectory() && !isHidden(next) && matcher.matches(next), FileVisitOption.FOLLOW_LINKS)) {
        return stream.sorted().collect(toList());
    } catch (IOException e) {
        throw new IllegalStateException("failed config scan for " + path, e);
    }
}
 
Example 6
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public Set<Permission> getFolderPermissions() {
    HashSet<PermissionGroup> groups = new HashSet<>(PermissionGroup.getAll());
    groups.remove(PermissionGroup.get(Hudson.class));
    groups.remove(PermissionGroup.get(Computer.class));
    groups.remove(PermissionGroup.get(Permission.class));
    return getSafePermissions(groups);
}
 
Example 7
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public Set<Permission> getAgentPermissions() {
    HashSet<PermissionGroup> groups = new HashSet<>(PermissionGroup.getAll());
    groups.remove(PermissionGroup.get(Run.class));
    groups.remove(PermissionGroup.get(SCM.class));
    groups.remove(PermissionGroup.get(View.class));
    groups.remove(PermissionGroup.get(Item.class));
    groups.remove(PermissionGroup.get(Hudson.class));
    groups.remove(PermissionGroup.get(Permission.class));
    return getSafePermissions(groups);
}
 
Example 8
Source Project: pipeline-maven-plugin   Source File: WithMavenStep.java    License: MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillMavenItems() {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default Maven ---",null);
    for (MavenInstallation installation : getMavenDescriptor().getInstallations()) {
        r.add(installation.getName());
    }
    return r;
}
 
Example 9
Source Project: pipeline-maven-plugin   Source File: WithMavenStep.java    License: MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillGlobalMavenSettingsConfigItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default settings or file path ---",null);
    for (Config config : ConfigFiles.getConfigsInContext(context, GlobalMavenSettingsConfigProvider.class)) {
        r.add(config.name, config.id);
    }
    return r;
}
 
Example 10
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public SortedSet<GlobalRole> getGlobalRoles() {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        return new TreeSet<>(((FolderBasedAuthorizationStrategy) strategy).getGlobalRoles());
    } else {
        throw new IllegalStateException(Messages.FolderBasedAuthorizationStrategy_NotCurrentStrategy());
    }
}
 
Example 11
/**
 * Get all {@link AbstractFolder}s in the system
 *
 * @return full names of all {@link AbstractFolder}s in the system
 */
@GET
@Nonnull
@Restricted(NoExternalUse.class)
public JSONArray doGetAllFolders() {
    Jenkins jenkins = Jenkins.get();
    jenkins.checkPermission(Jenkins.ADMINISTER);
    List<AbstractFolder> folders;

    try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
        folders = jenkins.getAllItems(AbstractFolder.class);
    }

    return JSONArray.fromObject(folders.stream().map(AbstractItem::getFullName).collect(Collectors.toList()));
}
 
Example 12
/**
 * Get all {@link Computer}s in the system
 *
 * @return all Computers in the system
 */
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public List<Computer> getAllComputers() {
    Jenkins jenkins = Jenkins.get();
    jenkins.checkPermission(Jenkins.ADMINISTER);
    Computer[] computers;

    try (ACLContext ignored = ACL.as(ACL.SYSTEM)) {
        computers = jenkins.getComputers();
    }

    return Arrays.asList(computers);
}
 
Example 13
/**
 * Returns the {@link FolderRole}s used by the {@link FolderBasedAuthorizationStrategy}.
 *
 * @return the {@link FolderRole}s used by the {@link FolderBasedAuthorizationStrategy}
 * @throws IllegalStateException when {@link Jenkins#getAuthorizationStrategy()} is
 *                               not {@link FolderBasedAuthorizationStrategy}
 */
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public SortedSet<FolderRole> getFolderRoles() {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        return new TreeSet<>(((FolderBasedAuthorizationStrategy) strategy).getFolderRoles());
    } else {
        throw new IllegalStateException(Messages.FolderBasedAuthorizationStrategy_NotCurrentStrategy());
    }
}
 
Example 14
@Nonnull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used by index.jelly
public SortedSet<AgentRole> getAgentRoles() {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        return new TreeSet<>(((FolderBasedAuthorizationStrategy) strategy).getAgentRoles());
    } else {
        throw new IllegalStateException(Messages.FolderBasedAuthorizationStrategy_NotCurrentStrategy());
    }
}
 
Example 15
/**
 * Sanity check for a Gitlab access token.
 *
 * @param value the personal access token.
 * @return the results of the sanity check.
 */
@Restricted(NoExternalUse.class) // stapler
@SuppressWarnings("unused")
public FormValidation doCheckToken(@QueryParameter String value) {
    Secret secret = Secret.fromString(value);
    if (StringUtils.equals(value, secret.getPlainText())) {
        if (value.length() != GITLAB_ACCESS_TOKEN_LENGTH) {
            return FormValidation
                .error(Messages.PersonalAccessTokenImpl_tokenWrongLength());
        }
    } else if (secret.getPlainText().length() != GITLAB_ACCESS_TOKEN_LENGTH) {
        return FormValidation.error(Messages.PersonalAccessTokenImpl_tokenWrongLength());
    }
    return FormValidation.ok();
}
 
Example 16
/**
 * Populates the strategy options.
 *
 * @return the stategy options.
 */
@NonNull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler
public ListBoxModel doFillStrategyIdItems() {
    ListBoxModel result = new ListBoxModel();
    result.add(Messages.ForkMergeRequestDiscoveryTrait_mergeOnly(), "1");
    result.add(Messages.ForkMergeRequestDiscoveryTrait_headOnly(), "2");
    result.add(Messages.ForkMergeRequestDiscoveryTrait_headAndMerge(), "3");
    return result;
}
 
Example 17
Source Project: pipeline-maven-plugin   Source File: WithMavenStep.java    License: MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillPublisherStrategyItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    for(MavenPublisherStrategy publisherStrategy: MavenPublisherStrategy.values()) {
        r.add(publisherStrategy.getDescription(), publisherStrategy.name());
    }
    return r;
}
 
Example 18
Source Project: gitlab-branch-source-plugin   Source File: SSHCheckoutTrait.java    License: MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillCredentialsIdItems(@CheckForNull @AncestorInPath Item context,
    @QueryParameter String serverUrl,
    @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
            && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
        context instanceof Queue.Task
            ? ((Queue.Task) context).getDefaultAuthentication()
            : ACL.SYSTEM,
        context,
        StandardUsernameCredentials.class,
        URIRequirementBuilder.fromUri(serverUrl).build(),
        CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
    );
    return result;
}
 
Example 19
Source Project: gitlab-branch-source-plugin   Source File: BranchDiscoveryTrait.java    License: MIT License 5 votes vote down vote up
/**
 * Populates the strategy options.
 *
 * @return the stategy options.
 */
@NonNull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler
public ListBoxModel doFillStrategyIdItems() {
    ListBoxModel result = new ListBoxModel();
    result.add(Messages.BranchDiscoveryTrait_excludeMRs(), "1");
    result.add(Messages.BranchDiscoveryTrait_onlyMRs(), "2");
    result.add(Messages.BranchDiscoveryTrait_allBranches(), "3");
    return result;
}
 
Example 20
/**
 * Populates the strategy options.
 *
 * @return the stategy options.
 */
@NonNull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler
public ListBoxModel doFillStrategyIdItems() {
    ListBoxModel result = new ListBoxModel();
    result.add(Messages.ForkMergeRequestDiscoveryTrait_mergeOnly(), "1");
    result.add(Messages.ForkMergeRequestDiscoveryTrait_headOnly(), "2");
    result.add(Messages.ForkMergeRequestDiscoveryTrait_headAndMerge(), "3");
    return result;
}
 
Example 21
/**
 * Form validation for the regular expression.
 *
 * @param value the regular expression.
 * @return the validation results.
 */
@Restricted(NoExternalUse.class) // stapler
public FormValidation doCheckRegex(@QueryParameter String value) {
    try {
        Pattern.compile(value);
        return FormValidation.ok();
    } catch (PatternSyntaxException e) {
        return FormValidation.error(e.getMessage());
    }
}
 
Example 22
Source Project: gitea-plugin   Source File: WebhookRegistrationTrait.java    License: MIT License 5 votes vote down vote up
/**
 * Form completion.
 *
 * @return the mode options.
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillModeItems() {
    ListBoxModel result = new ListBoxModel();
    result.add(Messages.WebhookRegistrationTrait_disableHook(), WebhookRegistration.DISABLE.toString());
    result.add(Messages.WebhookRegistrationTrait_useItemHook(), WebhookRegistration.ITEM.toString());
    return result;
}
 
Example 23
Source Project: gitea-plugin   Source File: SSHCheckoutTrait.java    License: MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillCredentialsIdItems(@CheckForNull @AncestorInPath Item context,
                                             @QueryParameter String serverUrl,
                                             @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
                && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.add(Messages.SSHCheckoutTrait_useAgentKey(), "");
    result.includeMatchingAs(
            context instanceof Queue.Task ?
                    ((Queue.Task) context).getDefaultAuthentication()
                    : ACL.SYSTEM,
            context,
            StandardUsernameCredentials.class,
            URIRequirementBuilder.fromUri(serverUrl).build(),
            CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
    );
    return result;
}
 
Example 24
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillTocItems() {
    ListBoxModel items = new ListBoxModel();
    for (TocType tocType : TocType.values()) {
        items.add(tocType.getToc(), tocType.name());
    }
    return items;
}
 
Example 25
Source Project: pipeline-maven-plugin   Source File: WithMavenStep.java    License: MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillMavenSettingsConfigItems(@AncestorInPath ItemGroup context) {
    ListBoxModel r = new ListBoxModel();
    r.add("--- Use system default settings or file path ---",null);
    for (Config config : ConfigFiles.getConfigsInContext(context, MavenSettingsConfigProvider.class)) {
        r.add(config.name, config.id);
    }
    return r;
}
 
Example 26
@Restricted(NoExternalUse.class) // Only for UI calls
public ListBoxModel doFillFormatItems() {
    ListBoxModel items = new ListBoxModel();
    for (FormatType formatType : FormatType.values()) {
        items.add(formatType.getFormat(), formatType.name());
    }
    return items;
}
 
Example 27
Source Project: gitea-plugin   Source File: ForkPullRequestDiscoveryTrait.java    License: MIT License 5 votes vote down vote up
/**
 * Populates the strategy options.
 *
 * @return the stategy options.
 */
@NonNull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler
public ListBoxModel doFillStrategyIdItems() {
    ListBoxModel result = new ListBoxModel();
    result.add(Messages.ForkPullRequestDiscoveryTrait_mergeOnly(), "1");
    result.add(Messages.ForkPullRequestDiscoveryTrait_headOnly(), "2");
    result.add(Messages.ForkPullRequestDiscoveryTrait_headAndMerge(), "3");
    return result;
}
 
Example 28
Source Project: gitea-plugin   Source File: OriginPullRequestDiscoveryTrait.java    License: MIT License 5 votes vote down vote up
/**
 * Populates the strategy options.
 *
 * @return the stategy options.
 */
@NonNull
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler
public ListBoxModel doFillStrategyIdItems() {
    ListBoxModel result = new ListBoxModel();
    result.add(Messages.ForkPullRequestDiscoveryTrait_mergeOnly(), "1");
    result.add(Messages.ForkPullRequestDiscoveryTrait_headOnly(), "2");
    result.add(Messages.ForkPullRequestDiscoveryTrait_headAndMerge(), "3");
    return result;
}
 
Example 29
Source Project: configuration-as-code-plugin   Source File: ConfigurationAsCode.java    License: MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReload(StaplerRequest request, StaplerResponse response) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    configure();
    response.sendRedirect("");
}
 
Example 30
Source Project: configuration-as-code-plugin   Source File: ConfigurationAsCode.java    License: MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doReplace(StaplerRequest request, StaplerResponse response) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String newSource = request.getParameter("_.newSource");
    String normalizedSource = Util.fixEmptyAndTrim(newSource);
    File file = new File(Util.fixNull(normalizedSource));
    if (file.exists() || ConfigurationAsCode.isSupportedURI(normalizedSource)) {
        List<String> candidatePaths = Collections.singletonList(normalizedSource);
        List<YamlSource> candidates = getConfigFromSources(candidatePaths);
        if (canApplyFrom(candidates)) {
            sources = candidatePaths;
            configureWith(getConfigFromSources(getSources()));
            CasCGlobalConfig config = GlobalConfiguration.all().get(CasCGlobalConfig.class);
            if (config != null) {
                config.setConfigurationPath(normalizedSource);
                config.save();
            }
            LOGGER.log(Level.FINE, "Replace configuration with: " + normalizedSource);
        } else {
            LOGGER.log(Level.WARNING, "Provided sources could not be applied");
            // todo: show message in UI
        }
    } else {
        LOGGER.log(Level.FINE, "No such source exists, applying default");
        // May be do nothing instead?
        configure();
    }
    response.sendRedirect("");
}