org.springframework.security.acls.model.Sid Java Examples

The following examples show how to use org.springframework.security.acls.model.Sid. 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: AccessService.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Transactional
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN + " or hasPermission(#ae, 'ADMINISTRATION')")
public MutableAclRecord update(AclEntity ae, int accessEntryIndex, Permission newPermission) {
    Message msg = MsgPicker.getMsg();

    if (ae == null)
        throw new BadRequestException(msg.getACL_DOMAIN_NOT_FOUND());
    if (newPermission == null)
        throw new BadRequestException(msg.getACL_PERMISSION_REQUIRED());

    MutableAclRecord acl = aclService.readAcl(new ObjectIdentityImpl(ae));
    Sid sid = acl.getAclRecord().getAccessControlEntryAt(accessEntryIndex).getSid();

    secureOwner(acl, sid);

    return aclService.upsertAce(acl, sid, newPermission);
}
 
Example #2
Source File: PermissionServiceDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testCreatePermission() {
  setSu();
  ObjectIdentity objectIdentity = new ObjectIdentityImpl("type", "identifier");
  Sid sid = new PrincipalSid("user");

  MutableAcl acl = mock(MutableAcl.class);
  when(acl.getOwner()).thenReturn(sid);
  when(mutableAclService.readAclById(objectIdentity)).thenReturn(acl);

  Permission permission = Permission.create(objectIdentity, sid, PermissionSet.WRITE);

  when(mutableAclClassService.getAclClassTypes()).thenReturn(singletonList("type"));

  permissionServiceDecorator.createPermission(permission);
  verify(permissionService).createPermission(permission);
  resetContext();
}
 
Example #3
Source File: AccessService.java    From kylin with Apache License 2.0 6 votes vote down vote up
@Transactional
@PreAuthorize(Constant.ACCESS_HAS_ROLE_ADMIN + " or hasPermission(#ae, 'ADMINISTRATION')")
public void batchGrant(AclEntity ae, Map<Sid, Permission> sidToPerm) {
    Message msg = MsgPicker.getMsg();

    if (ae == null)
        throw new BadRequestException(msg.getACL_DOMAIN_NOT_FOUND());
    if (sidToPerm == null)
        throw new BadRequestException(msg.getACL_PERMISSION_REQUIRED());

    MutableAclRecord acl;
    try {
        acl = aclService.readAcl(new ObjectIdentityImpl(ae));
    } catch (NotFoundException e) {
        acl = init(ae, null);
    }

    for (Sid sid : sidToPerm.keySet()) {
        secureOwner(acl, sid);
    }
    aclService.batchUpsertAce(acl, sidToPerm);
}
 
Example #4
Source File: PermissionInheritanceResolver.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Set<LabelledPermission> convertInheritedRolePermissions(
    List<InheritedUserPermissionsResult> requestedAclParentRolesPermissions) {
  Set<LabelledPermission> results = new HashSet<>();
  for (InheritedUserPermissionsResult parentRolePermission : requestedAclParentRolesPermissions) {
    PermissionSet ownPermission = parentRolePermission.getOwnPermission();
    Sid sid = parentRolePermission.getSid();
    Set<LabelledPermission> labelledPermissions = null;
    if (parentRolePermission.getInheritedUserPermissionsResult() != null) {
      labelledPermissions =
          convertInheritedRolePermissions(
              parentRolePermission.getInheritedUserPermissionsResult());
    }
    results.add(LabelledPermission.create(sid, null, ownPermission, labelledPermissions));
  }
  return results;
}
 
Example #5
Source File: AclService.java    From kylin with Apache License 2.0 6 votes vote down vote up
@Override
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> oids, List<Sid> sids) throws NotFoundException {
    Map<ObjectIdentity, Acl> aclMaps = new HashMap<>();
    for (ObjectIdentity oid : oids) {
        AclRecord record = getAclRecordByCache(objID(oid));
        if (record == null) {
            Message msg = MsgPicker.getMsg();
            throw new NotFoundException(String.format(Locale.ROOT, msg.getACL_INFO_NOT_FOUND(), oid));
        }

        Acl parentAcl = null;
        if (record.isEntriesInheriting() && record.getParentDomainObjectInfo() != null)
            parentAcl = readAclById(record.getParentDomainObjectInfo());

        record.init(parentAcl, aclPermissionFactory, permissionGrantingStrategy);

        aclMaps.put(oid, new MutableAclRecord(record));
    }
    return aclMaps;
}
 
Example #6
Source File: AccessService.java    From kylin with Apache License 2.0 6 votes vote down vote up
private Map<String, Integer> getProjectPermission(String project) {
    Map<String, Integer> SidWithPermission = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

    String uuid = ProjectManager.getInstance(KylinConfig.getInstanceFromEnv()).getProject(project).getUuid();
    AclEntity ae = getAclEntity(AclEntityType.PROJECT_INSTANCE, uuid);
    Acl acl = getAcl(ae);
    if (acl != null && acl.getEntries() != null) {
        List<AccessControlEntry> aces = acl.getEntries();
        for (AccessControlEntry ace : aces) {
            Sid sid = ace.getSid();
            if (sid instanceof PrincipalSid) {
                String principal = ((PrincipalSid) sid).getPrincipal();
                SidWithPermission.put(principal, ace.getPermission().getMask());
            }
            if (sid instanceof GrantedAuthoritySid) {
                String grantedAuthority = ((GrantedAuthoritySid) sid).getGrantedAuthority();
                SidWithPermission.put(grantedAuthority, ace.getPermission().getMask());
            }
        }
    }
    return SidWithPermission;
}
 
Example #7
Source File: PermissionServiceImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void deleteAce(Sid sid, MutableAcl acl) {
  int nrEntries = acl.getEntries().size();
  boolean updated = false;
  for (int i = nrEntries - 1; i >= 0; i--) {
    AccessControlEntry accessControlEntry = acl.getEntries().get(i);
    if (accessControlEntry.getSid().equals(sid)) {
      acl.deleteAce(i);
      updated = true;
    }
  }
  if (updated) {
    mutableAclService.updateAcl(acl);
  }
}
 
Example #8
Source File: ObjectIdentityServiceImplTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testGetObjectIdentities1() {
  Map<String, Object> paramMap = new HashMap<>();
  paramMap.put("classId", "classId");
  paramMap.put("sids", Collections.singletonList("user1"));
  paramMap.put("limit", 10);
  paramMap.put("offset", 20);

  List<Map<String, Object>> result = new ArrayList<>();
  Map<String, Object> result1 = new HashMap<>();
  result1.put("object_id_identity", "test1");
  result1.put("class", "classId");
  Map<String, Object> result2 = new HashMap<>();
  result2.put("object_id_identity", "test2");
  result2.put("class", "classId");
  result.addAll(Arrays.asList(result1, result2));
  doReturn(result)
      .when(jdbcTemplate)
      .queryForList(
          "SELECT DISTINCT acl_object_identity.object_id_identity, acl_class.class FROM acl_object_identity LEFT JOIN acl_class ON acl_object_identity.object_id_class = acl_class.id LEFT JOIN acl_entry ON acl_entry.acl_object_identity = acl_object_identity.id LEFT JOIN acl_sid ON acl_entry.sid = acl_sid.id WHERE acl_class.class = :classId AND acl_sid.sid IN (:sids) ORDER BY acl_object_identity.object_id_identity ASC LIMIT :limit OFFSET :offset",
          paramMap);
  Sid sid = new PrincipalSid("user1");
  ObjectIdentity identity1 = mock(ObjectIdentity.class);
  ObjectIdentity identity2 = mock(ObjectIdentity.class);
  doReturn(identity1).when(entityHelper).getObjectIdentity("classId", "test1");
  doReturn(identity2).when(entityHelper).getObjectIdentity("classId", "test2");
  List<ObjectIdentity> expected = Arrays.asList(identity1, identity2);
  assertEquals(
      expected, objectIdentityService.getObjectIdentities("classId", singleton(sid), 10, 20));
}
 
Example #9
Source File: AccessServiceTest.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void test100000Entries() throws JsonProcessingException {
    MockAclEntity ae = new MockAclEntity("100000Entries");
    long time = System.currentTimeMillis();
    for (int i = 0; i < 100000; i++) {
        if (i % 10 == 0) {
            long now = System.currentTimeMillis();
            System.out.println((now - time) + " ms for last 10 entries, total " + i);
            time = now;
        }
        Sid sid = accessService.getSid("USER" + i, true);
        accessService.grant(ae, AclPermission.OPERATION, sid);
    }
}
 
Example #10
Source File: PermissionsController.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Set<Sid> getSidsFromQuery(String queryString) {
  Set<Sid> sids = Collections.emptySet();
  if (!Strings.isNullOrEmpty(queryString)) {
    try {
      Node node = rsqlParser.parse(queryString);
      PermissionsQuery permissionsQuery = node.accept(new PermissionRsqlVisitor());
      sids =
          new LinkedHashSet<>(
              userRoleTools.getSids(permissionsQuery.getUsers(), permissionsQuery.getRoles()));
    } catch (RSQLParserException e) {
      throw new PermissionQueryParseException(e);
    }
  }
  return sids;
}
 
Example #11
Source File: PermissionServiceDecorator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Set<LabelledPermission> getPermissionsForObject(
    ObjectIdentity objectIdentity, Set<Sid> sids, boolean isReturnInheritedPermissions) {
  checkForSu(sids);
  checkReadPermission(objectIdentity.getType(), sids);
  return permissionService.getPermissionsForObject(
      objectIdentity, sids, isReturnInheritedPermissions);
}
 
Example #12
Source File: PermissionInheritanceResolver.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<InheritedUserPermissionsResult> getPermissionsForRoles(Acl acl, Sid sid) {
  List<Sid> roles = userRoleTools.getRolesForSid(sid);
  List<InheritedUserPermissionsResult> inheritedUserPermissionsResults = new ArrayList<>();
  for (Sid role : roles) {
    PermissionSet ownPermission = getPermissionsForAcl(acl, role);
    List<InheritedUserPermissionsResult> parentRolePernissionResult =
        getPermissionsForRoles(acl, role);
    InheritedUserPermissionsResult inheritedUserPermissionsResult =
        InheritedUserPermissionsResult.create(role, ownPermission, parentRolePernissionResult);
    if (isNotEmpty(inheritedUserPermissionsResult)) {
      inheritedUserPermissionsResults.add(inheritedUserPermissionsResult);
    }
  }
  return inheritedUserPermissionsResults;
}
 
Example #13
Source File: PermissionGrantingContext.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
void setCurrentSid(Sid currentSid) {
    this.currentSid = currentSid;
    currentSidTenants.clear();
    this.currentSidTenant = strategy.getTenantFromSid(this.currentSid);
    if(this.currentSidTenant == MultiTenancySupport.NO_TENANT) {
        this.currentSidTenant = this.currentDefaultTenant;
    }
    currentSidTenants.add(currentSidTenant);
    strategy.tenantsService.getChildTenants(currentSidTenant, currentSidTenants);
}
 
Example #14
Source File: PermissionManagerController.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@PreAuthorize("hasAnyRole('ROLE_SU')")
@Transactional(readOnly = true)
@GetMapping("/package/user/{username}")
@ResponseBody
public Permissions getUserPackagePermissions(@PathVariable String username) {
  Sid sid = createUserSid(username);
  return getPackagePermissions(sid);
}
 
Example #15
Source File: ValidateUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private List<Sid> getAllSids(String project) {
    List<Sid> allSids = new ArrayList<>();
    ProjectInstance prj = projectService.getProjectManager().getProject(project);
    AclEntity ae = accessService.getAclEntity("ProjectInstance", prj.getUuid());
    Acl acl = accessService.getAcl(ae);
    if (acl != null && acl.getEntries() != null) {
        for (AccessControlEntry ace : acl.getEntries()) {
            allSids.add(ace.getSid());
        }
    }
    return allSids;
}
 
Example #16
Source File: JpaMutableAclService.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
/**
 * Creates an entry in the acl_object_identity table for the passed ObjectIdentity. The Sid is also
 * necessary, as acl_object_identity has defined the sid column as non-null.
 *
 * @param object to represent an acl_object_identity for
 * @param owner for the SID column (will be created if there is no acl_sid entry for this particular Sid already)
 * @return
 */
protected void createObjectIdentity(ObjectIdentity object, Sid owner) {
    AclSid sid = createOrRetrieveSidPrimaryKey(owner, true);
    AclClass clazz = createOrRetrieveClassPrimaryKey(object.getType(), true);
    AclObjectIdentity identity = new AclObjectIdentity();
    identity.setObjIdClass(clazz);
    identity.setObjIdIdentity((Long) object.getIdentifier());
    identity.setOwner(sid);
    identity.setEntriesInheriting(Boolean.TRUE);
    aclDao.createObjectIdentity(identity);

}
 
Example #17
Source File: WebAppPermissionRegistryTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testGetPermissions() {
  Multimap<ObjectIdentity, Pair<PermissionSet, Sid>> permissions =
      new WebAppPermissionRegistry().getPermissions();
  assertFalse(permissions.isEmpty());
  Collection<Pair<PermissionSet, Sid>> pairs =
      permissions.get(new PluginIdentity(HomeController.ID));
  assertEquals(
      singleton(new Pair<>(READ, new GrantedAuthoritySid("ROLE_ANONYMOUS"))), copyOf(pairs));
}
 
Example #18
Source File: JpaMutableAclService.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException {
    Map<ObjectIdentity, Acl> map = readAclsById(Arrays.asList(object), sids);
    Assert.isTrue(map.containsKey(object), "There should have been an Acl entry for ObjectIdentity " + object);

    return (Acl) map.get(object);
}
 
Example #19
Source File: JpaMutableAclService.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
/**
 * Creates an entry in the acl_object_identity table for the passed ObjectIdentity. The Sid is also
 * necessary, as acl_object_identity has defined the sid column as non-null.
 *
 * @param object to represent an acl_object_identity for
 * @param owner for the SID column (will be created if there is no acl_sid entry for this particular Sid already)
 * @return
 */
protected void createObjectIdentity(ObjectIdentity object, Sid owner) {
    AclSid sid = createOrRetrieveSidPrimaryKey(owner, true);
    AclClass clazz = createOrRetrieveClassPrimaryKey(object.getType(), true);
    AclObjectIdentity identity = new AclObjectIdentity();
    identity.setObjIdClass(clazz);
    identity.setObjIdIdentity((Long) object.getIdentifier());
    identity.setOwner(sid);
    identity.setEntriesInheriting(Boolean.TRUE);
    aclDao.createObjectIdentity(identity);

}
 
Example #20
Source File: AclService.java    From kylin with Apache License 2.0 5 votes vote down vote up
void batchUpsertAce(MutableAclRecord acl, final Map<Sid, Permission> sidToPerm) {
    updateAclWithRetry(acl, new AclRecordUpdater() {
        @Override
        public void update(AclRecord record) {
            for (Sid sid : sidToPerm.keySet()) {
                record.upsertAce(sidToPerm.get(sid), sid);
            }
        }
    });
}
 
Example #21
Source File: PermissionsController.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Sid getSid(String user, String role) {
  if (isNullOrEmpty(user) && isNullOrEmpty(role)) {
    throw new MissingUserOrRoleException();
  } else if (!isNullOrEmpty(user) && !isNullOrEmpty(role)) {
    throw new UserAndRoleException();
  } else if (!isNullOrEmpty(user)) {
    userRoleTools.checkUserExists(user);
    return createUserSid(user);
  }
  userRoleTools.checkRoleExists(role);
  return createRoleSid(role);
}
 
Example #22
Source File: PermissionServiceDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testExists() {
  setUser();
  ObjectIdentity objectIdentity = new ObjectIdentityImpl("type", "identifier");
  Sid sid = new PrincipalSid("user");
  permissionServiceDecorator.exists(objectIdentity, sid);
  verify(permissionService).exists(objectIdentity, sid);
  resetContext();
}
 
Example #23
Source File: RowLevelSecurityRepositoryDecorator.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void createAcl(Entity entity) {
  MutableAcl acl;
  try {
    acl = mutableAclService.createAcl(new EntityIdentity(entity));
  } catch (AlreadyExistsException e) {
    throw new EntityAlreadyExistsException(entity, e);
  }
  Sid sid = SidUtils.createSecurityContextSid();
  acl.insertAce(acl.getEntries().size(), PermissionSet.WRITE, sid, true);
  mutableAclService.updateAcl(acl);
}
 
Example #24
Source File: PermissionServiceDecoratorTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void testUpdatePermissions() {
  setUser();
  ObjectIdentity objectIdentity = new ObjectIdentityImpl("type", "identifier");
  Sid sid = new PrincipalSid("user");

  MutableAcl acl = mock(MutableAcl.class);
  when(acl.getOwner()).thenReturn(sid);
  when(mutableAclService.readAclById(objectIdentity)).thenReturn(acl);
  when(mutableAclClassService.getAclClassTypes()).thenReturn(singletonList("type"));
  Permission permission = Permission.create(objectIdentity, sid, PermissionSet.WRITE);
  permissionServiceDecorator.updatePermissions(Collections.singleton(permission));
  verify(permissionService).updatePermissions(Collections.singleton(permission));
  resetContext();
}
 
Example #25
Source File: JpaMutableAclService.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Override
public Map<ObjectIdentity, Acl> readAclsById(List<ObjectIdentity> objects, List<Sid> sids) throws NotFoundException {
    Map<ObjectIdentity, Acl> result = lookupStrategy.readAclsById(objects, sids);

    // Check every requested object identity was found (throw NotFoundException if needed)
    for (ObjectIdentity oid : objects) {
        if (!result.containsKey(oid)) {
            throw new NotFoundException("Unable to find ACL information for object identity '" + oid + "'");
        }
    }

    return result;
}
 
Example #26
Source File: PermissionTestUtils.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Acl getSinglePermissionAcl(Sid sid, int mask, String name, Acl parentAcl) {
  Acl acl = mock(Acl.class, name);
  AccessControlEntry ace = mock(AccessControlEntry.class);
  when(ace.getSid()).thenReturn(sid);
  Permission permission = mock(Permission.class);
  when(permission.getMask()).thenReturn(mask);
  when(ace.getPermission()).thenReturn(permission);
  when(acl.getEntries()).thenReturn(Collections.singletonList(ace));
  if (parentAcl != null) {
    when(acl.getParentAcl()).thenReturn(parentAcl);
  }
  return acl;
}
 
Example #27
Source File: ValidateUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private Set<String> getUsersInPrj(List<Sid> allSids) throws IOException {
    Set<String> allUsers = new TreeSet<>();
    for (Sid sid : allSids) {
        if (sid instanceof PrincipalSid) {
            allUsers.add(((PrincipalSid) sid).getPrincipal());
        }
    }
    return allUsers;
}
 
Example #28
Source File: UserRoleTools.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
boolean isSuperUser(Sid sid) {
  String username = getUsername(sid).orElse(null);
  if (username == null) {
    String rolename =
        getRolename(sid)
            .orElseThrow(() -> new IllegalArgumentException("Sid is neither a user nor a role."));
    return AUTHORITY_SU.equals(SidUtils.createRoleAuthority(rolename));
  }
  User user = userService.getUser(username);
  // no UnknownUserException beccause this results in trouble with "WithMockUser" tests
  return user != null && user.isSuperuser();
}
 
Example #29
Source File: ValidateUtil.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public Set<String> getAllIdentifiersInPrj(String project, String type) throws IOException {
    List<Sid> allSids = getAllSids(project);
    if (type.equalsIgnoreCase(MetadataConstants.TYPE_USER)) {
        return getUsersInPrj(allSids);
    } else {
        return getAuthoritiesInPrj(allSids);
    }
}
 
Example #30
Source File: NextServerAclService.java    From nextreports-server with Apache License 2.0 5 votes vote down vote up
@Override
public Acl readAclById(ObjectIdentity object, List<Sid> sids) throws NotFoundException {
	List<ObjectIdentity> objects = new ArrayList<ObjectIdentity>();
	objects.add(object);
	Map<ObjectIdentity, Acl> map = readAclsById(objects, sids);
	if (map.size() == 0) {
		throw new NotFoundException("Acl not find for " + object);
	}

	return map.get(object);
}