/** * Safer variant of {@link #impersonate(Authentication)} that does not require a finally-block. * @param auth authentication, such as {@link #SYSTEM} * @param body an action to run with this alternate authentication in effect * @since 1.509 * @deprecated use try with resources and {@link #as(Authentication)} */ @Deprecated public static void impersonate(@Nonnull Authentication auth, @Nonnull Runnable body) { SecurityContext old = impersonate(auth); try { body.run(); } finally { SecurityContextHolder.setContext(old); } }
/** * Convenient short-cut for {@code getACL().hasPermission(a, permission)} * @since 2.92 */ default boolean hasPermission(@Nonnull Authentication a, @Nonnull Permission permission) { if (a == ACL.SYSTEM) { return true; } return getACL().hasPermission(a, permission); }
/** * Convenient short-cut for {@code getACL().checkPermission(permission)} */ default void checkPermission(@Nonnull Permission permission) throws AccessDeniedException { getACL().checkPermission(permission); }
@Override @Nonnull public ACL getACL() { ACL base = Jenkins.get().getAuthorizationStrategy().getACL(this); // always allow a non-anonymous user full control of himself. return ACL.lambda((a, permission) -> (idStrategy().equals(a.getName(), id) && !(a instanceof AnonymousAuthenticationToken)) || base.hasPermission(a, permission)); }
/** * Implementation can choose to provide different ACL for different views. * This can be used as a basis for more fine-grained access control. * * <p> * The default implementation makes the view visible if any of the items are visible * or the view is configurable. * * @since 1.220 */ public @Nonnull ACL getACL(final @Nonnull View item) { return ACL.lambda((a, permission) -> { ACL base = item.getOwner().getACL(); boolean hasPermission = base.hasPermission(a, permission); if (!hasPermission && permission == View.READ) { return base.hasPermission(a,View.CONFIGURE) || !item.getItems().isEmpty(); } return hasPermission; }); }
@Override @Restricted(NoExternalUse.class) public Object getTarget() { if (!SKIP_PERMISSION_CHECK) { if (!getACL().hasPermission(Item.DISCOVER)) { return null; } getACL().checkPermission(Item.READ); } return this; }
/** * Checks if the current security principal has this permission. * * @return false * if the user doesn't have the permission. */ public final boolean hasPermission(@Nonnull Permission p) { Authentication a = Jenkins.getAuthentication(); if (a == SYSTEM) { return true; } return hasPermission(a, p); }
@Override public boolean hasPermission(@Nonnull Authentication a, @Nonnull Permission permission) { return user.equals(User.get(a.getName())) && user.getACL().hasPermission(a, permission); } };
/** * Changes the {@link Authentication} associated with the current thread to the specified one and returns an * {@link AutoCloseable} that restores the previous security context. * * <p> * This makes impersonation much easier within code as it can now be used using the try with resources construct: * <pre> * try (ACLContext ctx = ACL.as(auth)) { * ... * } * </pre> * * @param user the user to impersonate. * @return the previous authentication context * @since 2.14 */ @Nonnull public static ACLContext as(@CheckForNull User user) { return as(user == null ? Jenkins.ANONYMOUS : user.impersonate()); }
private static boolean canDiscoverItem(@Nonnull final String fullName) { final Jenkins jenkins = Jenkins.getInstance(); item = jenkins.getItemByFullName(fullName); } catch (AccessDeniedException ex) { final Authentication userAuth = Jenkins.getAuthentication(); try (ACLContext acl = ACL.as(ACL.SYSTEM)) { final Item itemBySystemUser = jenkins.getItemByFullName(fullName); if (itemBySystemUser == null) {
/** * Securely check for the existence of an item before trying to create one with the same name. * @param parent the folder where we are about to create/rename/move an item * @param newName the proposed new name * @param variant if not null, an existing item which we accept could be there * @throws IllegalArgumentException if there is already something there, which you were supposed to know about * @throws Failure if there is already something there but you should not be told details */ static void verifyItemDoesNotAlreadyExist(@Nonnull ItemGroup<?> parent, @Nonnull String newName, @CheckForNull Item variant) throws IllegalArgumentException, Failure { Item existing; try (ACLContext ctxt = ACL.as(ACL.SYSTEM)) { existing = parent.getItem(newName); } if (existing != null && existing != variant) { if (existing.hasPermission(Item.DISCOVER)) { String prefix = parent.getFullName(); throw new IllegalArgumentException((prefix.isEmpty() ? "" : prefix + "/") + newName + " already exists"); } else { // Cannot hide its existence, so at least be as vague as possible. throw new Failure(""); } } }
public void setChannel(@Nonnull Channel channel, @CheckForNull OutputStream launchLog, @CheckForNull Channel.Listener listener) throws IOException, InterruptedException { if (Util.isRelativePath(remoteFS)) { remoteFS = channel.call(new AbsolutePath(remoteFS)); log.println("NOTE: Relative remote path resolved to: "+remoteFS); SecurityContext old = ACL.impersonate(ACL.SYSTEM); try { for (ComputerListener cl : ComputerListener.all()) { SecurityContextHolder.setContext(old); old = ACL.impersonate(ACL.SYSTEM); try { for (ComputerListener cl : ComputerListener.all()) { SecurityContextHolder.setContext(old); Jenkins.get().getQueue().scheduleMaintenance();
private void checkIfNameIsUsed(@Nonnull String newName) throws Failure { try { Item item = getParent().getItem(newName); throw new Failure(Messages.AbstractItem_NewNameInUse(newName)); try (ACLContext ctx = ACL.as(ACL.SYSTEM)) { item = getParent().getItem(newName); if (item != null) { LOGGER.log(Level.FINE, "Unable to rename the job {0}: name {1} is already in use. " + "User {2} has {3} permission, but no {4} for existing job with the same name", new Object[] {this.getFullName(), newName, User.current(), Item.DISCOVER.name, Item.READ.name} );
private boolean shouldTrigger(Run upstreamBuild, TaskListener listener) { Jenkins jenkins = Jenkins.getInstance(); if (job == null) { return false; downstreamVisible = jenkins.getItemByFullName(job.getFullName()) == job; } catch (AccessDeniedException ex) { Authentication originalAuth = Jenkins.getAuthentication(); Job upstream = upstreamBuild.getParent(); Authentication auth = Tasks.getAuthenticationOf((Queue.Task) job); SecurityContext orig = ACL.impersonate(auth); Item authUpstream = null; try { SecurityContextHolder.setContext(orig);
public void build() { // Set full privileges while computing to avoid missing any projects the current user cannot see. SecurityContext saveCtx = ACL.impersonate(ACL.SYSTEM); try { this.computationalData = new HashMap<Class<?>, Object>(); for( AbstractProject p : Jenkins.getInstance().allItems(AbstractProject.class) ) p.buildDependencyGraph(this); forward = finalize(forward); backward = finalize(backward); topologicalDagSort(); this.computationalData = null; built = true; } finally { SecurityContextHolder.setContext(saveCtx); } }
StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),","); boolean hasProjects = false; while(tokens.hasMoreTokens()) { String projectName = tokens.nextToken().trim(); if (StringUtils.isNotBlank(projectName)) { Item item = Jenkins.getInstance().getItem(projectName,project,Item.class); if (item == null) { Job<?, ?> nearest = Items.findNearest(Job.class, projectName, project.getParent()); String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?"; return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative)); if (!item.getACL().hasPermission(auth, Item.BUILD)) { return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName));
private static void remove(Saveable obj, boolean isDelete) { Jenkins j = Jenkins.getInstance(); OldDataMonitor odm = get(j); SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM); try { odm.data.remove(referTo(obj)); if (isDelete && obj instanceof Job<?, ?>) { for (Run r : ((Job<?, ?>) obj).getBuilds()) { odm.data.remove(referTo(r)); } } } finally { SecurityContextHolder.setContext(oldContext); } }
private void checkPermission(Permission permission) { if (((GitLabConnectionConfig) Jenkins.getInstance().getDescriptor(GitLabConnectionConfig.class)).isUseAuthenticatedEndpoint()) { if (!Jenkins.getActiveInstance().getACL().hasPermission(authentication, permission)) { String message = Messages.AccessDeniedException2_MissingPermission(authentication.getName(), permission.group.title+"/"+permission.name); LOGGER.finest("Unauthorized (Did you forget to add API Token to the web hook ?)"); throw HttpResponses.errorWithoutStack(403, message); } } }
SecurityContext context = ACL.impersonate(ACL.SYSTEM); try { int result = 0; for (TopLevelItem topLevelItem : Jenkins.getInstance().getItemMap().values()) { if (topLevelItem instanceof AbstractProject) { final AbstractProject project = (AbstractProject) topLevelItem; SecurityContextHolder.setContext(context);
/** * Checks if the current user (for which we are processing the current request) * has the admin access. * * @deprecated since 2007-12-18. * This method is deprecated when Hudson moved from simple Unix root-like model * of "admin gets to do everything, and others don't have any privilege" to more * complex {@link hudson.security.ACL} and {@link hudson.security.Permission} based scheme. * * <p> * For a quick migration, use {@code Hudson.getInstance().getACL().hasPermission(Hudson.ADMINISTER)} * To check if the user has the 'administer' role in Hudson. * * <p> * But ideally, your plugin should first identify a suitable {@link hudson.security.Permission} (or create one, * if appropriate), then identify a suitable {@link hudson.security.AccessControlled} object to check its permission * against. */ @Deprecated public static boolean isAdmin() { return Jenkins.getInstance().getACL().hasPermission(ADMINISTER); }