hudson.security.Permission Java Examples

The following examples show how to use hudson.security.Permission. 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: CLICommandInvoker.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
@Override
public ACL getRootACL() {
    return new SidACL() {
        @Override
        protected Boolean hasPermission(Sid u, Permission permission) {
            if (u instanceof PrincipalSid && ((PrincipalSid) u).getPrincipal().equals(username)) {
                for (Permission p = permission; p != null; p = p.impliedBy) {
                    if (permissions.contains(p)) {
                        return true;
                    }
                }
            }
            return false;
        }
    };
}
 
Example #2
Source File: FolderBasedAuthorizationStrategy.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
@Nonnull
@Override
public FolderBasedAuthorizationStrategy newInstance(@Nullable StaplerRequest req, @Nonnull JSONObject formData) {
    AuthorizationStrategy strategy = Jenkins.get().getAuthorizationStrategy();
    if (strategy instanceof FolderBasedAuthorizationStrategy) {
        // this action was invoked from the 'Configure Global Security' page when the
        // old strategy was FolderBasedAuthorizationStrategy; return it back as formData would be empty
        return (FolderBasedAuthorizationStrategy) strategy;
    } else {
        // when this AuthorizationStrategy is selected for the first time, this makes the current
        // user admin (give all permissions) and prevents him/her from getting access denied.
        // The same thing happens in Role Strategy plugin. See RoleBasedStrategy.DESCRIPTOR.newInstance()

        HashSet<PermissionGroup> groups = new HashSet<>(PermissionGroup.getAll());
        groups.remove(PermissionGroup.get(Permission.class));
        Set<PermissionWrapper> adminPermissions = PermissionWrapper.wrapPermissions(
            FolderAuthorizationStrategyManagementLink.getSafePermissions(groups));

        GlobalRole adminRole = new GlobalRole(ADMIN_ROLE_NAME, adminPermissions,
            Collections.singleton(new PrincipalSid(Jenkins.getAuthentication()).getPrincipal()));

        return new FolderBasedAuthorizationStrategy(Collections.singleton(adminRole), Collections.emptySet(),
            Collections.emptySet());
    }
}
 
Example #3
Source File: AbstractAcl.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
private static Set<Permission> cacheImplyingPermissions(Permission permission) {
    Set<Permission> implyingPermissions;

    if (PermissionWrapper.DANGEROUS_PERMISSIONS.contains(permission)) {
        // dangerous permissions should be deferred to Jenkins.ADMINISTER
        implyingPermissions = getImplyingPermissions(Jenkins.ADMINISTER);
    } else {
        implyingPermissions = new HashSet<>();

        for (Permission p = permission; p != null; p = p.impliedBy) {
            implyingPermissions.add(p);
        }
    }

    implyingPermissionsCache.put(permission, implyingPermissions);
    return implyingPermissions;
}
 
Example #4
Source File: GitLabRequireOrganizationMembershipACL.java    From gitlab-oauth-plugin with MIT License 6 votes vote down vote up
public boolean hasRepositoryPermission(GitLabAuthenticationToken authenticationToken, Permission permission) {
    String repositoryName = getRepositoryName();

    if (repositoryName == null) {
        if (authenticatedUserCreateJobPermission) {
            if (permission.equals(Item.READ) ||
                    permission.equals(Item.CONFIGURE) ||
                    permission.equals(Item.DELETE) ||
                    permission.equals(Item.EXTENDED_READ)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else if (checkReadPermission(permission) &&
            authenticationToken.isPublicRepository(repositoryName)) {
        return true;
    } else {
        return authenticationToken.hasRepositoryPermission(repositoryName);
    }
}
 
Example #5
Source File: AbstractAcl.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
@Override
@SuppressFBWarnings(value = "NP_BOOLEAN_RETURN_NULL",
        justification = "hudson.security.SidACL requires null when unknown")
@Nullable
protected Boolean hasPermission(Sid sid, Permission permission) {
    if (PermissionWrapper.DANGEROUS_PERMISSIONS.contains(permission)) {
        permission = Jenkins.ADMINISTER;
    }

    Set<Permission> permissions = permissionList.get(toString(sid));
    if (permissions != null && CollectionUtils.containsAny(permissions, getImplyingPermissions(permission))) {
        return true;
    }

    return null;
}
 
Example #6
Source File: GlobalAclImpl.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
/**
 * Initializes the ACL objects and preemptively calculates all permissions for all sids.
 *
 * @param globalRoles set of roles from which to calculate the permissions.
 */
public GlobalAclImpl(Set<GlobalRole> globalRoles) {
    for (GlobalRole role : globalRoles) {
        Set<Permission> impliedPermissions = ConcurrentHashMap.newKeySet();

        role.getPermissionsUnsorted().parallelStream().map(PermissionWrapper::getPermission).forEach(impliedPermissions::add);

        role.getSids().parallelStream().forEach(sid -> {
            Set<Permission> permissionsForSid = permissionList.get(sid);
            if (permissionsForSid == null) {
                permissionsForSid = new HashSet<>();
            }
            permissionsForSid.addAll(impliedPermissions);
            permissionList.put(sid, permissionsForSid);
        });
    }
}
 
Example #7
Source File: PermissionFinder.java    From folder-auth-plugin with MIT License 6 votes vote down vote up
/**
 * Attempt to match a given permission to what is defined in the UI.
 * @param id String of the form "Title/Permission" (Look in the UI) for a particular permission
 * @return a matched permission ID
 */
@CheckForNull
public static String findPermissionId(String id) {
    List<PermissionGroup> pgs = PermissionGroup.getAll();
    Matcher m = PERMISSION_PATTERN.matcher(id);
    if(m.matches()) {
        String owner = m.group(1);
        String name = m.group(2);
        for(PermissionGroup pg : pgs) {
            if(pg.owner.equals(Permission.class)) {
                continue;
            }
            if(pg.getId().equals(owner)) {
                return pg.owner.getName() + "." + name;
            }
        }
    }
    return null;
}
 
Example #8
Source File: OrganizationFolderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testOrganizationFolderFactory() throws Exception{
    List<OrganizationFolderPipelineImpl.OrganizationFolderFactory> organizationFolderFactoryList = ExtensionList.lookup(OrganizationFolderPipelineImpl.OrganizationFolderFactory.class);
    OrganizationFolderFactoryTestImpl organizationFolderFactoryTest = ((ExtensionList<OrganizationFolderPipelineImpl.OrganizationFolderFactory>) organizationFolderFactoryList).get(OrganizationFolderFactoryTestImpl.class);
    assertNotNull(organizationFolderFactoryTest);

    OrganizationFolderPipelineImpl folderPipeline = organizationFolderFactoryTest.getFolder(orgFolder, new Reachable() {
        @Override
        public Link getLink() {
            return organization.getLink().rel("/pipelines/");
        }
    }, mockOrganization());
    assertNotNull(folderPipeline);

    assertNotNull(folderPipeline.getQueue());
    assertNotNull(folderPipeline.getQueue().iterator());

    //Make sure the user does has permissions to that folder
    PowerMockito.when(orgFolder.getACL()).thenReturn(new ACL() {
        @Override
        public boolean hasPermission(Authentication arg0, Permission arg1) {
            return true;
        }
    });

    ScmResourceImpl scmResource = new ScmResourceImpl(orgFolder, folderPipeline);
    StaplerRequest staplerRequest = PowerMockito.mock(StaplerRequest.class);
    assertEquals("hello", scmResource.getContent(staplerRequest));
}
 
Example #9
Source File: CLICommandInvoker.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * @deprecated Rather use {@link #asUser}.
 */
@Deprecated
public CLICommandInvoker authorizedTo(final Permission... permissions) {

    this.permissions = Arrays.asList(permissions);
    return this;
}
 
Example #10
Source File: GitLabRequireOrganizationMembershipACL.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
private boolean checkReadPermission(Permission permission) {
    if (permission.getId().equals("hudson.model.Hudson.Read")
            || permission.getId().equals("hudson.model.Item.Workspace")
            || permission.getId().equals("hudson.model.Item.Read")) {
        return true;
    } else {
        return false;
    }
}
 
Example #11
Source File: GitLabRequireOrganizationMembershipACL.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
private boolean testBuildPermission(Permission permission) {
    if (permission.getId().equals("hudson.model.Hudson.Build")
            || permission.getId().equals("hudson.model.Item.Build")) {
        return true;
    } else {
        return false;
    }
}
 
Example #12
Source File: OrganizationFolderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test(expected = ServiceException.ForbiddenException.class)
public void testOrganizationFolderFactoryNoPermissionsFolder() throws Exception {
    List<OrganizationFolderPipelineImpl.OrganizationFolderFactory> organizationFolderFactoryList = ExtensionList.lookup(OrganizationFolderPipelineImpl.OrganizationFolderFactory.class);
    OrganizationFolderFactoryTestImpl organizationFolderFactoryTest = ((ExtensionList<OrganizationFolderPipelineImpl.OrganizationFolderFactory>) organizationFolderFactoryList).get(OrganizationFolderFactoryTestImpl.class);
    assertNotNull(organizationFolderFactoryTest);

    OrganizationFolderPipelineImpl folderPipeline = organizationFolderFactoryTest.getFolder(orgFolder, new Reachable() {
        @Override
        public Link getLink() {
            return organization.getLink().rel("/pipelines/");
        }
    }, mockOrganization());
    assertNotNull(folderPipeline);

    assertNotNull(folderPipeline.getQueue());
    assertNotNull(folderPipeline.getQueue().iterator());

    //Make sure the user does not have permissions to that folder
    PowerMockito.when(orgFolder.getACL()).thenReturn(new ACL() {
        @Override
        public boolean hasPermission(Authentication arg0, Permission arg1) {
            return false;
        }
    });

    ScmResourceImpl scmResource = new ScmResourceImpl(orgFolder, folderPipeline);
    StaplerRequest staplerRequest = PowerMockito.mock(StaplerRequest.class);
    assertEquals("hello", scmResource.getContent(staplerRequest));
}
 
Example #13
Source File: MockAuthorizationStrategy.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
/**
 * Begin granting a set of permissions.
 * Note that grants cannot be subsequently revoked, but you could reset the strategy to a newly configured one.
 * @param permissions which permissions to grant ({@link Permission#impliedBy} is honored)
 */
public Grant grant(Permission... permissions) {
    Set<Permission> effective = new HashSet<Permission>(Arrays.asList(permissions));
    boolean added = true;
    while (added) {
        added = false;
        for (Permission p : Permission.getAll()) {
            added |= effective.contains(p.impliedBy) && effective.add(p);
        }
    }
    return new Grant(effective);
}
 
Example #14
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public boolean hasPermission(@Nonnull Authentication a, @Nonnull Permission permission) {
    // its read only so for all permissions other than READ, we return false
    if(permission == CREATE || permission == DELETE ||
            permission == MANAGE_DOMAINS || permission == UPDATE){
        return false;
    }
    return owner.getACL().hasPermission(a,permission);
}
 
Example #15
Source File: UserImplPermissionTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Tests against jenkins
 */
@Test
public void useTestAgainstJenkinsRoot() {
    OrganizationImpl baseOrg = new OrganizationImpl("jenkins", jenkins);
    UserImpl userImpl = new UserImpl(baseOrg, user, baseOrg);
    checkPermissions(userImpl.getPermission(), false, false);

    when(jenkins.getACL()).thenReturn(new ACL() {
        public boolean hasPermission(Authentication a, Permission permission) {
            return true;
        }
    });

    checkPermissions(userImpl.getPermission(), true, true);
}
 
Example #16
Source File: FolderBasedAuthorizationStrategyTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
public void permissionTest() {
    Jenkins jenkins = jenkinsRule.jenkins;

    try (ACLContext ignored = ACL.as(admin)) {
        assertTrue(jenkins.hasPermission(Jenkins.ADMINISTER));
        assertTrue(child3.hasPermission(Item.CONFIGURE));
        assertTrue(job1.hasPermission(Item.READ));
        assertTrue(job2.hasPermission(Item.CREATE));
    }

    try (ACLContext ignored = ACL.as(user1)) {
        assertTrue(jenkins.hasPermission(Permission.READ));
        assertTrue(root.hasPermission(Item.READ));
        assertTrue(job1.hasPermission(Item.READ));
        assertTrue(job2.hasPermission(Item.READ));

        assertFalse(job1.hasPermission(Item.CREATE));
        assertFalse(job1.hasPermission(Item.DELETE));
        assertFalse(job1.hasPermission(Item.CONFIGURE));
        assertFalse(job2.hasPermission(Item.CREATE));
        assertFalse(job2.hasPermission(Item.CONFIGURE));
    }

    try (ACLContext ignored = ACL.as(user2)) {
        assertTrue(jenkins.hasPermission(Permission.READ));
        assertTrue(child2.hasPermission(Item.READ));
        assertTrue(child1.hasPermission(Item.READ));
        assertTrue(job2.hasPermission(Item.CONFIGURE));
        assertFalse(job1.hasPermission(Item.CONFIGURE));
    }
}
 
Example #17
Source File: AbstractAcl.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
private static Set<Permission> getImplyingPermissions(Permission p) {
    Set<Permission> permissions = implyingPermissionsCache.get(p);
    if (permissions != null) {
        return permissions;
    } else {
        return cacheImplyingPermissions(p);
    }
}
 
Example #18
Source File: GenericAclImpl.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
/**
 * Assigns {@code permissions} to each sid in {@code sid}.
 *
 * @param sids        the sids to be assigned {@code permissions}
 * @param permissions the {@link Permission}s to be assigned
 */
public void assignPermissions(Set<String> sids, Set<Permission> permissions) {
    sids.parallelStream().forEach(sid -> {
        Set<Permission> assignedPermissions = permissionList.get(sid);
        if (assignedPermissions == null) {
            assignedPermissions = new HashSet<>();
        }
        assignedPermissions.addAll(permissions);
        permissionList.put(sid, assignedPermissions);
    });
}
 
Example #19
Source File: CLICommandInvoker.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
GrantPermissions(String username, List<Permission> permissions) {
    this.username = username;
    this.permissions = permissions;
    for (Permission p : permissions) {
        p.setEnabled(true);
    }
}
 
Example #20
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 #21
Source File: MockAuthorizationStrategy.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override protected Boolean hasPermission(Sid p, Permission permission) {
    String name = toString(p);
    for (Grant.GrantOn.GrantOnTo grantOnTo : grantsOnTo) {
        if (grantOnTo.matches(path, name, permission)) {
            return true;
        }
    }
    return null; // allow groups to be checked after users, etc.
}
 
Example #22
Source File: SecuredMockFolder.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override
public boolean hasPermission(Permission p) {
    if (super.hasPermission(p)) {
        return true;
    }
    return hasPermissionInField(Jenkins.getAuthentication().getName(), p);
}
 
Example #23
Source File: SecuredMockFolder.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
private boolean hasPermissionInField(String sid, @Nonnull Permission p) {
    if (sid.equals(grantedUser)) {
        if (grantedPermissions != null && grantedPermissions.contains(p.getId())) {
            return true;
        }
    }
    return false;
}
 
Example #24
Source File: SecuredMockFolder.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
public void setPermissions(String username, Permission... permissions) {
    this.grantedUser = username;
    if (grantedPermissions == null) {
        grantedPermissions = new HashSet<String>();
    } else {
        grantedPermissions.clear();
    }
    for (Permission p : permissions) {
        grantedPermissions.add(p.getId());
    }
}
 
Example #25
Source File: ParallelsDesktopConnectorSlaveComputer.java    From jenkins-parallels with MIT License 5 votes vote down vote up
@Override
public boolean hasPermission(Permission permission)
{
	if (permission == CONFIGURE)
		return false;
	return super.hasPermission(permission);
}
 
Example #26
Source File: ParallelsDesktopVMSlaveComputer.java    From jenkins-parallels with MIT License 5 votes vote down vote up
@Override
public boolean hasPermission(Permission permission)
{
	if (permission == CONFIGURE)
		return false;
	return super.hasPermission(permission);
}
 
Example #27
Source File: KubernetesComputer.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public ACL getACL() {
    final ACL base = super.getACL();
    return new ACL() {
        @Override
        public boolean hasPermission(Authentication a, Permission permission) {
            return permission == Computer.CONFIGURE ? false : base.hasPermission(a,permission);
        }
    };
}
 
Example #28
Source File: GitHubPRRepositoryTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private void hasPermissionExpectation(Permission permission, boolean isAllowed) {
    PowerMockito.mockStatic(Jenkins.class);
    when(Jenkins.getInstance()).thenReturn(instance);
    when(instance.hasPermission(permission)).thenReturn(isAllowed);
    PowerMockito.mockStatic(User.class);
    when(User.current()).thenReturn(user);
}
 
Example #29
Source File: DockerTraceabilityRootAction.java    From docker-traceability-plugin with MIT License 5 votes vote down vote up
/**
 * Check permission.
 * Also prohibits the access if Jenkins has not been started yet.
 * @param p Permission to be checked
 * @throws AccessDeniedException Access denied
 */
private void checkPermission(Permission p) throws AccessDeniedException {
    final Jenkins j = Jenkins.getInstance();
    if (j == null) {
        throw new AccessDeniedException("Cannot retrieve Jenkins instance. "
                + "Probably, the service is starting or shutting down");
    }     
    j.checkPermission(p);
}
 
Example #30
Source File: BuildWebHookAction.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private void checkPermission(Permission permission, Item project) {
    if (((GitLabConnectionConfig) Jenkins.get().getDescriptor(GitLabConnectionConfig.class)).isUseAuthenticatedEndpoint()) {
        if (!project.getACL().hasPermission(authentication, permission)) {
            String message =  String.format("%s is missing the %s/%s permission", 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);
        }
    }
}