[Major] refactored the use of the Privilege class, now Roles have Privileges in a composition relationship

This commit is contained in:
eitch 2011-07-30 13:20:08 +00:00
parent 65c17ab4a3
commit 8b9c8ea1e5
13 changed files with 556 additions and 759 deletions

View File

@ -1,31 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<UsersAndRoles>
<Privileges>
<Privilege name="NoRestriction" policy="DefaultPrivilege">
<AllAllowed>true</AllAllowed>
<Deny></Deny>
<Allow></Allow>
</Privilege>
<Privilege name="Service" policy="DefaultPrivilege">
<AllAllowed>false</AllAllowed>
<Deny></Deny>
<Allow>ch.eitchnet.privilege.test.TestRestrictable</Allow>
</Privilege>
</Privileges>
<Users>
<User userId="1" username="eitch" password="c775e7b757ede630cd0aa1113bd102661ab38829ca52a6422ab782862f268646">
<Firstname>Robert</Firstname>
<Surname>von Burg</Surname>
<User userId="1" username="admin" password="8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918">
<Firstname>Featherlite</Firstname>
<Surname>Administrator</Surname>
<State>ENABLED</State>
<Locale>en_GB</Locale>
<Roles>
<Role>PrivilegeAdmin</Role>
<Role>admin</Role>
<Role>serviceExecutor</Role>
<Role>FeatherliteUser</Role>
</Roles>
</User>
@ -35,14 +20,16 @@
<Role name="PrivilegeAdmin" />
<Role name="admin">
<Privilege name="NoRestriction" />
</Role>
<Role name="user" />
<Role name="serviceExecutor">
<Privilege name="Service" />
<Role name="FeatherliteUser">
<Privilege name="com.rsp.core.base.service.Service">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="com.rsp.core.base.query.RSPQuery">
<AllAllowed>true</AllAllowed>
</Privilege>
<Privilege name="RegisterObservers">
<AllAllowed>true</AllAllowed>
</Privilege>
</Role>
</Roles>

View File

@ -19,6 +19,7 @@ import java.util.Set;
import org.apache.log4j.Logger;
import ch.eitchnet.privilege.helper.ClassHelper;
import ch.eitchnet.privilege.i18n.AccessDeniedException;
import ch.eitchnet.privilege.i18n.PrivilegeException;
import ch.eitchnet.privilege.model.Certificate;
@ -64,6 +65,11 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
*/
protected long lastSessionId;
/**
* Map of {@link PrivilegePolicy} classes
*/
private Map<String, Class<PrivilegePolicy>> policyMap;
/**
* Map keeping a reference to all active sessions with their certificates
*/
@ -84,20 +90,15 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
*/
protected boolean initialized;
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#getPrivilege(java.lang.String)
*/
@Override
public PrivilegeRep getPrivilege(String privilegeName) {
return this.persistenceHandler.getPrivilege(privilegeName).asPrivilegeRep();
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#getRole(java.lang.String)
*/
@Override
public RoleRep getRole(String roleName) {
return this.persistenceHandler.getRole(roleName).asRoleRep();
Role role = this.persistenceHandler.getRole(roleName);
if (role == null)
throw new PrivilegeException("Role " + roleName + " does not exist!");
return role.asRoleRep();
}
/**
@ -105,33 +106,45 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
*/
@Override
public UserRep getUser(String username) {
return this.persistenceHandler.getUser(username).asUserRep();
User user = this.persistenceHandler.getUser(username);
if (user == null)
throw new PrivilegeException("User " + username + " does not exist!");
return user.asUserRep();
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#getPolicy(java.lang.String)
* <p>
* This method instantiates a {@link PrivilegePolicy} object from the given policyName. The {@link PrivilegePolicy}
* is not stored in a database. The privilege name is a class name and is then used to instantiate a new
* {@link PrivilegePolicy} object
* </p>
*
* @param policyName
* the class name of the {@link PrivilegePolicy} object to return
*
* @return the {@link PrivilegePolicy} object
*
* @throws PrivilegeException
* if the {@link PrivilegePolicy} object for the given policy name could not be instantiated
*/
@Override
public PrivilegePolicy getPolicy(String policyName) {
return this.persistenceHandler.getPolicy(policyName);
}
protected PrivilegePolicy getPolicy(String policyName) {
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#addOrReplacePrivilege(ch.eitchnet.privilege.model.Certificate,
* ch.eitchnet.privilege.model.PrivilegeRep)
*/
@Override
public void addOrReplacePrivilege(Certificate certificate, PrivilegeRep privilegeRep) {
// get the policies class
Class<PrivilegePolicy> policyClazz = this.policyMap.get(policyName);
if (policyClazz == null) {
return null;
}
// validate who is doing this
validateIsPrivilegeAdmin(certificate);
// instantiate the policy
PrivilegePolicy policy;
try {
policy = ClassHelper.instantiateClass(policyClazz);
} catch (Exception e) {
throw new PrivilegeException("The class for the policy with the name " + policyName + " does not exist!"
+ policyName, e);
}
// create a new privilege
Privilege privilege = new Privilege(privilegeRep.getName(), privilegeRep.getPolicy(),
privilegeRep.isAllAllowed(), privilegeRep.getDenyList(), privilegeRep.getAllowList());
// delegate to persistence handler
this.persistenceHandler.addOrReplacePrivilege(privilege);
return policy;
}
/**
@ -144,8 +157,11 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// validate who is doing this
validateIsPrivilegeAdmin(certificate);
// create new role
Role role = new Role(roleRep.getName(), roleRep.getPrivileges());
// create new role from RoleRep
Role role = new Role(roleRep);
// validate policy if not null
validatePolicies(role);
// delegate to persistence handler
this.persistenceHandler.addOrReplaceRole(role);
@ -180,39 +196,37 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#addPrivilegeToRole(ch.eitchnet.privilege.model.Certificate,
* java.lang.String, java.lang.String)
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#addOrReplacePrivilegeOnRole(ch.eitchnet.privilege.model.Certificate,
* java.lang.String, ch.eitchnet.privilege.model.PrivilegeRep)
*/
@Override
public void addPrivilegeToRole(Certificate certificate, String roleName, String privilegeName) {
public void addOrReplacePrivilegeOnRole(Certificate certificate, String roleName, PrivilegeRep privilegeRep) {
// validate who is doing this
validateIsPrivilegeAdmin(certificate);
// validate PrivilegeRep
privilegeRep.validate();
// get role
Role role = this.persistenceHandler.getRole(roleName);
if (role == null) {
throw new PrivilegeException("Role " + roleName + " does not exist!");
}
// ignore if role already has this privilege
Set<String> currentPrivileges = role.getPrivileges();
if (currentPrivileges.contains(roleName)) {
logger.error("Role " + roleName + " already has privilege " + privilegeName);
return;
}
// validate that privilege exists
if (getPrivilege(privilegeName) == null) {
throw new PrivilegeException("Privilege " + privilegeName + " does not exist and can not be added to role "
+ roleName);
// validate that policy exists if needed
String policy = privilegeRep.getPolicy();
if (policy != null && !this.policyMap.containsKey(policy)) {
throw new PrivilegeException("Policy " + policy + " for Privilege " + privilegeRep.getName()
+ " does not exist");
}
// create new role with the additional privilege
Set<String> newPrivileges = new HashSet<String>(currentPrivileges);
newPrivileges.add(roleName);
Privilege newPrivilege = new Privilege(privilegeRep);
Map<String, Privilege> privilegeMap = new HashMap<String, Privilege>(role.getPrivilegeMap());
privilegeMap.put(newPrivilege.getName(), newPrivilege);
Role newRole = new Role(role.getName(), newPrivileges);
Role newRole = new Role(role.getName(), privilegeMap);
// delegate role replacement to persistence handler
this.persistenceHandler.addOrReplaceRole(newRole);
@ -257,26 +271,6 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
this.persistenceHandler.addOrReplaceUser(newUser);
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#removePrivilege(ch.eitchnet.privilege.model.Certificate,
* java.lang.String)
*/
@Override
public PrivilegeRep removePrivilege(Certificate certificate, String privilegeName) {
// validate who is doing this
validateIsPrivilegeAdmin(certificate);
// delegate privilege removal to persistence handler
Privilege removedPrivilege = this.persistenceHandler.removePrivilege(privilegeName);
if (removedPrivilege == null)
return null;
// return privilege rep if it was removed
return removedPrivilege.asPrivilegeRep();
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#removePrivilegeFromRole(ch.eitchnet.privilege.model.Certificate,
* java.lang.String, java.lang.String)
@ -294,15 +288,17 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
}
// ignore if role does not have privilege
Set<String> currentPrivileges = role.getPrivileges();
if (!currentPrivileges.contains(privilegeName)) {
logger.error("Role " + roleName + " doest not have privilege " + privilegeName);
return;
if (!role.hasPrivilege(privilegeName))
throw new PrivilegeException("Role " + roleName + " does not have Privilege " + privilegeName);
// create new set of privileges with out the to remove privilege
Map<String, Privilege> newPrivileges = new HashMap<String, Privilege>(role.getPrivilegeMap().size() - 1);
for (Privilege privilege : role.getPrivilegeMap().values()) {
if (!privilege.getName().equals(privilegeName))
newPrivileges.put(privilege.getName(), privilege);
}
// create new role
Set<String> newPrivileges = new HashSet<String>(currentPrivileges);
newPrivileges.remove(privilegeName);
Role newRole = new Role(role.getName(), newPrivileges);
// delegate user replacement to persistence handler
@ -384,115 +380,6 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#setPrivilegeAllAllowed(ch.eitchnet.privilege.model.Certificate,
* java.lang.String, boolean)
*/
@Override
public void setPrivilegeAllAllowed(Certificate certificate, String privilegeName, boolean allAllowed) {
// validate who is doing this
validateIsPrivilegeAdmin(certificate);
// get Privilege
Privilege privilege = this.persistenceHandler.getPrivilege(privilegeName);
if (privilege == null) {
throw new PrivilegeException("Privilege " + privilegeName + " does not exist!");
}
// ignore if privilege is already set to argument
if (privilege.isAllAllowed() == allAllowed) {
logger.error("Privilege " + privilegeName + " is already set to "
+ (allAllowed ? "all allowed" : "not all allowed"));
return;
}
// create new privilege
Privilege newPrivilege = new Privilege(privilege.getName(), privilege.getPolicy(), allAllowed,
privilege.getDenyList(), privilege.getAllowList());
// delegate privilege replacement to persistence handler
this.persistenceHandler.addOrReplacePrivilege(newPrivilege);
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#setPrivilegeAllowList(ch.eitchnet.privilege.model.Certificate,
* java.lang.String, java.util.Set)
*/
@Override
public void setPrivilegeAllowList(Certificate certificate, String privilegeName, Set<String> allowList) {
// validate who is doing this
validateIsPrivilegeAdmin(certificate);
// get Privilege
Privilege privilege = this.persistenceHandler.getPrivilege(privilegeName);
if (privilege == null) {
throw new PrivilegeException("Privilege " + privilegeName + " does not exist!");
}
// create new privilege
Privilege newPrivilege = new Privilege(privilege.getName(), privilege.getPolicy(), privilege.isAllAllowed(),
privilege.getDenyList(), allowList);
// delegate privilege replacement to persistence handler
this.persistenceHandler.addOrReplacePrivilege(newPrivilege);
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#setPrivilegeDenyList(ch.eitchnet.privilege.model.Certificate,
* java.lang.String, java.util.Set)
*/
@Override
public void setPrivilegeDenyList(Certificate certificate, String privilegeName, Set<String> denyList) {
// validate who is doing this
validateIsPrivilegeAdmin(certificate);
// get Privilege
Privilege privilege = this.persistenceHandler.getPrivilege(privilegeName);
if (privilege == null) {
throw new PrivilegeException("Privilege " + privilegeName + " does not exist!");
}
// create new privilege
Privilege newPrivilege = new Privilege(privilege.getName(), privilege.getPolicy(), privilege.isAllAllowed(),
denyList, privilege.getAllowList());
// delegate privilege replacement to persistence handler
this.persistenceHandler.addOrReplacePrivilege(newPrivilege);
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#setPrivilegePolicy(ch.eitchnet.privilege.model.Certificate,
* java.lang.String, java.lang.String)
*/
@Override
public void setPrivilegePolicy(Certificate certificate, String privilegeName, String policyName) {
// validate who is doing this
validateIsPrivilegeAdmin(certificate);
// get Privilege
Privilege privilege = this.persistenceHandler.getPrivilege(privilegeName);
if (privilege == null) {
throw new PrivilegeException("Privilege " + privilegeName + " does not exist!");
}
// validate that the policy exists
PrivilegePolicy policy = this.persistenceHandler.getPolicy(policyName);
if (policy == null) {
throw new PrivilegeException("No privilege policy exists for the name " + policyName);
}
// create new privilege
Privilege newPrivilege = new Privilege(privilege.getName(), policyName, privilege.isAllAllowed(),
privilege.getDenyList(), privilege.getAllowList());
// delegate privilege replacement to persistence handler
this.persistenceHandler.addOrReplacePrivilege(newPrivilege);
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#setUserLocale(ch.eitchnet.privilege.model.Certificate,
* java.lang.String, java.util.Locale)
@ -706,9 +593,8 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
// first validate certificate
if (!isCertificateValid(certificate)) {
logger.info("Certificate is not valid, so action is not allowed: " + certificate + " for restrictable: "
+ restrictable);
return false;
throw new PrivilegeException("Certificate is not valid, so action is not allowed: " + certificate
+ " for restrictable: " + restrictable);
}
// restrictable must not be null
@ -797,13 +683,13 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
}
// get the privilege for this restrictable
Privilege privilege = this.persistenceHandler.getPrivilege(privilegeName);
if (privilege == null) {
throw new PrivilegeException("No Privilege exists with the name " + privilegeName + " for Restrictable "
+ restrictable.getClass().getName());
}
Privilege privilege = role.getPrivilegeMap().get(privilegeName);
// get the policy configured for this privilege
// check if all is allowed
if (privilege.isAllAllowed())
return true;
// otherwise delegate checking to the policy configured for this privilege
PrivilegePolicy policy = this.getPolicy(privilege.getPolicy());
if (policy == null) {
throw new PrivilegeException("PrivilegePolicy " + privilege.getPolicy() + " does not exist for Privilege "
@ -906,24 +792,58 @@ public class DefaultPrivilegeHandler implements PrivilegeHandler {
}
/**
* @see ch.eitchnet.privilege.handler.PrivilegeHandler#initialize(java.util.Map,
* ch.eitchnet.privilege.handler.EncryptionHandler, ch.eitchnet.privilege.handler.PersistenceHandler)
* Initializes the concrete {@link EncryptionHandler}. The passed parameter map contains any configuration this
* {@link PrivilegeHandler} might need. This method may only be called once and this must be enforced by the
* concrete implementation
*
* @param parameterMap
* a map containing configuration properties
* @param encryptionHandler
* the {@link EncryptionHandler} instance for this {@link PrivilegeHandler}
* @param persistenceHandler
* the {@link PersistenceHandler} instance for this {@link PrivilegeHandler}
* @param policyMap
* map of {@link PrivilegePolicy} classes
*
* @throws PrivilegeException
* if the this method is called multiple times or an initialization exception occurs
*/
@Override
public void initialize(Map<String, String> parameterMap, EncryptionHandler encryptionHandler,
PersistenceHandler persistenceHandler) {
PersistenceHandler persistenceHandler, Map<String, Class<PrivilegePolicy>> policyMap) {
if (this.initialized)
throw new PrivilegeException("Already initialized!");
this.policyMap = policyMap;
this.encryptionHandler = encryptionHandler;
this.persistenceHandler = persistenceHandler;
// validate policies on privileges of Roles
for (Role role : persistenceHandler.getAllRoles()) {
validatePolicies(role);
}
this.lastSessionId = 0l;
this.sessionMap = Collections.synchronizedMap(new HashMap<String, CertificateSessionPair>());
this.initialized = true;
}
/**
* Validates that the policies which are not null on the privileges of the role exist
*
* @param role
* the role for which the policies are to be checked
*/
private void validatePolicies(Role role) {
for (Privilege privilege : role.getPrivilegeMap().values()) {
String policy = privilege.getPolicy();
if (policy != null && !this.policyMap.containsKey(policy)) {
throw new PrivilegeException("Policy " + policy + " for Privilege " + privilege.getName()
+ " does not exist on role " + role);
}
}
}
/**
* @return a new session id
*/

View File

@ -10,9 +10,9 @@
package ch.eitchnet.privilege.handler;
import java.util.List;
import java.util.Map;
import ch.eitchnet.privilege.i18n.PrivilegeException;
import ch.eitchnet.privilege.model.Restrictable;
import ch.eitchnet.privilege.model.internal.Privilege;
import ch.eitchnet.privilege.model.internal.Role;
@ -36,6 +36,20 @@ import ch.eitchnet.privilege.policy.PrivilegePolicy;
*/
public interface PersistenceHandler {
/**
* Returns all currently known {@link User}s
*
* @return all currently known {@link User}s
*/
public List<User> getAllUsers();
/**
* Returns all currently known {@link Role}s
*
* @return all currently known {@link Role}s
*/
public List<Role> getAllRoles();
/**
* Returns a {@link User} object from the underlying database
*
@ -56,33 +70,6 @@ public interface PersistenceHandler {
*/
public Role getRole(String roleName);
/**
* Returns a {@link Privilege} object from the underlying database
*
* @param privilegeName
* the name/id of the {@link Privilege} object to return
*
* @return the {@link Privilege} object, or null if it was not found
*/
public Privilege getPrivilege(String privilegeName);
/**
* <p>
* This method instantiates a {@link PrivilegePolicy} object from the given policyName. The {@link PrivilegePolicy}
* is not stored in a database. The privilege name is a class name and is then used to instantiate a new
* {@link PrivilegePolicy} object
* </p>
*
* @param policyName
* the class name of the {@link PrivilegePolicy} object to return
*
* @return the {@link PrivilegePolicy} object
*
* @throws PrivilegeException
* if the {@link PrivilegePolicy} object for the given policy name could not be instantiated
*/
public PrivilegePolicy getPolicy(String policyName) throws PrivilegeException;
/**
* Removes a {@link User} with the given name and returns the removed object if it existed
*
@ -103,16 +90,6 @@ public interface PersistenceHandler {
*/
public Role removeRole(String roleName);
/**
* Removes a {@link Privilege} with the given name and returns the removed object if it existed
*
* @param privilegeName
* the name of the {@link Privilege} to remove
*
* @return the {@link Privilege} removed, or null if it did not exist
*/
public Privilege removePrivilege(String privilegeName);
/**
* Adds a {@link User} object to the underlying database. If the {@link User} already exists, it is replaced
*
@ -129,15 +106,6 @@ public interface PersistenceHandler {
*/
public void addOrReplaceRole(Role role);
/**
* Adds a {@link Privilege} object to the underlying database. If the {@link Privilege} already exists, it is
* replaced
*
* @param privilege
* the {@link Privilege} object to add
*/
public void addOrReplacePrivilege(Privilege privilege);
/**
* Informs this {@link PersistenceHandler} to persist any changes which need to be saved
*
@ -145,14 +113,19 @@ public interface PersistenceHandler {
*/
public boolean persist();
/**
* Informs this {@link PersistenceHandler} to reload the data from the backend
*
* @return true if the reload was successful, false if something went wrong
*/
public boolean reload();
/**
* Initialize the concrete {@link PersistenceHandler}. The passed parameter map contains any configuration the
* concrete {@link PersistenceHandler} might need
*
* @param parameterMap
* a map containing configuration properties
* @param policyMap
* map of policy key/policy class pairs
*/
public void initialize(Map<String, String> parameterMap, Map<String, Class<PrivilegePolicy>> policyMap);
public void initialize(Map<String, String> parameterMap);
}

View File

@ -10,10 +10,7 @@
package ch.eitchnet.privilege.handler;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import ch.eitchnet.privilege.i18n.AccessDeniedException;
import ch.eitchnet.privilege.i18n.PrivilegeException;
@ -27,7 +24,6 @@ import ch.eitchnet.privilege.model.internal.Privilege;
import ch.eitchnet.privilege.model.internal.Role;
import ch.eitchnet.privilege.model.internal.Session;
import ch.eitchnet.privilege.model.internal.User;
import ch.eitchnet.privilege.policy.PrivilegePolicy;
/**
* The {@link PrivilegeHandler} is the centrally exposed API for accessing the privilege library. It exposes all needed
@ -64,26 +60,6 @@ public interface PrivilegeHandler {
*/
public RoleRep getRole(String roleName);
/**
* Returns a {@link PrivilegeRep} for the given privilegeName
*
* @param privilegeName
* the name of the {@link PrivilegeRep} to return
*
* @return the {@link PrivilegeRep} for the given privilegeName, or null if it was not found
*/
public PrivilegeRep getPrivilege(String privilegeName);
/**
* Returns a {@link PrivilegePolicy} for the given policyName
*
* @param policyName
* the name of the {@link PrivilegePolicy} to return
*
* @return the {@link PrivilegePolicy} for the given policyName, or null if it was not found
*/
public PrivilegePolicy getPolicy(String policyName);
/**
* Removes the user with the given username
*
@ -156,24 +132,6 @@ public interface PrivilegeHandler {
public void removePrivilegeFromRole(Certificate certificate, String roleName, String privilegeName)
throws AccessDeniedException, PrivilegeException;
/**
* Removes the privilege with the given privilegeName
*
* @param certificate
* the {@link Certificate} of the user which has the privilege to perform this action
* @param privilegeName
* the privilegeName of the privilege to remove
*
* @return the {@link PrivilegeRep} of the privilege removed, or null if the privilege did not exist
*
* @throws AccessDeniedException
* if the user for this certificate may not perform the action
* @throws PrivilegeException
* if there is anything wrong with this certificate
*/
public PrivilegeRep removePrivilege(Certificate certificate, String privilegeName) throws AccessDeniedException,
PrivilegeException;
/**
* <p>
* Adds a new user, or replaces the user with the information from this {@link UserRep} if the user already exists
@ -217,23 +175,6 @@ public interface PrivilegeHandler {
public void addOrReplaceRole(Certificate certificate, RoleRep roleRep) throws AccessDeniedException,
PrivilegeException;
/**
* Adds a new privilege, or replaces the privilege with the information from this {@link PrivilegeRep} if the
* privilege already exists
*
* @param certificate
* the {@link Certificate} of the user which has the privilege to perform this action
* @param privilegeRep
* the {@link PrivilegeRep} containing the information to create the new {@link Privilege}
*
* @throws AccessDeniedException
* if the user for this certificate may not perform the action
* @throws PrivilegeException
* if there is anything wrong with this certificate
*/
public void addOrReplacePrivilege(Certificate certificate, PrivilegeRep privilegeRep) throws AccessDeniedException,
PrivilegeException;
/**
* Adds the role with the given roleName to the {@link User} with the given username
*
@ -253,21 +194,21 @@ public interface PrivilegeHandler {
PrivilegeException;
/**
* Adds the privilege with the given privilegeName to the {@link Role} with the given roleName
* Adds the {@link PrivilegeRep} to the {@link Role} with the given roleName
*
* @param certificate
* the {@link Certificate} of the user which has the privilege to perform this action
* @param roleName
* the roleName of the {@link Role} to which the privilege should be added
* @param privilegeName
* the privilegeName of the {@link Privilege} which should be added to the {@link Role}
* @param privilegeRep
* the representation of the {@link Privilege} which should be added to the {@link Role}
*
* @throws AccessDeniedException
* if the user for this certificate may not perform the action
* @throws PrivilegeException
* if there is anything wrong with this certificate
*/
public void addPrivilegeToRole(Certificate certificate, String roleName, String privilegeName)
public void addOrReplacePrivilegeOnRole(Certificate certificate, String roleName, PrivilegeRep privilegeRep)
throws AccessDeniedException, PrivilegeException;
/**
@ -349,82 +290,6 @@ public interface PrivilegeHandler {
public void setUserLocale(Certificate certificate, String username, Locale locale) throws AccessDeniedException,
PrivilegeException;
/**
* Sets the class name of the {@link PrivilegePolicy} object for the {@link Privilege} registered for the given
* privilegeName
*
* @param certificate
* the {@link Certificate} of the user which has the privilege to perform this action
* @param privilegeName
* the name of the {@link Privilege} for which the policy is to be changed
* @param policyName
* class name of the {@link PrivilegePolicy} to be registered for this {@link Privilege}
*
* @throws AccessDeniedException
* if the user for this certificate may not perform the action
* @throws PrivilegeException
* if there is anything wrong with this certificate or if the class name of the policy is invalid
*/
public void setPrivilegePolicy(Certificate certificate, String privilegeName, String policyName)
throws AccessDeniedException, PrivilegeException;
/**
* Sets the special flag on the given {@link Privilege} defined by the privilegeName argument so that all is allowed
* and thus the allow and deny list of the privilege are ignored
*
* @param certificate
* the {@link Certificate} of the user which has the privilege to perform this action
* @param privilegeName
* the name of the {@link Privilege} for which the allAllowed value is to be changed
* @param allAllowed
* the boolean defining if all privileges are granted for the value true, or not for the value false
*
* @throws AccessDeniedException
* if the user for this certificate may not perform the action
* @throws PrivilegeException
* if there is anything wrong with this certificate
*/
public void setPrivilegeAllAllowed(Certificate certificate, String privilegeName, boolean allAllowed)
throws AccessDeniedException, PrivilegeException;
/**
* Sets the {@link List} of strings which represent values which denies finer grained privilege rights for the
* {@link Privilege} defined by the privilegeName argument
*
* @param certificate
* the {@link Certificate} of the user which has the privilege to perform this action
* @param privilegeName
* the name of the {@link Privilege} for which the deny list is to be changed
* @param denyList
* the {@link List} of strings which represent values which denies finer grained privilege rights
*
* @throws AccessDeniedException
* if the user for this certificate may not perform the action
* @throws PrivilegeException
* if there is anything wrong with this certificate
*/
public void setPrivilegeDenyList(Certificate certificate, String privilegeName, Set<String> denyList)
throws AccessDeniedException, PrivilegeException;
/**
* Sets the {@link List} of strings which represent values which grants finer grained privilege rights for the
* {@link Privilege} defined by the privilegeName argument
*
* @param certificate
* the {@link Certificate} of the user which has the privilege to perform this action
* @param privilegeName
* the name of the {@link Privilege} for which the allow list is to be changed
* @param allowList
* the {@link List} of strings which represent values which grants finer grained privilege rights
*
* @throws AccessDeniedException
* if the user for this certificate may not perform the action
* @throws PrivilegeException
* if there is anything wrong with this certificate
*/
public void setPrivilegeAllowList(Certificate certificate, String privilegeName, Set<String> allowList)
throws AccessDeniedException, PrivilegeException;
/**
* Authenticates a user by validating that a {@link User} for the given username and password exist and then returns
* a {@link Certificate} with which this user may then perform actions
@ -548,22 +413,4 @@ public interface PrivilegeHandler {
* if the users of the given certificate does not have the privilege to perform this action
*/
public boolean persist(Certificate certificate) throws AccessDeniedException;
/**
* Initializes the concrete {@link EncryptionHandler}. The passed parameter map contains any configuration this
* {@link PrivilegeHandler} might need. This method may only be called once and this must be enforced by the
* concrete implementation
*
* @param parameterMap
* a map containing configuration properties
* @param encryptionHandler
* the {@link EncryptionHandler} instance for this {@link PrivilegeHandler}
* @param persistenceHandler
* the {@link PersistenceHandler} instance for this {@link PrivilegeHandler}
*
* @throws PrivilegeException
* if the this method is called multiple times or an initialization exception occurs
*/
public void initialize(Map<String, String> parameterMap, EncryptionHandler encryptionHandler,
PersistenceHandler persistenceHandler) throws PrivilegeException;
}

View File

@ -15,6 +15,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@ -24,7 +25,6 @@ import org.apache.log4j.Logger;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import ch.eitchnet.privilege.helper.ClassHelper;
import ch.eitchnet.privilege.helper.XmlConstants;
import ch.eitchnet.privilege.helper.XmlHelper;
import ch.eitchnet.privilege.i18n.PrivilegeException;
@ -32,11 +32,10 @@ import ch.eitchnet.privilege.model.UserState;
import ch.eitchnet.privilege.model.internal.Privilege;
import ch.eitchnet.privilege.model.internal.Role;
import ch.eitchnet.privilege.model.internal.User;
import ch.eitchnet.privilege.policy.PrivilegePolicy;
/**
* {@link PersistenceHandler} implementation which reads the configuration from XML files. These configuration is passed
* in {@link #initialize(Map, Map)}
* in {@link #initialize(Map)}
*
* @author rvonburg
*/
@ -46,44 +45,59 @@ public class XmlPersistenceHandler implements PersistenceHandler {
private Map<String, User> userMap;
private Map<String, Role> roleMap;
private Map<String, Privilege> privilegeMap;
private Map<String, Class<PrivilegePolicy>> policyMap;
private long modelsFileDate;
private boolean userMapDirty;
private boolean roleMapDirty;
private boolean privilegeMapDirty;
private Map<String, String> parameterMap;
private String basePath;
private String modelPath;
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#addOrReplacePrivilege(ch.eitchnet.privilege.model.internal.Privilege)
* @see ch.eitchnet.privilege.handler.PersistenceHandler#getAllUsers()
*/
@Override
public void addOrReplacePrivilege(Privilege privilege) {
this.privilegeMap.put(privilege.getName(), privilege);
this.privilegeMapDirty = true;
public List<User> getAllUsers() {
synchronized (this.userMap) {
return new LinkedList<User>(this.userMap.values());
}
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#removePrivilege(java.lang.String)
* @see ch.eitchnet.privilege.handler.PersistenceHandler#getAllRoles()
*/
@Override
public Privilege removePrivilege(String privilegeName) {
Privilege privilege = this.privilegeMap.remove(privilegeName);
this.privilegeMapDirty = privilege != null;
return privilege;
public List<Role> getAllRoles() {
synchronized (this.roleMap) {
return new LinkedList<Role>(this.roleMap.values());
}
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#addOrReplaceRole(ch.eitchnet.privilege.model.internal.Role)
* @see ch.eitchnet.privilege.handler.PersistenceHandler#getUser(java.lang.String)
*/
@Override
public void addOrReplaceRole(Role role) {
this.roleMap.put(role.getName(), role);
this.roleMapDirty = true;
public User getUser(String username) {
return this.userMap.get(username);
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#getRole(java.lang.String)
*/
@Override
public Role getRole(String roleName) {
return this.roleMap.get(roleName);
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#removeUser(java.lang.String)
*/
@Override
public User removeUser(String username) {
User user = this.userMap.remove(username);
this.userMapDirty = user != null;
return user;
}
/**
@ -106,61 +120,12 @@ public class XmlPersistenceHandler implements PersistenceHandler {
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#removeUser(java.lang.String)
* @see ch.eitchnet.privilege.handler.PersistenceHandler#addOrReplaceRole(ch.eitchnet.privilege.model.internal.Role)
*/
@Override
public User removeUser(String username) {
User user = this.userMap.remove(username);
this.userMapDirty = user != null;
return user;
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#getPrivilege(java.lang.String)
*/
@Override
public Privilege getPrivilege(String privilegeName) {
return this.privilegeMap.get(privilegeName);
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#getRole(java.lang.String)
*/
@Override
public Role getRole(String roleName) {
return this.roleMap.get(roleName);
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#getUser(java.lang.String)
*/
@Override
public User getUser(String username) {
return this.userMap.get(username);
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#getPolicy(java.lang.String)
*/
@Override
public PrivilegePolicy getPolicy(String policyName) {
// get the policies class
Class<PrivilegePolicy> policyClazz = this.policyMap.get(policyName);
if (policyClazz == null) {
return null;
}
// instantiate the policy
PrivilegePolicy policy;
try {
policy = ClassHelper.instantiateClass(policyClazz);
} catch (Exception e) {
throw new PrivilegeException("The class for the policy with the name " + policyName + " does not exist!"
+ policyName, e);
}
return policy;
public void addOrReplaceRole(Role role) {
this.roleMap.put(role.getName(), role);
this.roleMapDirty = true;
}
/**
@ -176,9 +141,9 @@ public class XmlPersistenceHandler implements PersistenceHandler {
+ XmlConstants.XML_PARAM_MODEL_FILE + " is invalid");
}
// get model file
File modelFile = new File(this.basePath + "/" + modelFileName);
File modelFile = new File(this.modelPath);
boolean modelFileUnchanged = modelFile.exists() && modelFile.lastModified() == this.modelsFileDate;
if (!(modelFileUnchanged && this.privilegeMapDirty && this.roleMapDirty && this.userMapDirty)) {
if (!(modelFileUnchanged && this.roleMapDirty && this.userMapDirty)) {
logger.warn("Not persisting as current file is unchanged and model data is not dirty");
return false;
}
@ -206,20 +171,10 @@ public class XmlPersistenceHandler implements PersistenceHandler {
}
rootElement.add(rolesElement);
// PRIVILEGES
// build XML DOM of privileges
List<Element> privileges = toDomPrivileges();
Element privilegesElement = docFactory.createElement(XmlConstants.XML_PRIVILEGES);
for (Element privilegeElement : privileges) {
privilegesElement.add(privilegeElement);
}
rootElement.add(privilegesElement);
// reset dirty states and return if something was dirty, false otherwise
if (this.userMapDirty || this.roleMapDirty || this.privilegeMapDirty) {
if (this.userMapDirty || this.roleMapDirty) {
this.userMapDirty = false;
this.roleMapDirty = false;
this.privilegeMapDirty = false;
return true;
@ -227,45 +182,27 @@ public class XmlPersistenceHandler implements PersistenceHandler {
this.userMapDirty = false;
this.roleMapDirty = false;
this.privilegeMapDirty = false;
return false;
}
/**
* @see ch.eitchnet.privilege.handler.EncryptionHandler#initialize(java.util.Map)
* @see ch.eitchnet.privilege.handler.PersistenceHandler#reload()
*/
@Override
public void initialize(Map<String, String> parameterMap, Map<String, Class<PrivilegePolicy>> policyMap) {
this.roleMap = Collections.synchronizedMap(new HashMap<String, Role>());
this.userMap = Collections.synchronizedMap(new HashMap<String, User>());
this.privilegeMap = Collections.synchronizedMap(new HashMap<String, Privilege>());
this.policyMap = policyMap;
// get and validate base bath
this.basePath = parameterMap.get(XmlConstants.XML_PARAM_BASE_PATH);
File basePathF = new File(this.basePath);
if (!basePathF.exists() && !basePathF.isDirectory()) {
throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter "
+ XmlConstants.XML_PARAM_BASE_PATH + " is invalid");
}
// get model file name
String modelFileName = parameterMap.get(XmlConstants.XML_PARAM_MODEL_FILE);
if (modelFileName == null || modelFileName.isEmpty()) {
throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter "
+ XmlConstants.XML_PARAM_MODEL_FILE + " is invalid");
}
public boolean reload() {
// validate file exists
File modelsFile = new File(this.basePath + "/" + modelFileName);
File modelsFile = new File(this.modelPath);
if (!modelsFile.exists()) {
throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter "
+ XmlConstants.XML_PARAM_MODEL_FILE + " is invalid as models file does not exist at path "
+ modelsFile.getAbsolutePath());
}
this.roleMap = Collections.synchronizedMap(new HashMap<String, Role>());
this.userMap = Collections.synchronizedMap(new HashMap<String, User>());
// parse models xml file to XML document
Element modelsRootElement = XmlHelper.parseDocument(modelsFile).getRootElement();
this.modelsFileDate = modelsFile.lastModified();
@ -282,19 +219,11 @@ public class XmlPersistenceHandler implements PersistenceHandler {
// read users
readUsers(usersElement);
// PRIVILEGES
// get privileges element
Element privilegesElement = modelsRootElement.element(XmlConstants.XML_PRIVILEGES);
// read privileges
readPrivileges(privilegesElement);
this.userMapDirty = false;
this.roleMapDirty = false;
this.privilegeMapDirty = false;
logger.info("Read " + this.userMap.size() + " Users");
logger.info("Read " + this.roleMap.size() + " Roles");
logger.info("Read " + this.privilegeMap.size() + " Privileges");
// validate we have a user with PrivilegeAdmin access
boolean privilegeAdminExists = false;
@ -310,6 +239,36 @@ public class XmlPersistenceHandler implements PersistenceHandler {
logger.warn("No User with role '" + PrivilegeHandler.PRIVILEGE_ADMIN_ROLE
+ "' exists. Privilege modifications will not be possible!");
}
return true;
}
/**
* @see ch.eitchnet.privilege.handler.PersistenceHandler#initialize(java.util.Map)
*/
@Override
public void initialize(Map<String, String> parameterMap) {
// get and validate base bath
String basePath = parameterMap.get(XmlConstants.XML_PARAM_BASE_PATH);
File basePathF = new File(basePath);
if (!basePathF.exists() && !basePathF.isDirectory()) {
throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter "
+ XmlConstants.XML_PARAM_BASE_PATH + " is invalid");
}
// get model file name
String modelFileName = parameterMap.get(XmlConstants.XML_PARAM_MODEL_FILE);
if (modelFileName == null || modelFileName.isEmpty()) {
throw new PrivilegeException("[" + PersistenceHandler.class.getName() + "] Defined parameter "
+ XmlConstants.XML_PARAM_MODEL_FILE + " is invalid");
}
// save path to model
this.modelPath = basePath + "/" + modelFileName;
if (reload())
logger.info("Privilege Data loaded.");
}
/**
@ -369,27 +328,23 @@ public class XmlPersistenceHandler implements PersistenceHandler {
String roleName = roleElement.attributeValue(XmlConstants.XML_ATTR_NAME);
@SuppressWarnings("unchecked")
List<Element> privilegeElements = roleElement.elements(XmlConstants.XML_PRIVILEGE);
Set<String> privileges = new HashSet<String>();
for (Element privilegeElement : privilegeElements) {
Map<String, Privilege> privilegeMap = readPrivileges(roleElement);
String privilegeName = privilegeElement.attributeValue(XmlConstants.XML_ATTR_NAME);
privileges.add(privilegeName);
}
Role role = new Role(roleName, privileges);
Role role = new Role(roleName, privilegeMap);
this.roleMap.put(roleName, role);
}
}
/**
* @param rolesRootElement
* @param roleParentElement
* @return
*/
private void readPrivileges(Element privilegesRootElement) {
private Map<String, Privilege> readPrivileges(Element roleParentElement) {
Map<String, Privilege> privilegeMap = new HashMap<String, Privilege>();
@SuppressWarnings("unchecked")
List<Element> privilegeElements = privilegesRootElement.elements(XmlConstants.XML_PRIVILEGE);
List<Element> privilegeElements = roleParentElement.elements(XmlConstants.XML_PRIVILEGE);
for (Element privilegeElement : privilegeElements) {
String privilegeName = privilegeElement.attributeValue(XmlConstants.XML_ATTR_NAME);
@ -403,11 +358,8 @@ public class XmlPersistenceHandler implements PersistenceHandler {
Set<String> denyList = new HashSet<String>(denyElements.size());
for (Element denyElement : denyElements) {
String denyValue = denyElement.getTextTrim();
if (denyValue.isEmpty()) {
logger.error("Privilege " + privilegeName + " has an empty deny value!");
} else {
if (!denyValue.isEmpty())
denyList.add(denyValue);
}
}
@SuppressWarnings("unchecked")
@ -415,89 +367,15 @@ public class XmlPersistenceHandler implements PersistenceHandler {
Set<String> allowList = new HashSet<String>(allowElements.size());
for (Element allowElement : allowElements) {
String allowValue = allowElement.getTextTrim();
if (allowValue.isEmpty()) {
logger.error("Privilege " + privilegeName + " has an empty allow value!");
} else {
if (!allowValue.isEmpty())
allowList.add(allowValue);
}
}
Privilege privilege = new Privilege(privilegeName, privilegePolicy, allAllowed, denyList, allowList);
this.privilegeMap.put(privilegeName, privilege);
}
}
private List<Element> toDomPrivileges() {
List<Element> privilegesAsElements = new ArrayList<Element>(this.privilegeMap.size());
DocumentFactory documentFactory = DocumentFactory.getInstance();
synchronized (this.privilegeMap) {
for (String privilegeName : this.privilegeMap.keySet()) {
// get the privilege object
Privilege privilege = this.privilegeMap.get(privilegeName);
// create the privilege element
Element privilegeElement = documentFactory.createElement(XmlConstants.XML_PRIVILEGE);
privilegeElement.addAttribute(XmlConstants.XML_ATTR_NAME, privilege.getName());
privilegeElement.addAttribute(XmlConstants.XML_ATTR_POLICY, privilege.getPolicy());
// add the all allowed element
Element allAllowedElement = documentFactory.createElement(XmlConstants.XML_ALL_ALLOWED);
allAllowedElement.setText(Boolean.toString(privilege.isAllAllowed()));
privilegeElement.add(allAllowedElement);
// add all the deny values
for (String denyValue : privilege.getDenyList()) {
Element denyValueElement = documentFactory.createElement(XmlConstants.XML_DENY);
denyValueElement.setText(denyValue);
privilegeElement.add(denyValueElement);
}
// add all the allow values
for (String allowValue : privilege.getAllowList()) {
Element allowValueElement = documentFactory.createElement(XmlConstants.XML_ALLOW);
allowValueElement.setText(allowValue);
privilegeElement.add(allowValueElement);
}
// add element to return list
privilegesAsElements.add(privilegeElement);
}
privilegeMap.put(privilegeName, privilege);
}
return privilegesAsElements;
}
private List<Element> toDomRoles() {
List<Element> rolesAsElements = new ArrayList<Element>(this.roleMap.size());
DocumentFactory documentFactory = DocumentFactory.getInstance();
synchronized (this.roleMap) {
for (String roleName : this.roleMap.keySet()) {
// get the role object
Role role = this.roleMap.get(roleName);
// create the role element
Element roleElement = documentFactory.createElement(XmlConstants.XML_ROLE);
roleElement.addAttribute(XmlConstants.XML_ATTR_NAME, role.getName());
// add all the privileges
for (String privilegeName : role.getPrivileges()) {
Element privilegeElement = documentFactory.createElement(XmlConstants.XML_PRIVILEGE);
privilegeElement.addAttribute(XmlConstants.XML_ATTR_NAME, privilegeName);
roleElement.add(privilegeElement);
}
// add element to return list
rolesAsElements.add(roleElement);
}
}
return rolesAsElements;
return privilegeMap;
}
private List<Element> toDomUsers() {
@ -505,6 +383,7 @@ public class XmlPersistenceHandler implements PersistenceHandler {
List<Element> usersAsElements = new ArrayList<Element>(this.userMap.size());
DocumentFactory documentFactory = DocumentFactory.getInstance();
synchronized (this.userMap) {
for (String userName : this.userMap.keySet()) {
@ -553,4 +432,66 @@ public class XmlPersistenceHandler implements PersistenceHandler {
return usersAsElements;
}
private List<Element> toDomRoles() {
List<Element> rolesAsElements = new ArrayList<Element>(this.roleMap.size());
DocumentFactory documentFactory = DocumentFactory.getInstance();
synchronized (this.roleMap) {
for (String roleName : this.roleMap.keySet()) {
// get the role object
Role role = this.roleMap.get(roleName);
// create the role element
Element roleElement = documentFactory.createElement(XmlConstants.XML_ROLE);
roleElement.addAttribute(XmlConstants.XML_ATTR_NAME, role.getName());
// add all the privileges
toDomPrivileges(roleElement, role.getPrivilegeMap());
// add element to return list
rolesAsElements.add(roleElement);
}
}
return rolesAsElements;
}
private void toDomPrivileges(Element roleParentElement, Map<String, Privilege> privilegeMap) {
DocumentFactory documentFactory = DocumentFactory.getInstance();
for (Privilege privilege : privilegeMap.values()) {
// create the privilege element
Element privilegeElement = documentFactory.createElement(XmlConstants.XML_PRIVILEGE);
privilegeElement.addAttribute(XmlConstants.XML_ATTR_NAME, privilege.getName());
privilegeElement.addAttribute(XmlConstants.XML_ATTR_POLICY, privilege.getPolicy());
// add the all allowed element
Element allAllowedElement = documentFactory.createElement(XmlConstants.XML_ALL_ALLOWED);
allAllowedElement.setText(Boolean.toString(privilege.isAllAllowed()));
privilegeElement.add(allAllowedElement);
// add all the deny values
for (String denyValue : privilege.getDenyList()) {
Element denyValueElement = documentFactory.createElement(XmlConstants.XML_DENY);
denyValueElement.setText(denyValue);
privilegeElement.add(denyValueElement);
}
// add all the allow values
for (String allowValue : privilege.getAllowList()) {
Element allowValueElement = documentFactory.createElement(XmlConstants.XML_ALLOW);
allowValueElement.setText(allowValue);
privilegeElement.add(allowValueElement);
}
// add element to parent
roleParentElement.add(privilegeElement);
}
}
}

View File

@ -36,7 +36,7 @@ public class InitializationHelper {
private static final Logger logger = Logger.getLogger(InitializationHelper.class);
/**
* Initializes the {@link PrivilegeHandler} from the configuration file
* Initializes the {@link DefaultPrivilegeHandler} from the configuration file
*
* @param privilegeXmlFile
* a {@link File} reference to the XML file containing the configuration for Privilege
@ -65,7 +65,7 @@ public class InitializationHelper {
PersistenceHandler persistenceHandler = ClassHelper.instantiateClass(persistenceHandlerClassName);
// instantiate privilege handler
PrivilegeHandler privilegeHandler = new DefaultPrivilegeHandler();
DefaultPrivilegeHandler privilegeHandler = new DefaultPrivilegeHandler();
// get policies
Element policiesElement = rootElement.element(XmlConstants.XML_POLICIES);
@ -93,7 +93,7 @@ public class InitializationHelper {
Map<String, String> parameterMap = convertToParameterMap(parameterElement);
// initialize persistence handler
persistenceHandler.initialize(parameterMap, policyMap);
persistenceHandler.initialize(parameterMap);
} catch (Exception e) {
logger.error(e, e);
@ -108,7 +108,7 @@ public class InitializationHelper {
Map<String, String> parameterMap = convertToParameterMap(parameterElement);
// initialize privilege handler
privilegeHandler.initialize(parameterMap, encryptionHandler, persistenceHandler);
privilegeHandler.initialize(parameterMap, encryptionHandler, persistenceHandler, policyMap);
} catch (Exception e) {
logger.error(e, e);

View File

@ -14,6 +14,7 @@ import java.io.Serializable;
import java.util.Set;
import ch.eitchnet.privilege.handler.PrivilegeHandler;
import ch.eitchnet.privilege.i18n.PrivilegeException;
import ch.eitchnet.privilege.model.internal.Privilege;
import ch.eitchnet.privilege.model.internal.Role;
import ch.eitchnet.privilege.policy.PrivilegePolicy;
@ -132,4 +133,46 @@ public class PrivilegeRep implements Serializable {
public void setAllowList(Set<String> allowList) {
this.allowList = allowList;
}
/**
* <p>
* Validates this {@link PrivilegeRep} so that a {@link Privilege} object can later be created from it
* </p>
*
* TODO write comment on how validation is done
*/
public void validate() {
if (this.name == null || this.name.isEmpty()) {
throw new PrivilegeException("No name defined!");
}
// if not all allowed, then validate that deny and allow lists are defined
if (this.allAllowed) {
// all allowed means no policy will be used
if (this.policy != null && !this.policy.isEmpty()) {
throw new PrivilegeException("All is allowed, so Policy may not be set!");
}
if (this.denyList != null && !this.denyList.isEmpty())
throw new PrivilegeException("All is allowed, so deny list must be null");
if (this.allowList != null && !this.allowList.isEmpty())
throw new PrivilegeException("All is allowed, so allow list must be null");
} else {
// not all allowed, so policy must be set
if (this.policy == null || this.policy.isEmpty()) {
throw new PrivilegeException("All is not allowed, so Policy must be defined!");
}
if (this.denyList == null) {
throw new PrivilegeException("All is not allowed, so deny list must be set, even if empty");
}
if (this.allowList == null) {
throw new PrivilegeException("All is not allowed, so allow list must be set, even if empty");
}
}
}
}

View File

@ -11,7 +11,7 @@
package ch.eitchnet.privilege.model;
import java.io.Serializable;
import java.util.Set;
import java.util.Map;
import ch.eitchnet.privilege.model.internal.Role;
@ -27,19 +27,19 @@ public class RoleRep implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Set<String> privileges;
private Map<String, PrivilegeRep> privilegeMap;
/**
* Default constructor
*
* @param name
* the name of this role
* @param privileges
* the set of privileges granted to this role
* @param privilegeMap
* the map of privileges granted to this role
*/
public RoleRep(String name, Set<String> privileges) {
public RoleRep(String name, Map<String, PrivilegeRep> privilegeMap) {
this.name = name;
this.privileges = privileges;
this.privilegeMap = privilegeMap;
}
/**
@ -58,17 +58,17 @@ public class RoleRep implements Serializable {
}
/**
* @return the privileges
* @return the privilegeMap
*/
public Set<String> getPrivileges() {
return this.privileges;
public Map<String, PrivilegeRep> getPrivilegeMap() {
return this.privilegeMap;
}
/**
* @param privileges
* the privileges to set
* @param privilegeMap
* the privilegeMap to set
*/
public void setPrivileges(Set<String> privileges) {
this.privileges = privileges;
public void setPrivileges(Map<String, PrivilegeRep> privilegeMap) {
this.privilegeMap = privilegeMap;
}
}

View File

@ -23,8 +23,9 @@ import ch.eitchnet.privilege.policy.PrivilegePolicy;
/**
* <p>
* {@link Privilege} is the main model object for Privilege. A {@link Role} has a set of Privileges assigned to it which
* defines the privileges a logged in user with that role has. For every privilege a {@link PrivilegePolicy} is
* configured which is used to evaluate if privilege is granted to a {@link Restrictable}
* defines the privileges a logged in user with that role has. If the {@link Privilege} has a {@link PrivilegePolicy}
* defined, then that policy will be used for finer granularity and with the deny and allow lists configured which is
* used to evaluate if privilege is granted to a {@link Restrictable}
* </p>
*
* <p>
@ -52,35 +53,64 @@ public final class Privilege {
* @param name
* the name of this privilege, which is unique to all privileges known in the {@link PrivilegeHandler}
* @param policy
* the {@link PrivilegePolicy} configured to evaluate if the privilege is granted
* the {@link PrivilegePolicy} configured to evaluate if the privilege is granted. If null, then
* privilege is granted
* @param allAllowed
* a boolean defining if a {@link Role} with this {@link Privilege} has unrestricted access to a
* {@link Restrictable}
* {@link Restrictable} in which case the deny and allow lists are ignored and can be null
* @param denyList
* a list of deny rules for this {@link Privilege}
* a list of deny rules for this {@link Privilege}, can be null if all allowed
* @param allowList
* a list of allow rules for this {@link Privilege}
* a list of allow rules for this {@link Privilege}, can be null if all allowed
*/
public Privilege(String name, String policy, boolean allAllowed, Set<String> denyList, Set<String> allowList) {
if (name == null || name.isEmpty()) {
throw new PrivilegeException("No name defined!");
}
if (policy == null || policy.isEmpty()) {
throw new PrivilegeException("No policy defined!");
}
if (denyList == null) {
throw new PrivilegeException("No denyList defined!");
}
if (allowList == null) {
throw new PrivilegeException("No allowList defined!");
}
this.name = name;
this.policy = policy;
this.allAllowed = allAllowed;
this.denyList = Collections.unmodifiableSet(denyList);
this.allowList = Collections.unmodifiableSet(allowList);
// if not all allowed, then validate that deny and allow lists are defined
if (allAllowed) {
this.allAllowed = true;
// all allowed means no policy will be used
this.policy = null;
this.denyList = Collections.emptySet();
this.allowList = Collections.emptySet();
} else {
this.allAllowed = false;
// not all allowed, so policy must be set
if (policy == null || policy.isEmpty()) {
throw new PrivilegeException("No Policy defined!");
}
this.policy = policy;
if (denyList == null) {
throw new PrivilegeException("No denyList defined!");
}
this.denyList = Collections.unmodifiableSet(denyList);
if (allowList == null) {
throw new PrivilegeException("No allowList defined!");
}
this.allowList = Collections.unmodifiableSet(allowList);
}
}
/**
* Constructs a {@link Privilege} from the {@link PrivilegeRep}
*
* @param privilegeRep
* the {@link PrivilegeRep} from which to create the {@link Privilege}
*/
public Privilege(PrivilegeRep privilegeRep) {
this(privilegeRep.getName(), privilegeRep.getPolicy(), privilegeRep.isAllAllowed(), privilegeRep.getDenyList(),
privilegeRep.getDenyList());
}
/**
@ -136,12 +166,6 @@ public final class Privilege {
builder.append(this.name);
builder.append(", policy=");
builder.append(this.policy);
builder.append(", allAllowed=");
builder.append(this.allAllowed);
builder.append(", denyList=");
builder.append(this.denyList);
builder.append(", allowList=");
builder.append(this.allowList);
builder.append("]");
return builder.toString();
}
@ -153,11 +177,7 @@ public final class Privilege {
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (this.allAllowed ? 1231 : 1237);
result = prime * result + ((this.allowList == null) ? 0 : this.allowList.hashCode());
result = prime * result + ((this.denyList == null) ? 0 : this.denyList.hashCode());
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result + ((this.policy == null) ? 0 : this.policy.hashCode());
return result;
}
@ -173,28 +193,12 @@ public final class Privilege {
if (getClass() != obj.getClass())
return false;
Privilege other = (Privilege) obj;
if (this.allAllowed != other.allAllowed)
return false;
if (this.allowList == null) {
if (other.allowList != null)
return false;
} else if (!this.allowList.equals(other.allowList))
return false;
if (this.denyList == null) {
if (other.denyList != null)
return false;
} else if (!this.denyList.equals(other.denyList))
return false;
if (this.name == null) {
if (other.name != null)
return false;
} else if (!this.name.equals(other.name))
return false;
if (this.policy == null) {
if (other.policy != null)
return false;
} else if (!this.policy.equals(other.policy))
return false;
return true;
}
}

View File

@ -11,10 +11,11 @@
package ch.eitchnet.privilege.model.internal;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;
import java.util.Map;
import ch.eitchnet.privilege.i18n.PrivilegeException;
import ch.eitchnet.privilege.model.PrivilegeRep;
import ch.eitchnet.privilege.model.RoleRep;
/**
@ -33,27 +34,54 @@ import ch.eitchnet.privilege.model.RoleRep;
public final class Role {
private final String name;
private final Set<String> privileges;
private final Map<String, Privilege> privilegeMap;
/**
* Default constructor
*
* @param name
* the name of the role
* @param privileges
* a set of names of privileges granted to this role
* @param privilegeMap
* a map of {@link Privilege}s granted to this role
*/
public Role(String name, Set<String> privileges) {
public Role(String name, Map<String, Privilege> privilegeMap) {
if (name == null || name.isEmpty()) {
throw new PrivilegeException("No name defined!");
}
if (privileges == null) {
if (privilegeMap == null) {
throw new PrivilegeException("No privileges defined!");
}
this.name = name;
this.privileges = Collections.unmodifiableSet(privileges);
this.privilegeMap = Collections.unmodifiableMap(privilegeMap);
}
/**
* Construct {@link Role} from its representation {@link RoleRep}
*
* @param roleRep
* the representation from which to create the {@link Role}
*/
public Role(RoleRep roleRep) {
String name = roleRep.getName();
if (name == null || name.isEmpty()) {
throw new PrivilegeException("No name defined!");
}
if (roleRep.getPrivilegeMap() == null) {
throw new PrivilegeException("No privileges defined!");
}
// build privileges from reps
Map<String, Privilege> privilegeMap = new HashMap<String, Privilege>(roleRep.getPrivilegeMap().size());
for (String privilegeName : roleRep.getPrivilegeMap().keySet()) {
privilegeMap.put(privilegeName, new Privilege(roleRep.getPrivilegeMap().get(privilegeName)));
}
this.name = name;
this.privilegeMap = Collections.unmodifiableMap(privilegeMap);
}
/**
@ -64,12 +92,12 @@ public final class Role {
}
/**
* Returns the {@link Set} of {@link Privilege} names which is granted to this {@link Role}
* Returns the {@link Map} of {@link Privilege}s which are granted to this {@link Role}
*
* @return the {@link Set} of {@link Privilege} names which is granted to this
* @return the {@link Map} of {@link Privilege}s which are granted to this {@link Role}
*/
public Set<String> getPrivileges() {
return this.privileges;
public Map<String, Privilege> getPrivilegeMap() {
return this.privilegeMap;
}
/**
@ -81,14 +109,18 @@ public final class Role {
* @return true if this {@link Role} has the {@link Privilege} with the given name
*/
public boolean hasPrivilege(String name) {
return this.privileges.contains(name);
return this.privilegeMap.containsKey(name);
}
/**
* @return a {@link RoleRep} which is a representation of this object used to serialize and view on clients
*/
public RoleRep asRoleRep() {
return new RoleRep(this.name, new HashSet<String>(this.privileges));
Map<String, PrivilegeRep> privilegeMap = new HashMap<String, PrivilegeRep>();
for (String privilegeName : this.privilegeMap.keySet()) {
privilegeMap.put(privilegeName, this.privilegeMap.get(privilegeName).asPrivilegeRep());
}
return new RoleRep(this.name, privilegeMap);
}
/**
@ -100,7 +132,7 @@ public final class Role {
builder.append("Role [name=");
builder.append(this.name);
builder.append(", privileges=");
builder.append(this.privileges);
builder.append(this.privilegeMap.keySet());
builder.append("]");
return builder.toString();
}
@ -113,7 +145,6 @@ public final class Role {
final int prime = 31;
int result = 1;
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result + ((this.privileges == null) ? 0 : this.privileges.hashCode());
return result;
}
@ -134,12 +165,6 @@ public final class Role {
return false;
} else if (!this.name.equals(other.name))
return false;
if (this.privileges == null) {
if (other.privileges != null)
return false;
} else if (!this.privileges.equals(other.privileges))
return false;
return true;
}
}

View File

@ -213,4 +213,35 @@ public final class User {
builder.append("]");
return builder.toString();
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.userId == null) ? 0 : this.userId.hashCode());
return result;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (this.userId == null) {
if (other.userId != null)
return false;
} else if (!this.userId.equals(other.userId))
return false;
return true;
}
}

View File

@ -11,7 +11,9 @@
package ch.eitchnet.privilege.test;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.ConsoleAppender;
@ -26,16 +28,28 @@ import ch.eitchnet.privilege.helper.InitializationHelper;
import ch.eitchnet.privilege.i18n.AccessDeniedException;
import ch.eitchnet.privilege.i18n.PrivilegeException;
import ch.eitchnet.privilege.model.Certificate;
import ch.eitchnet.privilege.model.PrivilegeRep;
import ch.eitchnet.privilege.model.Restrictable;
import ch.eitchnet.privilege.model.RoleRep;
import ch.eitchnet.privilege.model.UserRep;
import ch.eitchnet.privilege.model.UserState;
/**
* @author rvonburg
* JUnit for performing Privilege tests. This JUnit is by no means complete, but checks the bare minimum. TODO add more
* tests, especially with deny and allow lists
*
* @author rvonburg
*/
public class PrivilegeTest {
private static final String ADMIN = "admin";
private static final String PASS_ADMIN = "admin";
private static final String BOB = "bob";
private static final String TED = "ted";
private static final String PASS_BOB = "admin1";
private static final String ROLE_USER = "user";
private static final String PASS_BAD = "123";
private static final Logger logger = Logger.getLogger(PrivilegeTest.class);
private static PrivilegeHandler privilegeHandler;
@ -71,7 +85,7 @@ public class PrivilegeTest {
@Test
public void testAuthenticationOk() throws Exception {
Certificate certificate = privilegeHandler.authenticate("eitch", "1234567890");
Certificate certificate = privilegeHandler.authenticate(ADMIN, PASS_ADMIN);
org.junit.Assert.assertTrue("Certificate is null!", certificate != null);
}
@ -82,7 +96,7 @@ public class PrivilegeTest {
@Test(expected = AccessDeniedException.class)
public void testFailAuthenticationNOk() throws Exception {
Certificate certificate = privilegeHandler.authenticate("eitch", "123");
Certificate certificate = privilegeHandler.authenticate(ADMIN, PASS_BAD);
org.junit.Assert.assertTrue("Certificate is null!", certificate != null);
}
@ -93,7 +107,7 @@ public class PrivilegeTest {
@Test(expected = PrivilegeException.class)
public void testFailAuthenticationPWNull() throws Exception {
Certificate certificate = privilegeHandler.authenticate("eitch", null);
Certificate certificate = privilegeHandler.authenticate(ADMIN, null);
org.junit.Assert.assertTrue("Certificate is null!", certificate != null);
}
@ -102,17 +116,17 @@ public class PrivilegeTest {
* if something goes wrong
*/
@Test
public void testAddUserBobWithPW() throws Exception {
public void testAddUserBobAsAdmin() throws Exception {
Certificate certificate = privilegeHandler.authenticate("eitch", "1234567890");
Certificate certificate = privilegeHandler.authenticate(ADMIN, PASS_ADMIN);
// let's add a new user bob
UserRep userRep = new UserRep("1", "bob", "Bob", "Newman", UserState.NEW, new HashSet<String>(), null);
UserRep userRep = new UserRep("1", BOB, "Bob", "Newman", UserState.NEW, new HashSet<String>(), null);
privilegeHandler.addOrReplaceUser(certificate, userRep, null);
logger.info("Added user bob");
logger.info("Added user " + BOB);
// set bob's password
privilegeHandler.setUserPassword(certificate, "bob", "12345678901");
privilegeHandler.setUserPassword(certificate, BOB, PASS_BOB);
logger.info("Set Bob's password");
}
@ -124,8 +138,7 @@ public class PrivilegeTest {
*/
@Test(expected = AccessDeniedException.class)
public void testFailAuthAsBob() throws Exception {
privilegeHandler.authenticate("bob", "12345678901");
privilegeHandler.authenticate(BOB, PASS_BOB);
}
/**
@ -134,9 +147,8 @@ public class PrivilegeTest {
*/
@Test
public void testEnableUserBob() throws Exception {
Certificate certificate = privilegeHandler.authenticate("eitch", "1234567890");
privilegeHandler.setUserState(certificate, "bob", UserState.ENABLED);
Certificate certificate = privilegeHandler.authenticate(ADMIN, PASS_ADMIN);
privilegeHandler.setUserState(certificate, BOB, UserState.ENABLED);
}
/**
@ -148,7 +160,7 @@ public class PrivilegeTest {
@Test(expected = PrivilegeException.class)
public void testFailAuthUserBob() throws Exception {
Certificate certificate = privilegeHandler.authenticate("bob", "12345678901");
Certificate certificate = privilegeHandler.authenticate(BOB, PASS_BOB);
org.junit.Assert.assertTrue("Certificate is null!", certificate != null);
}
@ -157,10 +169,23 @@ public class PrivilegeTest {
* if something goes wrong
*/
@Test
public void testAddUserRoleToBob() throws Exception {
public void testAddRole() throws Exception {
Certificate certificate = privilegeHandler.authenticate(ADMIN, PASS_ADMIN);
Certificate certificate = privilegeHandler.authenticate("eitch", "1234567890");
privilegeHandler.addRoleToUser(certificate, "bob", "user");
Map<String, PrivilegeRep> privilegeMap = new HashMap<String, PrivilegeRep>();
RoleRep roleRep = new RoleRep(ROLE_USER, privilegeMap);
privilegeHandler.addOrReplaceRole(certificate, roleRep);
}
/**
* @throws Exception
* if something goes wrong
*/
@Test
public void testAddRoleToBob() throws Exception {
Certificate certificate = privilegeHandler.authenticate(ADMIN, PASS_ADMIN);
privilegeHandler.addRoleToUser(certificate, BOB, ROLE_USER);
}
/**
@ -169,8 +194,7 @@ public class PrivilegeTest {
*/
@Test
public void testAuthAsBob() throws Exception {
privilegeHandler.authenticate("bob", "12345678901");
privilegeHandler.authenticate(BOB, PASS_BOB);
}
/**
@ -182,13 +206,14 @@ public class PrivilegeTest {
@Test(expected = AccessDeniedException.class)
public void testFailAddUserTedAsBob() throws Exception {
Certificate certificate = privilegeHandler.authenticate("bob", "12345678901");
// auth as Bog
Certificate certificate = privilegeHandler.authenticate(BOB, PASS_BOB);
org.junit.Assert.assertTrue("Certificate is null!", certificate != null);
// let's add a new user bob
UserRep userRep = new UserRep("1", "bob", "Bob", "Newman", UserState.NEW, new HashSet<String>(), null);
// let's add a new user Ted
UserRep userRep = new UserRep("1", TED, "Ted", "And then Some", UserState.NEW, new HashSet<String>(), null);
privilegeHandler.addOrReplaceUser(certificate, userRep, null);
logger.info("Added user bob");
logger.info("Added user " + TED);
}
/**
@ -198,8 +223,9 @@ public class PrivilegeTest {
@Test
public void testAddAdminRoleToBob() throws Exception {
Certificate certificate = privilegeHandler.authenticate("eitch", "1234567890");
privilegeHandler.addRoleToUser(certificate, "bob", PrivilegeHandler.PRIVILEGE_ADMIN_ROLE);
Certificate certificate = privilegeHandler.authenticate(ADMIN, PASS_ADMIN);
privilegeHandler.addRoleToUser(certificate, BOB, PrivilegeHandler.PRIVILEGE_ADMIN_ROLE);
logger.info("Added " + PrivilegeHandler.PRIVILEGE_ADMIN_ROLE + " to " + ADMIN);
}
/**
@ -209,13 +235,13 @@ public class PrivilegeTest {
@Test
public void testAddUserTedAsBob() throws Exception {
Certificate certificate = privilegeHandler.authenticate("bob", "12345678901");
Certificate certificate = privilegeHandler.authenticate(BOB, PASS_BOB);
org.junit.Assert.assertTrue("Certificate is null!", certificate != null);
// let's add a new user ted
UserRep userRep = new UserRep("2", "ted", "Ted", "Newman", UserState.NEW, new HashSet<String>(), null);
UserRep userRep = new UserRep("2", TED, "Ted", "Newman", UserState.NEW, new HashSet<String>(), null);
privilegeHandler.addOrReplaceUser(certificate, userRep, null);
logger.info("Added user bob");
logger.info("Added user " + TED);
}
/**
@ -225,12 +251,12 @@ public class PrivilegeTest {
@Test
public void testPerformRestrictable() throws Exception {
Certificate certificate = privilegeHandler.authenticate("eitch", "1234567890");
Certificate certificate = privilegeHandler.authenticate(ADMIN, PASS_ADMIN);
org.junit.Assert.assertTrue("Certificate is null!", certificate != null);
// see if eitch can perform restrictable
Restrictable restrictable = new TestRestrictable();
boolean actionAllowed = privilegeHandler.actionAllowed(certificate, restrictable);
org.junit.Assert.assertTrue("eitch may not perform restrictable!", actionAllowed);
org.junit.Assert.assertTrue(ADMIN + " may not perform restrictable!", actionAllowed);
}
}

View File

@ -23,7 +23,7 @@ public class TestRestrictable implements Restrictable {
*/
@Override
public String getPrivilegeName() {
return "Service";
return "com.rsp.core.base.service.Service";
}
/**