org.kohsuke.accmod.Restricted Java Examples

The following examples show how to use org.kohsuke.accmod.Restricted. 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: PersonalAccessTokenImpl.java    From gitea-plugin with 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 #2
Source File: GiteaServer.java    From gitea-plugin with 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 File: ConfigurationAsCode.java    From configuration-as-code-plugin with 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 #4
Source File: GitLabServer.java    From gitlab-branch-source-plugin with 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 #5
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with 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 #6
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@VisibleForTesting
@Restricted(NoExternalUse.class)
public static void serializeYamlNode(Node root, Writer writer) throws IOException {
    DumperOptions options = new DumperOptions();
    options.setDefaultFlowStyle(BLOCK);
    options.setDefaultScalarStyle(PLAIN);
    options.setSplitLines(true);
    options.setPrettyFlow(true);
    Serializer serializer = new Serializer(new Emitter(writer, options), new Resolver(),
            options, null);
    serializer.open();
    serializer.serialize(root);
    serializer.close();
}
 
Example #7
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Export JSONSchema to URL
 * @throws Exception
 */
@Restricted(NoExternalUse.class)
public void doSchema(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    res.setContentType("application/json; charset=utf-8");
    res.getWriter().print(writeJSONSchema());
}
 
Example #8
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public static String printThrowable(@NonNull Throwable t) {
    String s = Functions.printThrowable(t)
        .split("at io.jenkins.plugins.casc.ConfigurationAsCode.export")[0]
        .replaceAll("\t", "  ");
    return s.substring(0, s.lastIndexOf(")") + 1);
}
 
Example #9
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Retrieve which plugin do provide this extension point, used in documentation.jelly
 *
 * @return String representation of the extension source, usually artifactId.
 */
@Restricted(NoExternalUse.class)
@CheckForNull
public String getExtensionSource(Configurator c) throws IOException {
    final Class e = c.getImplementedAPI();
    final String jar = Which.jarFile(e).getName();
    if (jar.startsWith("jenkins-core-")) { // core jar has version in name
        return "jenkins-core";
    }
    return jar.substring(0, jar.lastIndexOf('.'));
}
 
Example #10
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
/**
 * Retrieve the html help tip associated to an attribute, used in documentation.jelly
 * FIXME would prefer &lt;st:include page="help-${a.name}.html" class="${c.target}" optional="true"/&gt;
 * @param attribute to get help for
 * @return String that shows help. May be empty
 * @throws IOException if the resource cannot be read
 */
@Restricted(NoExternalUse.class)
@NonNull
public String getHtmlHelp(Class type, String attribute) throws IOException {
    final URL resource = Klass.java(type).getResource("help-" + attribute + ".html");
    if (resource != null) {
        return IOUtils.toString(resource.openStream(), StandardCharsets.UTF_8);
    }
    return "";
}
 
Example #11
Source File: DefaultGiteaConnection.java    From gitea-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
protected HttpURLConnection openConnection(UriTemplate template) throws IOException {
    URL url = new URL(template.expand());
    Jenkins jenkins = Jenkins.get();
    if (jenkins.proxy == null) {
        return (HttpURLConnection) url.openConnection();
    }
    return (HttpURLConnection) url.openConnection(jenkins.proxy.createProxy(url.getHost()));
}
 
Example #12
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public void doReference(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    req.getView(this, "reference.jelly").forward(req, res);
}
 
Example #13
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@RequirePOST
@Restricted(NoExternalUse.class)
public void doViewExport(StaplerRequest req, StaplerResponse res) throws Exception {
    if (!Jenkins.get().hasPermission(Jenkins.SYSTEM_READ)) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    export(out);

    req.setAttribute("export", out.toString(StandardCharsets.UTF_8.name()));
    req.getView(this, "viewExport.jelly").forward(req, res);
}
 
Example #14
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@POST
@Restricted(NoExternalUse.class)
public FormValidation doCheckNewSource(@QueryParameter String newSource) {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    String normalizedSource = Util.fixEmptyAndTrim(newSource);
    File file = new File(Util.fixNull(normalizedSource));
    if (normalizedSource == null) {
        return FormValidation.ok(); // empty, do nothing
    }
    if (!file.exists() && !ConfigurationAsCode.isSupportedURI(normalizedSource)) {
        return FormValidation.error("Configuration cannot be applied. File or URL cannot be parsed or do not exist.");
    }

    List<YamlSource> yamlSources = Collections.emptyList();
    try {
        List<String> sources = Collections.singletonList(normalizedSource);
        yamlSources = getConfigFromSources(sources);
        final Map<Source, String> issues = checkWith(yamlSources);
        final JSONArray errors = collectProblems(issues, "error");
        if (!errors.isEmpty()) {
            return FormValidation.error(errors.toString());
        }
        final JSONArray warnings = collectProblems(issues, "warning");
        if (!warnings.isEmpty()) {
            return FormValidation.warning(warnings.toString());
        }
        return FormValidation.okWithMarkup("The configuration can be applied");
    } catch (ConfiguratorException | IllegalArgumentException e) {
        return FormValidation.error(e, e.getCause() == null ? e.getMessage() : e.getCause().getMessage());
    }
}
 
Example #15
Source File: OriginPullRequestDiscoveryTrait.java    From gitea-plugin with 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 #16
Source File: ConfigurationAsCode.java    From configuration-as-code-plugin with 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 #17
Source File: GitLabSCMBranchMonitorStrategy.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public FormValidation doCheckIncludes(@QueryParameter String includes) {
    if (includes.isEmpty()) {
        return FormValidation.warning(Messages.GitLabSCMBranchMonitorStrategy_did_you_mean_to_use_to_match_all_branches());
    }
    return FormValidation.ok();
}
 
Example #18
Source File: FolderAuthorizationStrategyManagementLink.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@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 #19
Source File: ForkPullRequestDiscoveryTrait.java    From gitea-plugin with 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 #20
Source File: GitLabSCMNavigator.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillProjectSelectorIdItems() {
    ListBoxModel items = new ListBoxModel();
    for (String id : GitLabProjectSelector.ids()) {
        items.add(id, id);
    }
    return items;
}
 
Example #21
Source File: SSHCheckoutTrait.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * Validation for checkout credentials.
 *
 * @param context   the context.
 * @param serverUrl the server url.
 * @param value     the current selection.
 * @return the validation results
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public FormValidation doCheckCredentialsId(@CheckForNull @AncestorInPath Item context,
                                           @QueryParameter String serverUrl,
                                           @QueryParameter String value) {
    if (context == null
            ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
            : !context.hasPermission(Item.EXTENDED_READ)) {
        return FormValidation.ok();
    }
    if (StringUtils.isBlank(value)) {
        // use agent key
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider
                    .lookupCredentials(SSHUserPrivateKey.class, context, context instanceof Queue.Task
                            ? ((Queue.Task) context).getDefaultAuthentication()
                            : ACL.SYSTEM, URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider
                    .lookupCredentials(StandardUsernameCredentials.class, context, context instanceof Queue.Task
                            ? ((Queue.Task) context).getDefaultAuthentication()
                            : ACL.SYSTEM, URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.error(Messages.SSHCheckoutTrait_incompatibleCredentials());
    }
    return FormValidation.warning(Messages.SSHCheckoutTrait_missingCredentials());
}
 
Example #22
Source File: SSHCheckoutTrait.java    From gitea-plugin with 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 #23
Source File: WebhookRegistrationTrait.java    From gitea-plugin with 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 #24
Source File: GitLabSCMNavigator.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillProjectVisibilityIdItems() {
    ListBoxModel items = new ListBoxModel();
    for (String id : GitLabProjectVisibility.ids()) {
        items.add(id, id);
    }
    return items;
}
 
Example #25
Source File: GerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@Restricted(DoNotUse.class)
@DataBoundSetter
public void setExtensions(@CheckForNull List<GitSCMExtension> extensions) {
  List<SCMSourceTrait> traits = new ArrayList<>(this.traits);
  for (Iterator<SCMSourceTrait> iterator = traits.iterator(); iterator.hasNext(); ) {
    if (iterator.next() instanceof GitSCMExtensionTrait) {
      iterator.remove();
    }
  }
  EXTENSIONS:
  for (GitSCMExtension extension : Util.fixNull(extensions)) {
    for (SCMSourceTraitDescriptor d : SCMSourceTrait.all()) {
      if (d instanceof GitSCMExtensionTraitDescriptor) {
        GitSCMExtensionTraitDescriptor descriptor = (GitSCMExtensionTraitDescriptor) d;
        if (descriptor.getExtensionClass().isInstance(extension)) {
          try {
            SCMSourceTrait trait = descriptor.convertToTrait(extension);
            if (trait != null) {
              traits.add(trait);
              continue EXTENSIONS;
            }
          } catch (UnsupportedOperationException e) {
            LOGGER.log(
                Level.WARNING,
                "Could not convert " + extension.getClass().getName() + " to a trait",
                e);
          }
        }
      }
      LOGGER.log(
          Level.FINE,
          "Could not convert {0} to a trait (likely because this option does not "
              + "make sense for a GitSCMSource)",
          extension.getClass().getName());
    }
  }
  setTraits(traits);
}
 
Example #26
Source File: GitLabSCMSourceSettings.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public ListBoxModel doFillConnectionNameItems() {
    ListBoxModel items = new ListBoxModel();
    for (String name : gitLabConnectionNames()) {
        items.add(name, name);
    }
    return items;
}
 
Example #27
Source File: GerritSCMSource.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@Restricted(DoNotUse.class)
@DataBoundSetter
public void setBrowser(GitRepositoryBrowser browser) {
  List<SCMSourceTrait> traits = new ArrayList<>(this.traits);
  for (Iterator<SCMSourceTrait> iterator = traits.iterator(); iterator.hasNext(); ) {
    if (iterator.next() instanceof GitBrowserSCMSourceTrait) {
      iterator.remove();
    }
  }
  if (browser != null) {
    traits.add(new GitBrowserSCMSourceTrait(browser));
  }
  setTraits(traits);
}
 
Example #28
Source File: ChangeRequestBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Restricted(ProtectedExternally.class)
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision lastBuiltRevision, @CheckForNull SCMRevision lastSeenRevision, @NonNull TaskListener listener) {
    if (!(head instanceof ChangeRequestSCMHead)) {
        return false;
    }
    if (ignoreTargetOnlyChanges
            && currRevision instanceof ChangeRequestSCMRevision
            && lastBuiltRevision instanceof ChangeRequestSCMRevision) {
        ChangeRequestSCMRevision<?> curr = (ChangeRequestSCMRevision<?>) currRevision;
        if (curr.isMerge() && curr.equivalent((ChangeRequestSCMRevision<?>) lastBuiltRevision)) {
            return false;
        }
    }
    try {
        if (ignoreUntrustedChanges && !currRevision.equals(source.getTrustedRevision(currRevision, listener))) {
            return false;
        }
    } catch (IOException | InterruptedException e) {
        LogRecord lr = new LogRecord(Level.WARNING,
                "Could not determine trust status for revision {0} of {1}, assuming untrusted");
        lr.setParameters(new Object[] {currRevision, head});
        lr.setThrown(e);
        Functions.printLogRecord(lr);
        return false;
    }
    return true;
}
 
Example #29
Source File: ChangeRequestBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Restricted(ProtectedExternally.class)
@Deprecated
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision prevRevision, @NonNull TaskListener taskListener) {
    return isAutomaticBuild(source,head, currRevision, prevRevision, prevRevision, taskListener);
}
 
Example #30
Source File: NamedBranchBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 5 votes vote down vote up
/**
 * 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());
    }
}