Removed old policy related and deprecated code.
Change-Id: I678fdfda188dbda14078f4ccea5070f421401d05
diff --git a/core/Changes b/core/Changes
index 3b341f8..17ae3a2 100644
--- a/core/Changes
+++ b/core/Changes
@@ -1,3 +1,8 @@
+version 0.60
+01/03/2018
+ - removed old policy and deprecated code (margaretha)
+ - moved authentication related code to /full (margaretha)
+
version 0.59.10
20/02/2018
- updated hibernate and reflection versions (margaretha)
diff --git a/core/pom.xml b/core/pom.xml
index ee9b4b0..9b8bce9 100644
--- a/core/pom.xml
+++ b/core/pom.xml
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>de.ids_mannheim.korap</groupId>
<artifactId>Kustvakt-core</artifactId>
- <version>0.59.10</version>
+ <version>0.60</version>
<properties>
<java.version>1.8</java.version>
@@ -105,7 +105,7 @@
</execution>
</executions>
</plugin>
- <plugin>
+ <!-- <plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
@@ -118,17 +118,12 @@
<excludes>
<exclude>**/*APITest.java</exclude>
- <exclude>de/ids_mannheim/korap/suites/*.java</exclude>
- <exclude>**/KustvaktServerTest.java</exclude>
- <exclude>**/ResourceServiceTest.java</exclude>
- <exclude>**/ResourceInfoServiceTest.java</exclude>
- <exclude>**/PolicyServiceTest.java</exclude>
</excludes>
<includes>
<include>de/ids_mannheim/korap/**/*.java</include>
</includes>
</configuration>
- </plugin>
+ </plugin> -->
</plugins>
</build>
<dependencies>
@@ -188,16 +183,11 @@
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
- <!-- <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId>
- <version>1.7.5</version> </dependency> -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
- <!-- <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId>
- <version>1.2.17</version> </dependency> <dependency> <groupId>log4j</groupId>
- <artifactId>apache-log4j-extras</artifactId> <version>1.2.17</version> </dependency> -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@@ -325,23 +315,6 @@
<version>${spring-framework.version}</version>
</dependency>
- <!-- copied from extension -->
- <!-- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-jdbc</artifactId>
- <version>${spring-framework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-tx</artifactId>
- <version>${spring-framework.version}</version>
- </dependency>
- <dependency>
- <groupId>org.flywaydb</groupId>
- <artifactId>flyway-core</artifactId>
- <version>4.0</version>
- </dependency> -->
-
<!-- <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId>
<version>2.6.5</version> </dependency> -->
diff --git a/core/src/main/java/de/ids_mannheim/korap/config/AuthenticationMethod.java b/core/src/main/java/de/ids_mannheim/korap/config/AuthenticationMethod.java
deleted file mode 100644
index afd81ed..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/config/AuthenticationMethod.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package de.ids_mannheim.korap.config;
-
-public enum AuthenticationMethod {
- LDAP, SHIBBOLETH, DATABASE;
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/config/AuthenticationScheme.java b/core/src/main/java/de/ids_mannheim/korap/config/AuthenticationScheme.java
deleted file mode 100644
index 6d9c58e..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/config/AuthenticationScheme.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package de.ids_mannheim.korap.config;
-
-import org.apache.commons.lang.WordUtils;
-
-public enum AuthenticationScheme {
- // standard http
- BASIC, BEARER,
- // custom
- SESSION, API;
-
- public String displayName () {
- return WordUtils.capitalizeFully(name());
- }
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/config/BeanConfiguration.java b/core/src/main/java/de/ids_mannheim/korap/config/BeanConfiguration.java
index 36e6581..1dfe134 100644
--- a/core/src/main/java/de/ids_mannheim/korap/config/BeanConfiguration.java
+++ b/core/src/main/java/de/ids_mannheim/korap/config/BeanConfiguration.java
@@ -7,7 +7,6 @@
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
-import de.ids_mannheim.korap.interfaces.AuthenticationManagerIface;
import de.ids_mannheim.korap.interfaces.EncryptionIface;
import de.ids_mannheim.korap.interfaces.ValidatorIface;
import de.ids_mannheim.korap.interfaces.db.AuditingIface;
@@ -170,9 +169,9 @@
}
- public AuthenticationManagerIface getAuthenticationManager () {
- return getBean(KUSTVAKT_AUTHENTICATION_MANAGER);
- }
+// public AuthenticationManagerIface getAuthenticationManager () {
+// return getBean(KUSTVAKT_AUTHENTICATION_MANAGER);
+// }
public EntityHandlerIface getUserDBHandler () {
diff --git a/core/src/main/java/de/ids_mannheim/korap/config/ContextHolder.java b/core/src/main/java/de/ids_mannheim/korap/config/ContextHolder.java
index cb91a18..4139f5b 100644
--- a/core/src/main/java/de/ids_mannheim/korap/config/ContextHolder.java
+++ b/core/src/main/java/de/ids_mannheim/korap/config/ContextHolder.java
@@ -1,7 +1,5 @@
package de.ids_mannheim.korap.config;
-import de.ids_mannheim.korap.interfaces.AuthenticationIface;
-import de.ids_mannheim.korap.interfaces.AuthenticationManagerIface;
import de.ids_mannheim.korap.interfaces.EncryptionIface;
import de.ids_mannheim.korap.interfaces.ValidatorIface;
import de.ids_mannheim.korap.interfaces.db.*;
@@ -99,9 +97,9 @@
}
- public AuthenticationManagerIface getAuthenticationManager () {
- return getBean(KUSTVAKT_AUTHENTICATION_MANAGER);
- }
+// public AuthenticationManagerIface getAuthenticationManager () {
+// return getBean(KUSTVAKT_AUTHENTICATION_MANAGER);
+// }
public EntityHandlerIface getUserDBHandler () {
@@ -119,9 +117,9 @@
}
- public Collection<AuthenticationIface> getAuthProviders () {
- return getBean(KUSTVAKT_AUTHPROVIDERS);
- }
+// public Collection<AuthenticationIface> getAuthProviders () {
+// return getBean(KUSTVAKT_AUTHPROVIDERS);
+// }
public Collection<ResourceOperationIface> getResourceProviders () {
diff --git a/core/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationIface.java b/core/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationIface.java
deleted file mode 100644
index 8d715a7..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationIface.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package de.ids_mannheim.korap.interfaces;
-
-import java.util.Map;
-
-import de.ids_mannheim.korap.config.TokenType;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.user.TokenContext;
-import de.ids_mannheim.korap.user.User;
-
-public interface AuthenticationIface {
-
- public TokenContext getTokenContext(String authToken) throws KustvaktException;
-
-
- public TokenContext createTokenContext(User user, Map<String, Object> attr)
- throws KustvaktException;
-
-
- void removeUserSession (String token) throws KustvaktException;
-
-
- public TokenContext refresh (TokenContext context) throws KustvaktException;
-
-
- public TokenType getTokenType ();
-
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationManagerIface.java b/core/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationManagerIface.java
deleted file mode 100644
index f968b61..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/interfaces/AuthenticationManagerIface.java
+++ /dev/null
@@ -1,131 +0,0 @@
-package de.ids_mannheim.korap.interfaces;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.ws.rs.core.HttpHeaders;
-
-import de.ids_mannheim.korap.config.TokenType;
-import de.ids_mannheim.korap.config.AuthenticationMethod;
-import de.ids_mannheim.korap.config.AuthenticationScheme;
-import de.ids_mannheim.korap.config.KustvaktCacheable;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.user.TokenContext;
-import de.ids_mannheim.korap.user.User;
-import de.ids_mannheim.korap.user.Userdata;
-
-/**
- * @author hanl
- * @date 15/06/2015
- */
-public abstract class AuthenticationManagerIface extends KustvaktCacheable {
-
- private Map<TokenType, AuthenticationIface> providers;
-
-
- public AuthenticationManagerIface () {
- super("id_tokens", "key:id_tokens");
- this.providers = new HashMap<>();
- }
-
-
- public void setProviders (Set<AuthenticationIface> providers) {
- for (AuthenticationIface i : providers){
- this.providers.put(i.getTokenType(), i);
- }
- }
-
-
- protected AuthenticationIface getProvider (TokenType scheme, TokenType default_iface) {
-
- // Debug FB: loop a Map
-
- /*for (Map.Entry<String, AuthenticationIface> entry : this.providers.entrySet())
- {
- System.out.println("Debug: provider: Key : " + entry.getKey() + " Value : " + entry.getValue());
- }
- */
- // todo: configurable authentication schema
- if (scheme == null){
- return this.providers.get(default_iface);
- }
- else{
- return this.providers.get(scheme);
- }
- }
-
-
- public abstract TokenContext getTokenContext (TokenType type,
- String token, String host, String useragent)
- throws KustvaktException;
-
-
- public abstract User getUser (String username) throws KustvaktException;
-
- public abstract boolean isRegistered (String id);
-
-
- public abstract User authenticate (AuthenticationMethod method, String username,
- String password, Map<String, Object> attributes)
- throws KustvaktException;
-
- // public abstract User authenticate (int type, String username,
- // String password, Map<String, Object> attributes)
- // throws KustvaktException;
-
-
- public abstract TokenContext createTokenContext (User user,
- Map<String, Object> attr, TokenType type)
- throws KustvaktException;
-
-// public abstract TokenContext createTokenContext (User user,
-// Map<String, Object> attr, String provider_key)
-// throws KustvaktException;
-
- public abstract void setAccessAndLocation (User user, HttpHeaders headers);
-
- public abstract void logout (TokenContext context) throws KustvaktException;
-
-
- public abstract void lockAccount (User user) throws KustvaktException;
-
-
- public abstract User createUserAccount (Map<String, Object> attributes,
- boolean confirmation_required) throws KustvaktException;
-
-
- // public abstract boolean updateAccount(User user) throws KustvaktException;
-
- public abstract boolean deleteAccount (User user) throws KustvaktException;
-
-
- public abstract <T extends Userdata> T getUserData (User user,
- Class<T> clazz) throws KustvaktException;
-
-
- public abstract void updateUserData (Userdata data)
- throws KustvaktException;
-
-
- public abstract Object[] validateResetPasswordRequest (String username,
- String email) throws KustvaktException;
-
-
- public abstract void resetPassword (String uriFragment, String username,
- String newPassphrase) throws KustvaktException;
-
-
- public abstract void confirmRegistration (String uriFragment,
- String username) throws KustvaktException;
-
-
- public String providerList () {
- return "provider list: " + this.providers.toString();
- }
-
-
- public abstract User getUser (String username, String method)
- throws KustvaktException;
-
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionConstraint.java b/core/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionConstraint.java
deleted file mode 100644
index f005413..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/resource/rewrite/CollectionConstraint.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package de.ids_mannheim.korap.resource.rewrite;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import de.ids_mannheim.korap.config.Attributes;
-import de.ids_mannheim.korap.config.KustvaktConfiguration;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.resources.Corpus;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.security.ac.SecurityManager;
-import de.ids_mannheim.korap.user.User;
-
-/**
- * @author hanl
- * @date 03/07/2015
- */
-public class CollectionConstraint implements RewriteTask.IterableRewritePath {
-
-
-
- @Override
- public JsonNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
- User user) {
- if (node.get("@type").equals("koral:doc")) {
- if (node.get("key").equals(Attributes.CORPUS_SIGLE)) {
- String id = node.get("value");
- KustvaktResource corpus = check(id, user);
- if (corpus == null)
- node.removeNode(new KoralNode.RewriteIdentifier(
- Attributes.CORPUS_SIGLE, id));
- }
- }
- return node.rawNode();
- }
-
-
- /**
- * @param id
- * @param user
- * @return boolean if true access granted
- */
- private KustvaktResource check (String id, User user) {
- // todo: can be used to circumvent access control if public filter not applied
- if (user == null)
- return null;
-
- KustvaktResource corpus;
- try {
- SecurityManager m = SecurityManager
- .findbyId(id, user, Corpus.class);
- corpus = m.getResource();
- }
- catch (RuntimeException | KustvaktException e) {
- return null;
- }
- return corpus;
- }
-
-
- @Override
- public JsonNode rewriteResult (KoralNode node) {
- return null;
- }
-
-
- @Override
- public String path () {
- return "collection";
- }
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/resource/rewrite/PublicCollection.java b/core/src/main/java/de/ids_mannheim/korap/resource/rewrite/PublicCollection.java
deleted file mode 100644
index 406c342..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/resource/rewrite/PublicCollection.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package de.ids_mannheim.korap.resource.rewrite;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import de.ids_mannheim.korap.config.Attributes;
-import de.ids_mannheim.korap.config.KustvaktConfiguration;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.exceptions.StatusCodes;
-import de.ids_mannheim.korap.resources.Corpus;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.security.ac.ResourceFinder;
-import de.ids_mannheim.korap.user.User;
-import de.ids_mannheim.korap.utils.KoralCollectionQueryBuilder;
-import de.ids_mannheim.korap.utils.JsonUtils;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * @author hanl
- * @date 04/07/2015
- */
-// EM: use CollectionRewrite instead
-@Deprecated
-public class PublicCollection implements RewriteTask.RewriteQuery {
-
- public PublicCollection () {
- super();
- }
-
- @Deprecated
- public JsonNode rewriteQuery (KoralNode node, KustvaktConfiguration config,
- User user) throws KustvaktException {
- JsonNode subnode = node.rawNode();
-
- if (!subnode.at("/collection").findValuesAsText("key")
- .contains(Attributes.CORPUS_SIGLE)) {
- KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
- if (subnode.has("collection"))
- b.setBaseQuery(JsonUtils.toJSON(subnode));
-
- Set resources = ResourceFinder.search(user, Corpus.class);
- ArrayList<KustvaktResource> list = new ArrayList(resources);
-
- // fixme: throw exception in resourcefinder to indicate if no resource or no permission!
- if (list.isEmpty())
- throw new KustvaktException(
- StatusCodes.NO_POLICY_PERMISSION,
- "Resources could not be loaded for user ",
- user.getUsername());
-
- Set ids = new HashSet(resources.size());
- for (int i = 0; i < list.size(); i++) {
- if (i > 0)
- b.or();
- b.with(Attributes.CORPUS_SIGLE + "="
- + list.get(i).getPersistentID());
- ids.add(list.get(i).getPersistentID());
- }
- JsonNode rewritten = JsonUtils.readTree(b.toJSON());
- node.set("collection", rewritten.at("/collection"),
- new KoralNode.RewriteIdentifier(Attributes.CORPUS_SIGLE,
- ids));
- node.at("/collection");
- }
-
- return node.rawNode();
- }
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManagement.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManagement.java
deleted file mode 100644
index bda8260..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManagement.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.config.BeansFactory;
-import de.ids_mannheim.korap.exceptions.EmptyResultException;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.exceptions.NotAuthorizedException;
-import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.security.PolicyCondition;
-import de.ids_mannheim.korap.user.User;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-
-/**
- * @author hanl
- * @date 04/03/2014
- */
-public class ConditionManagement {
-
- private static final Logger jlog = LoggerFactory
- .getLogger(ConditionManagement.class);
- private User user;
- private PolicyHandlerIface policydao;
-
-
- public ConditionManagement (User user) {
- this.user = user;
- this.policydao = BeansFactory.getKustvaktContext()
- .getPolicyDbProvider();
-
- }
-
-
- /**
- * adds a user to an existing group
- *
- * @param usernames
- * @param condition
- * @param admin
- */
- // todo: conflict resolution
- // fixme: not applicable to korap system roles
- // only works if there is a policy with that condition and permission set, if not, create one!
- public void addUser (List<String> usernames, PolicyCondition condition,
- boolean admin) throws NotAuthorizedException, KustvaktException {
- if (policydao.matchCondition(this.user, condition.getSpecifier(), true) == 1) {
- policydao.addToCondition(usernames, condition, admin);
- }
- else
- jlog.error("Users '{}' could not be added to condition '{}'",
- usernames, condition.getSpecifier());
- }
-
-
- public void addUser (String username, PolicyCondition condition,
- boolean admin) throws NotAuthorizedException, KustvaktException {
- addUser(Arrays.asList(username), condition, admin);
- }
-
-
- public void removeUser (List<String> users, PolicyCondition condition)
- throws KustvaktException {
- if (policydao.matchCondition(this.user, condition.getSpecifier(), true) == 1) {
- policydao.removeFromCondition(users, condition);
- }
- }
-
-
- public Set<String> getMembers (PolicyCondition condition) {
- try {
- if (policydao.matchCondition(this.user, condition.getSpecifier(),
- true) == 1) {
- return new HashSet<>(policydao.getUsersFromCondition(condition));
- }
- }
- catch (KustvaktException e) {
- return Collections.emptySet();
- }
- return Collections.emptySet();
- }
-
-
- @Deprecated
- public void addUser (KustvaktResource resource, String user,
- Permissions.Permission ... pps) throws NotAuthorizedException,
- KustvaktException, EmptyResultException {
- addUser(resource, Arrays.asList(user), pps);
- }
-
-
- @Deprecated
- public void addUser (KustvaktResource resource, List<String> users,
- Permissions.Permission ... pps) throws NotAuthorizedException,
- KustvaktException, EmptyResultException {
- SecurityManager policies = SecurityManager.findbyId(resource.getId(),
- this.user);
- PolicyCondition c = policies.getExtensional(pps);
- if (c != null)
- this.addUser(users, c, false);
- else {
- PolicyCondition ex = new PolicyCondition();
- new PolicyBuilder(this.user).setResources(resource)
- .addCondition(ex.getSpecifier()).setPermissions(pps)
- .create();
- this.addUser(users, ex, false);
- }
- }
-
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManager.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManager.java
deleted file mode 100644
index ba984d6..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/ConditionManager.java
+++ /dev/null
@@ -1,111 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.config.BeansFactory;
-import de.ids_mannheim.korap.exceptions.EmptyResultException;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.exceptions.NotAuthorizedException;
-import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.security.PolicyCondition;
-import de.ids_mannheim.korap.user.User;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-
-/**
- * @author hanl
- * @date 04/03/2014
- */
-public class ConditionManager {
-
- private static final Logger jlog = LoggerFactory
- .getLogger(ConditionManager.class);
- private User user;
- private PolicyHandlerIface policydao;
-
-
- public ConditionManager (User user) {
- this.user = user;
- this.policydao = BeansFactory.getKustvaktContext()
- .getPolicyDbProvider();
- }
-
-
- /**
- * adds a user to an existing group
- *
- * @param usernames
- * @param condition
- * @param admin
- */
- // todo: conflict resolution
- // fixme: not applicable to korap system roles
- // only works if there is a policy with that condition and permission set, if not, create one!
- public void addUser (List<String> usernames, PolicyCondition condition,
- boolean admin) throws NotAuthorizedException, KustvaktException {
- if (policydao.matchCondition(this.user, condition.getSpecifier(), true) == 1) {
- policydao.addToCondition(usernames, condition, admin);
- }
- else
- jlog.error("Users '{}' could not be added to condition '{}'",
- usernames, condition.getSpecifier());
- }
-
-
- public void addUser (String username, PolicyCondition condition,
- boolean admin) throws NotAuthorizedException, KustvaktException {
- addUser(Arrays.asList(username), condition, admin);
- }
-
-
- public void removeUser (List<String> users, PolicyCondition condition)
- throws KustvaktException {
- if (policydao.matchCondition(this.user, condition.getSpecifier(), true) == 1) {
- policydao.removeFromCondition(users, condition);
- }
- }
-
-
- public Set<String> getMembers (PolicyCondition condition) {
- try {
- if (policydao.matchCondition(this.user, condition.getSpecifier(),
- true) == 1) {
- return new HashSet<>(policydao.getUsersFromCondition(condition));
- }
- }
- catch (KustvaktException e) {
- return Collections.emptySet();
- }
- return Collections.emptySet();
- }
-
-
- @Deprecated
- public void addUser (KustvaktResource resource, String user,
- Permissions.Permission ... pps) throws NotAuthorizedException,
- KustvaktException, EmptyResultException {
- addUser(resource, Arrays.asList(user), pps);
- }
-
-
- @Deprecated
- public void addUser (KustvaktResource resource, List<String> users,
- Permissions.Permission ... pps) throws NotAuthorizedException,
- KustvaktException, EmptyResultException {
- SecurityManager policies = SecurityManager.findbyId(resource.getId(),
- this.user);
- PolicyCondition c = policies.getExtensional(pps);
- if (c != null)
- this.addUser(users, c, false);
- else {
- PolicyCondition ex = new PolicyCondition();
- new PolicyBuilder(this.user).setResources(resource)
- .addCondition(ex.getSpecifier()).setPermissions(pps)
- .create();
- this.addUser(users, ex, false);
- }
- }
-
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyBuilder.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyBuilder.java
deleted file mode 100644
index fac7636..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyBuilder.java
+++ /dev/null
@@ -1,199 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.exceptions.StatusCodes;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.resources.Relation;
-import de.ids_mannheim.korap.response.Notifications;
-import de.ids_mannheim.korap.security.PolicyCondition;
-import de.ids_mannheim.korap.security.PolicyContext;
-import de.ids_mannheim.korap.security.SecurityPolicy;
-import de.ids_mannheim.korap.user.User;
-
-/**
- * @author hanl
- * @date 14/04/2014
- */
-
-// todo: also be able to create or edit relations
-public class PolicyBuilder {
-
- private Notifications notifications;
- private User user;
- private KustvaktResource[] resources;
- private KustvaktResource[] parents;
- private Permissions.Permission[] permissions;
- private PolicyCondition[] conditions;
- // private Map<String, ParameterSettingsHandler> settings;
- private Relation rel = null;
- private PolicyContext context;
-
-
- public PolicyBuilder (User user) {
- this.user = user;
- this.notifications = new Notifications();
- // fixme: other exception!?
- if (this.user.getId() == -1)
- throw new RuntimeException("user id must be a valid interger id");
- }
-
-
- public PolicyBuilder setResources (KustvaktResource ... targets) {
- this.resources = targets;
- this.parents = new KustvaktResource[targets.length];
- return this;
- }
-
-
- /**
- * set the parents for the resources. Order is relevant, since the
- * relation parent - resource is handled
- * via the index within the array. Parent relation is limited to
- * depth 1!
- * In case of a skipped parent resource relation within the array,
- * set 'null'
- *
- * @param parents
- * @return
- */
- public PolicyBuilder setParents (KustvaktResource ... parents) {
- for (int idx = 0; idx < parents.length; idx++)
- this.parents[idx] = parents[idx];
- return this;
- }
-
-
- public PolicyBuilder setContext (PolicyContext context) {
- this.context = context;
- return this;
- }
-
-
- public PolicyBuilder setContext (long start, long end) {
- if (this.context == null)
- this.context = new PolicyContext();
- this.context.setEnableTime(start);
- this.context.setExpirationTime(end);
- return this;
- }
-
-
- public PolicyBuilder setLocation (String iprange) {
- if (this.context == null)
- this.context = new PolicyContext();
- this.context.setIPMask(iprange);
- return this;
- }
-
-
- public PolicyBuilder setPermissions (Permissions.Permission ... permissions) {
- this.permissions = permissions;
- return this;
- }
-
-
- public PolicyBuilder setConditions (String ... conditions) {
- this.conditions = new PolicyCondition[conditions.length];
- for (int idx = 0; idx < conditions.length; idx++)
- this.conditions[idx] = new PolicyCondition(conditions[idx]);
- return this;
- }
-
-
- public PolicyBuilder setConditions (PolicyCondition ... conditions) {
- this.conditions = new PolicyCondition[conditions.length];
- for (int idx = 0; idx < conditions.length; idx++)
- this.conditions[idx] = conditions[idx];
- return this;
- }
-
-
- public PolicyBuilder setRelation (Relation rel) {
- this.rel = rel;
- return this;
- }
-
-
- public PolicyBuilder addCondition (String condition) {
- if (this.rel == null)
- setRelation(Relation.AND);
- return setConditions(condition);
- }
-
-
- public String create () throws KustvaktException {
- return this.doIt();
- }
-
-
- // for and relations there is no way of setting parameters conjoined with the policy
- private String doIt () throws KustvaktException {
- if (this.resources == null)
- throw new KustvaktException(user.getId(),
- StatusCodes.ILLEGAL_ARGUMENT, "resource must be set",
- "resource");
- if (this.permissions == null)
- throw new KustvaktException(user.getId(),
- StatusCodes.ILLEGAL_ARGUMENT, "permissions must be set",
- "permission");
- if (this.conditions == null)
- throw new KustvaktException(user.getId(),
- StatusCodes.ILLEGAL_ARGUMENT, "conditions must be set",
- "condition");
- if (this.rel == null)
- this.rel = Relation.AND;
-
- for (int idx = 0; idx < this.resources.length; idx++) {
- try {
- if (parents[idx] != null)
- resources[idx].setParentID(parents[idx].getPersistentID());
- SecurityManager manager = SecurityManager.register(
- resources[idx], user);
-
- if (rel.equals(Relation.AND)) {
- SecurityPolicy policy = new SecurityPolicy()
- .setConditions(this.conditions)
- .setTarget(resources[idx])
- .addPermission(permissions)
- .setCreator(this.user.getId());
-
- if (this.context != null)
- policy.setContext(this.context);
-
- manager.addPolicy(policy);
-
- }
- else if (rel.equals(Relation.OR)) {
- for (PolicyCondition c : this.conditions) {
- SecurityPolicy policy = new SecurityPolicy()
- .addNewCondition(c).setTarget(resources[idx])
- .addPermission(permissions)
- .setCreator(this.user.getId());
-
- if (this.context != null)
- policy.setContext(this.context);
-
- //todo: ???
- // if (this.settings != null) {
- // ParameterSettingsHandler settings = this.settings
- // .get(c.getSpecifier());
- // if (settings != null) {
- // // fixme: context setting overlap!
- // policy.setContext(settings.getContext());
- // manager.addPolicy(policy, settings.getParameters());
- // continue;
- // }
- // }
- manager.addPolicy(policy);
- }
- }
- }
- catch (KustvaktException e) {
- this.notifications.addError(e.getStatusCode(), e.getMessage(),
- resources[idx].getPersistentID());
- }
- }
- return notifications.toJsonString();
- }
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyDao.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyDao.java
deleted file mode 100644
index 72b52bc..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyDao.java
+++ /dev/null
@@ -1,937 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.exceptions.StatusCodes;
-import de.ids_mannheim.korap.exceptions.DatabaseException;
-import de.ids_mannheim.korap.interfaces.db.PersistenceClient;
-import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
-import de.ids_mannheim.korap.resources.Foundry;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.ResourceFactory;
-import de.ids_mannheim.korap.security.Parameter;
-import de.ids_mannheim.korap.security.PolicyCondition;
-import de.ids_mannheim.korap.security.SecurityPolicy;
-import de.ids_mannheim.korap.config.Attributes;
-import de.ids_mannheim.korap.user.User;
-import de.ids_mannheim.korap.utils.BooleanUtils;
-import de.ids_mannheim.korap.utils.StringUtils;
-import de.ids_mannheim.korap.utils.TimeUtils;
-import edu.emory.mathcs.backport.java.util.Collections;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.dao.DataAccessException;
-import org.springframework.jdbc.core.ResultSetExtractor;
-import org.springframework.jdbc.core.RowCallbackHandler;
-import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
-import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
-import org.springframework.jdbc.support.GeneratedKeyHolder;
-import org.springframework.jdbc.support.KeyHolder;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-
-/**
- * @author hanl
- * @date 14/01/2014
- */
-// todo: transactions and exception management
-public class PolicyDao implements PolicyHandlerIface {
-
- private static final Logger jlog = LoggerFactory.getLogger(PolicyDao.class);
-
- private NamedParameterJdbcTemplate jdbcTemplate;
-
-
- public PolicyDao (PersistenceClient client) {
- this.jdbcTemplate = (NamedParameterJdbcTemplate) client.getSource();
- }
-
-
- /**
- * @param policy
- * @param user
- * @return int to indicate the rows updated/inserted
- * @throws KustvaktException
- */
- // fixme: better way of dealing with this?
- // fixme: enable needs to be set specifically for mysql db
- @Override
- public int createPolicy (SecurityPolicy policy, User user)
- throws KustvaktException {
- String sql = "INSERT INTO policy_store (target_id, creator, created, posix, enable, expire, iprange)"
- + " SELECT id, :creator, :cr, :posix, :en, :exp, :ip FROM resource_store WHERE persistent_id=:target;";
-
- if (policy.getTarget() == null)
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.NO_POLICY_TARGET, "Persistent id is missing.",
- policy.toString());
-
- if (policy.getConditions().isEmpty())
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.NO_POLICY_CONDITION,
- "Policy conditions are missing.");
-
- if (policy.getPermissionByte() == 0)
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.NO_POLICY_PERMISSION,
- "Policy permissions are missing.");
-
- KeyHolder keyHolder = new GeneratedKeyHolder();
- MapSqlParameterSource np = new MapSqlParameterSource();
- np.addValue("target", policy.getTarget());
- if (policy.getContext().getEnd() != 0L)
- np.addValue("exp", policy.getContext().getEnd());
- else
- np.addValue("exp", null);
- np.addValue("en", policy.getContext().getStart());
- np.addValue("posix", policy.getPermissionByte());
- np.addValue("cr", new Timestamp(TimeUtils.getNow().getMillis()));
- np.addValue("creator", user.getId());
- np.addValue("ip", policy.getContext().getIpmask());
-
- try {
- mapConditionsToUsers(policy, user);
- this.jdbcTemplate.update(sql, np, keyHolder, new String[] { "id" });
- policy.setID(keyHolder.getKey().intValue());
- this.mapConstraints(policy);
- return policy.getID();
- }
- catch (DataAccessException e) {
- e.printStackTrace();
- jlog.error("Operation (INSERT) not possible for '{}' for user '{}'",
- policy.toString(), user.getId());
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.DB_INSERT_FAILED, policy.toString());
- }
- }
-
-
- /**
- * should also include a remove operation, so removed policy
- * constraints
- *
- * @param policy
- * @return
- * @throws KustvaktException
- */
- // benchmark this!
- @Override
- public void mapConstraints (SecurityPolicy policy)
- throws KustvaktException {
- final String cond = "INSERT INTO group_ref (group_id, policy_id) VALUES (:group, :policyID);";
- final String remove = "DELETE FROM group_ref WHERE group_id=:group and policy_id=:policyID;";
- try {
- List<PolicyCondition> conditions = policy.getConditions();
- int idx = 0;
- if (!policy.getRemoved().isEmpty()) {
- MapSqlParameterSource[] sources_removed = new MapSqlParameterSource[policy
- .getRemoved().size()];
- for (Integer toremove : policy.getRemoved()) {
- MapSqlParameterSource source = new MapSqlParameterSource();
- source.addValue("group",
- conditions.get(toremove).getSpecifier());
- source.addValue("policyID", policy.getID());
- sources_removed[idx++] = source;
- }
- this.jdbcTemplate.batchUpdate(remove, sources_removed);
- }
-
- // todo: naming convention!
- if (!policy.getAdded().isEmpty()) {
- idx = 0;
- MapSqlParameterSource[] sources = new MapSqlParameterSource[policy
- .getAdded().size()];
- for (Integer add : policy.getAdded()) {
- MapSqlParameterSource source = new MapSqlParameterSource();
- source.addValue("group",
- conditions.get(add).getSpecifier());
- source.addValue("policyID", policy.getID());
- sources[idx++] = source;
- }
- this.jdbcTemplate.batchUpdate(cond, sources);
- }
- policy.clear();
- }
- catch (DataAccessException e) {
- e.printStackTrace();
- jlog.error(
- "Operation (MAPPING POLICY CONDITIONS) not possible for '{}' for user '{}'",
- policy.toString(), policy.getCreator());
- // throwing an error here is not recommended
- // throw new dbException(policy.getCreator(), "policy_store",
- // StatusCodes.DB_INSERT_FAILED, policy.toString());
- }
- }
-
-
- // todo: check transactional behaviour! --> rollback
- private void mapConditionsToUsers (SecurityPolicy policy, User user)
- throws KustvaktException {
- for (PolicyCondition cond : policy.getConditions()) {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("name", cond.getSpecifier());
- param.addValue("userid", user.getId());
-
- try {
- final Integer[] results = new Integer[2];
- jdbcTemplate.query(
- "SELECT COUNT(*) as total, (select count(*) from group_users where user_id=:userid and "
- + "group_id=:name) as users FROM group_store WHERE name=:name",
- param, new RowCallbackHandler() {
- @Override
- public void processRow (ResultSet rs)
- throws SQLException {
- results[0] = rs.getInt("total");
- results[1] = rs.getInt("users");
- }
- });
-
- boolean admin = false;
- if (results[0] == 0) {
- admin = true;
- this.createCondition(cond, user);
- }
- if (results[1] == 0)
- this.addToCondition(Arrays.asList(user.getUsername()), cond,
- admin);
- }
- catch (DataAccessException e) {
- jlog.error(
- "Operation (SELECT) not possible for '{}' for user '{}'",
- policy.getTarget(), user.getId());
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.DB_GET_FAILED,
- "Operation (SELECT) is not possible for "
- + policy.getTarget() + " for user "
- + user.getUsername(),
- policy.toString());
- }
- }
- }
-
-
- // fixme: does not compare permissions. parent can still disregard policy because of missing permisssions
- @Override
- public List<SecurityPolicy>[] getPolicies (Integer target, final User user,
- Byte perm) {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("target", target);
- param.addValue("userid", user.getId());
- param.addValue("perm", perm);
- param.addValue("en", TimeUtils.getNow().getMillis());
-
- String sql_new = "select pv.*, pv.perm & :perm as allowed, rh.depth, (select max(depth) from resource_tree \n"
- + "where child_id=rh.child_id) as max_depth from policy_view as pv "
- + "inner join resource_tree as rh on rh.parent_id=pv.id "
- + "where rh.child_id=:target and pv.enable <= :en and (pv.expire > :en or pv.expire is NULL) and "
- + "(pv.group_id='self' or pv.group_id in (select g.group_id from group_users as g where g.user_id=:userid)) and "
- + "(select sum(distinct depth) from resource_tree where child_id=rh.child_id) = "
- + "(select sum(distinct res.depth) from policy_view as pos inner join resource_tree as res on res.parent_id=pos.id where (pos.group_id in (select g.group_id from group_users as g "
- + "where g.user_id=:userid) or pos.group_id='self') and res.child_id=rh.child_id group by child_id);";
-
- try {
- return this.jdbcTemplate.query(sql_new, param,
- new ResultSetExtractor<List<SecurityPolicy>[]>() {
-
- @Override
- public List<SecurityPolicy>[] extractData (ResultSet rs)
- throws SQLException, DataAccessException {
- return SecurityRowMappers.mapResourcePolicies(rs);
- }
- });
- }
- catch (DataAccessException e) {
- jlog.error(
- "Permission Denied for policy retrieval for '{}' for user '{}'",
- target, user.getId());
- return new List[2];
- }
- }
-
-
- // without root policies, since these are policies from different resources!
- @Override
- public List<SecurityPolicy> getPolicies (PolicyCondition condition,
- Class<? extends KustvaktResource> clazz, Byte perm) {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("cond", condition.getSpecifier());
- param.addValue("perm", perm);
- param.addValue("type", ResourceFactory.getResourceMapping(clazz));
- param.addValue("en", TimeUtils.getNow().getMillis());
- String sql_new = "select pv.*, pv.perm & :perm as allowed, "
- + "rh.depth, (select max(depth) from resource_tree "
- + "where child_id=rh.child_id) as max_depth from policy_view as pv "
- + "inner join resource_tree as rh on rh.parent_id=pv.id "
- + "where "
- + "pv.enable <= :en and (pv.expire > :en or pv.expire is NULL) and "
- + "pv.group_id=:cond and pv.type=:type and "
- + "(select sum(distinct depth) from resource_tree where child_id=rh.child_id) = "
- + "(select sum(distinct res.depth) from policy_view as pos inner join resource_tree as res on res.parent_id=pos.id where (pos.group_id=:cond)"
- + " and res.child_id=rh.child_id group by child_id)";
-
- try {
- return this.jdbcTemplate.query(sql_new, param,
- new ResultSetExtractor<List<SecurityPolicy>>() {
-
- @Override
- public List<SecurityPolicy> extractData (ResultSet rs)
- throws SQLException, DataAccessException {
- return SecurityRowMappers.mapConditionPolicies(rs);
- }
- });
- }
- catch (DataAccessException e) {
- jlog.error("Permission Denied: policy retrieval for '{}'",
- condition.getSpecifier());
- return Collections.emptyList();
- }
- }
-
-
- // EM: should only return one policy
- @Override
- public List<SecurityPolicy> getPoliciesByPersistentId (
- PolicyCondition condition, Class<? extends KustvaktResource> clazz,
- byte perm, String persistentId) {
-
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("cond", condition.getSpecifier());
- param.addValue("perm", perm);
- param.addValue("type", ResourceFactory.getResourceMapping(clazz));
- param.addValue("en", TimeUtils.getNow().getMillis());
- param.addValue("persistentId", persistentId);
- String sql_new = "select pv.*, pv.perm & :perm as allowed, "
- + "rh.depth, (select max(depth) from resource_tree "
- + "where child_id=rh.child_id) as max_depth from policy_view as pv "
- + "inner join resource_tree as rh on rh.parent_id=pv.id "
- + "where " + "pv.persistent_id =:persistentId and "
- + "pv.enable <= :en and (pv.expire > :en or pv.expire is NULL) and "
- + "pv.group_id=:cond and pv.type=:type";
-
- try {
- return this.jdbcTemplate.query(sql_new, param,
- new ResultSetExtractor<List<SecurityPolicy>>() {
-
- @Override
- public List<SecurityPolicy> extractData (ResultSet rs)
- throws SQLException, DataAccessException {
- List<SecurityPolicy> policies = SecurityRowMappers
- .mapConditionPolicies(rs);
- if (policies.size() > 1)
- jlog.warn(
- "Policy ids are not uniques. Found more than one policy for id:"
- + policies.get(0).getID());
- return policies;
- }
- });
- }
- catch (DataAccessException e) {
- jlog.error(e.getLocalizedMessage());
- return Collections.emptyList();
- }
- }
-
-
- @Override
- public List<SecurityPolicy>[] getPolicies (String target, final User user,
- Byte perm) {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("target", target);
- param.addValue("userid", user.getId());
- param.addValue("perm", perm);
- param.addValue("en", TimeUtils.getNow().getMillis());
-
- String sql_new = "select pv.*, pv.perm & :perm as allowed, "
- + "rh.depth, (select max(depth) from resource_tree "
- + "where child_id=rh.child_id) as max_depth from policy_view as pv "
- + "inner join resource_tree as rh on rh.parent_id=pv.id "
- + "where rh.child_id=(select id from resource_store where persistent_id=:target) and "
- + "pv.enable <= :en and (pv.expire > :en or pv.expire is NULL) and "
- + "(pv.group_id='self' or pv.group_id in (select g.group_id from group_users as g where g.user_id=:userid)) and "
- + "(select sum(distinct depth) from resource_tree where child_id=rh.child_id) = "
- + "(select sum(distinct res.depth) from policy_view as pos inner join resource_tree as res on res.parent_id=pos.id where (pos.group_id in (select g.group_id from group_users "
- + "as g where g.user_id=:userid) or pos.group_id='self') and res.child_id=rh.child_id group by child_id)";
- try {
- return this.jdbcTemplate.query(sql_new, param,
- new ResultSetExtractor<List<SecurityPolicy>[]>() {
-
- @Override
- public List<SecurityPolicy>[] extractData (ResultSet rs)
- throws SQLException, DataAccessException {
- List<SecurityPolicy>[] pol = SecurityRowMappers
- .mapResourcePolicies(rs);
- return pol;
- }
- });
- }
- catch (DataAccessException e) {
- jlog.error(
- "Permission Denied: policy retrieval for '{}' for user '{}'",
- target, user.getId());
- return new List[2];
- }
- }
-
-
- @Override
- public List<SecurityPolicy>[] findPolicies (String path, final User user,
- Byte perm) {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("path", StringUtils.buildSQLRegex(path));
- param.addValue("userid", user.getId());
- param.addValue("perm", perm);
- param.addValue("en", TimeUtils.getNow().getMillis());
-
- String sql_new = "select pv.*, pv.perm & :perm as allowed, "
- + "rh.depth, (select max(depth) from resource_tree "
- + "where child_id=rh.child_id) as max_depth from policy_view as pv "
- + "inner join resource_tree as rh on rh.parent_id=pv.id "
- + "where rt.name_path regexp :path and "
- + "pv.enable <= :en and (pv.expire > :en or pv.expire is NULL) and "
- + "(pv.group_id='self' or pv.group_id in (select g.group_id from group_users as g where g.user_id=:userid)) and "
- + "(select sum(distinct depth) from resource_tree where child_id=rh.child_id) = "
- + "(select sum(distinct res.depth) from policy_view as pos inner join resource_tree as res on res.parent_id=pos.id where (pos.group_id in (select g.group_id from group_users "
- + "as g where g.user_id=:userid) or pos.group_id='self') and res.child_id=rh.child_id group by child_id)";
-
- try {
- return this.jdbcTemplate.query(sql_new, param,
- new ResultSetExtractor<List<SecurityPolicy>[]>() {
-
- @Override
- public List<SecurityPolicy>[] extractData (ResultSet rs)
- throws SQLException, DataAccessException {
- return SecurityRowMappers.mapResourcePolicies(rs);
- }
- });
- }
- catch (DataAccessException e) {
- jlog.error(
- "Permission Denied for retrieval for resource id '{}' for user '{}'",
- path, user.getId());
- return new List[2];
- }
- }
-
-
- /**
- * @param path
- * if set searches in path where the child element
- * equals name. Also applicable for root resources!
- * @param user
- * @param clazz
- * @return
- */
- //todo: not working yet!
- // todo: does not concern itsself with location matching, ever!
- @Override
- public List<KustvaktResource.Container> getDescending (String path,
- final User user, Byte b,
- final Class<? extends KustvaktResource> clazz)
- throws KustvaktException {
- final MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("userid", user.getId());
- param.addValue("type", ResourceFactory.getResourceMapping(clazz));
- param.addValue("part", "%" + path);
- param.addValue("perm", b);
-
- String sql;
- if (path != null && !path.isEmpty()) {
- sql = "select pv.*, pv.perm & :perm as allowed, rh.depth, rh.name_path, (select max(depth) from resource_tree \n"
- + "where child_id=rh.child_id) as max_depth from policy_view as pv "
- + "inner join resource_tree as rh on rh.child_id=pv.id "
- + "where pv.type=:type and (rh.name_path like :part) and ((pv.creator=:userid and pv.group_id='self') or "
- + "(pv.group_id in (select g.group_id from group_users as g where g.user_id=:userid) and "
- + "(select sum(distinct depth) from resource_tree where child_id=rh.child_id) = "
- + "(select sum(distinct depth) from policy_view as pos inner join resource_tree as res on res.parent_id=pos.id "
- + "where pos.group_id in (select g.group_id from group_users as g where g.user_id=:userid) "
- + "and res.child_id=rh.child_id group by child_id))) "
- + "group by pv.pid, pv.id having count(distinct pv.group_id) = "
- + "((select count(co.group_id) from group_ref as co where co.policy_id=pv.pid) or "
- + "(select 1 from policy_view as cp2 where cp2.group_id='self' and cp2.id=pv.id)) "
- + "order by rh.depth asc, pv.id desc;";
- }
- else {
- sql = "select pv.*, pv.perm & :perm as allowed, rh.depth, rh.name_path, (select max(depth) from resource_tree \n"
- + "where child_id=rh.child_id) as max_depth from policy_view as pv "
- + "inner join resource_tree as rh on rh.child_id=pv.id "
- + "where pv.type=:type and ((pv.creator=:userid and pv.group_id='self') or "
- + "(pv.group_id in (select g.group_id from group_users as g where g.user_id=:userid) and "
- + "(select sum(distinct depth) from resource_tree where child_id=rh.child_id) = "
- + "(select sum(distinct depth) from policy_view as pos inner join resource_tree as res on res.parent_id=pos.id "
- + "where pos.group_id in (select g.group_id from group_users as g where g.user_id=:userid) "
- + "and res.child_id=rh.child_id group by child_id))) "
- + "group by pv.pid, pv.id having count(distinct pv.group_id) = "
- + "((select count(co.group_id) from group_ref as co where co.policy_id=pv.pid) or "
- + "(select 1 from policy_view as cp2 where cp2.group_id='self' and cp2.id=pv.id)) "
- + "order by rh.depth asc, pv.id desc;";
- }
- try {
- return this.jdbcTemplate.query(sql, param,
- new SecurityRowMappers.HierarchicalResultExtractor());
- }
- catch (DataAccessException e) {
- jlog.error(
- "Permission Denied for retrieval for path '{}' for user '{}'",
- path, user.getId());
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.DB_GET_FAILED,
- "Permission is denied for retrieval for path " + path
- + " for user " + user.getUsername(),
- path, clazz.toString());
- }
- }
-
-
- @Override
- public List<KustvaktResource.Container> getAscending (String name,
- User user, Byte b, Class<? extends KustvaktResource> clazz)
- throws KustvaktException {
- final MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("userid", user.getId());
- param.addValue("type", ResourceFactory.getResourceMapping(clazz));
- param.addValue("part", "%" + name);
- param.addValue("perm", b);
-
- String sql;
- if (name != null && !name.isEmpty()) {
- sql = "select pv.*, pv.perm & :perm as allowed, rh.depth, rh.name_path,\n"
- + "(select max(depth) from resource_tree \n"
- + "where child_id=rh.child_id) as max_depth from policy_view as pv\n"
- + "inner join resource_tree as rh on rh.child_id=pv.id\n"
- + "where pv.id in (select rt.parent_id from resource_tree as rt inner join resource_store rs on rs.id=rt.child_id\n"
- + "where rs.type=:type and rt.name_path like :part) and ((pv.creator=:userid and pv.group_id='self') or\n"
- + "(pv.group_id in (select g.group_id from group_users as g where g.user_id=:userid) and\n"
- + "(select sum(distinct depth) from resource_tree where child_id=rh.child_id) =\n"
- + "(select sum(distinct depth) from policy_view as pos inner join resource_tree as res on res.parent_id=pos.id\n"
- + "where pos.group_id in (select g.group_id from group_users as g where g.user_id=:userid)\n"
- + "and res.child_id=rh.child_id group by child_id)))\n"
- + "group by pv.pid, pv.id having count(distinct pv.group_id) = \n"
- + "case when pv.creator=:userid then 1 else (select count(distinct co.group_id) "
- + "from group_ref as co where co.policy_id=pv.pid) end order by rh.depth desc, pv.id desc;";
- }
- else {
- sql = "select pv.*, pv.perm & :perm as allowed, rh.depth, rh.name_path,\n"
- + "(select max(depth) from resource_tree \n"
- + "where child_id=rh.child_id) as max_depth from policy_view as pv\n"
- + "inner join resource_tree as rh on rh.child_id=pv.id\n"
- + "where pv.id in (select rt.parent_id from resource_tree as rt inner join resource_store rs on rs.id=rt.child_id\n"
- + "where rs.type=:type) and ((pv.creator=:userid and pv.group_id='self') or\n"
- + "(pv.group_id in (select g.group_id from group_users as g where g.user_id=:userid) and\n"
- + "(select sum(distinct depth) from resource_tree where child_id=rh.child_id) =\n"
- + "(select sum(distinct depth) from policy_view as pos inner join resource_tree as res on res.parent_id=pos.target_id\n"
- + "where pos.group_id in (select g.group_id from group_users as g where g.user_id=:userid)\n"
- + "and res.child_id=rh.child_id group by child_id)))\n"
- + "group by pv.pid, pv.id having count(distinct pv.group_id) = \n"
- + "case when pv.creator=:userid then 1 else (select count(distinct co.group_id) "
- + "from group_ref as co where co.policy_id=pv.pid) end order by rh.depth desc, pv.id desc;";
- }
- try {
- return this.jdbcTemplate.query(sql, param,
- new SecurityRowMappers.HierarchicalResultExtractor());
- }
- catch (DataAccessException e) {
- jlog.error(
- "Permission Denied for retrieval for path '{}' for user '{}'",
- name, user.getId());
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.DB_GET_FAILED,
- "Permission is denied for retrieval for path " + name
- + "for user" + user.getUsername() + ".",
- name, clazz.toString());
- }
- }
-
-
- // todo: return all resources or only leave nodes? --> currently only leaves are returned
- // todo: access to leave node also means that the path to the root for that permission is allowed,
- // todo: thus all upper resource access is as well allowed
-
-
- //todo: remove not used context?! --> who is allowed to do so?
- @Override
- public int deletePolicy (SecurityPolicy policy, User user)
- throws KustvaktException {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("id", policy.getID());
-
- try {
- this.jdbcTemplate
- .update("DELETE FROM group_ref WHERE policy_id=:id", param);
- return this.jdbcTemplate
- .update("DELETE FROM policy_store WHERE id=:id", param);
- }
- catch (DataAccessException e) {
- jlog.error("Operation (DELETE) not possible for '{}' for user '{}'",
- policy.toString(), user.getId());
- throw new DatabaseException(user.getId(), "policy_store, group_ref",
- StatusCodes.DB_DELETE_FAILED,
- "Operation (DELETE) is not possible for user.",
- policy.toString());
- }
- }
-
-
- @Override
- public int deleteResourcePolicies (String id, User user)
- throws KustvaktException {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("id", id);
- String sql = "DELETE FROM policy_store WHERE target_id in (SELECT id FROM resource_store WHERE persistent_id=:id);";
- try {
- return this.jdbcTemplate.update(sql, param);
- }
- catch (DataAccessException e) {
- jlog.error("Operation (DELETE) not possible for '{}' for user '{}'",
- id, user.getId());
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.DB_DELETE_FAILED,
- "Operation (DELETE) is not possible for user "
- + user.getUsername(),
- id);
- }
- }
-
-
- @Override
- public int updatePolicy (SecurityPolicy policy, User user)
- throws KustvaktException {
- MapSqlParameterSource np = new MapSqlParameterSource();
- np.addValue("posix", policy.getPermissionByte());
- np.addValue("en", policy.getContext().getStart());
- np.addValue("ex", policy.getContext().getEnd());
- np.addValue("id", policy.getID());
-
- try {
- int result = this.jdbcTemplate.update(
- "UPDATE policy_store SET posix=:posix WHERE id=:id", np);
- this.mapConstraints(policy);
- return result;
- }
- catch (DataAccessException e) {
- jlog.error("Operation (UPDATE) not possible for '{}' for user '{}'",
- policy.toString(), user.getId());
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.DB_UPDATE_FAILED,
- "Operation (UPDATE) on " + policy.toString()
- + " is not possible for user" + user.getUsername(),
- policy.toString());
- }
- }
-
-
- @Override
- public int checkPolicy (SecurityPolicy policy, User user)
- throws KustvaktException {
- if (policy.getID() == -1)
- return 0;
-
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("id", policy.getID());
- String sql1 = "SELECT COUNT(*) FROM policy_store AS p WHERE p.id=:id;";
-
- try {
- return this.jdbcTemplate.queryForObject(sql1, param, Integer.class);
- }
- catch (DataAccessException e) {
- jlog.error("Operation (SELECT) not possible for '{}' for user '{}'",
- policy.getTarget(), user.getId());
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.DB_GET_FAILED,
- "Operation (SELECT) on " + policy.getTarget()
- + " is not possible for user " + user.getUsername(),
- policy.toString());
- }
- }
-
-
- /**
- * checks if the user is a member of the specified group.
- * Additional ownership can be tested via boolean flag
- *
- * @param user
- * @param group
- * @param owner
- * @return
- * @throws KustvaktException
- */
- @Override
- public int matchCondition (User user, String group, boolean owner)
- throws KustvaktException {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("userid", user.getId());
- param.addValue("group", group);
- param.addValue("isadmin", BooleanUtils.getBoolean(owner));
- String sql;
- if (owner) {
- sql = "SELECT COUNT(*) FROM group_users AS gu INNER JOIN group_store AS gs "
- + "ON gs.name=gu.group_id WHERE gu.user_id=:userid "
- + "AND gs.name=:group AND gu.admin=:isadmin;";
- }
- else {
- sql = "SELECT COUNT(*) FROM group_users AS gu INNER JOIN group_store AS gs "
- + "ON gs.name=gu.group_id WHERE gu.user_id=:userid "
- + "AND gs.name=:group;";
- }
-
- try {
- return this.jdbcTemplate.queryForObject(sql, param, Integer.class);
- }
- catch (DataAccessException e) {
- jlog.error("Operation (SELECT) not possible for '{}' for user '{}'",
- group, user.getId());
- throw new DatabaseException(user.getId(), "policy_store",
- StatusCodes.DB_GET_FAILED,
- "Operation (SELECT) is not possible for user "
- + user.getUsername(),
- group);
- }
- }
-
-
- private void createCondition (PolicyCondition condition, User user)
- throws KustvaktException {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("name", condition.getSpecifier());
- param.addValue("ex", condition.getFlags().get(Attributes.EXPORT));
- param.addValue("qo", condition.getFlags().get(Attributes.QUERY_ONLY));
- param.addValue("com", condition.getFlags().get(Attributes.COMMERCIAL));
- param.addValue("sy", condition.getFlags().get(Attributes.SYM_USE));
- param.addValue("ex", condition.getFlags().get(Attributes.LICENCE));
- try {
- this.jdbcTemplate
- .update("INSERT INTO group_store (name, sym_use, export, commercial) "
- + "VALUES (:name, :sy, :ex, :com);", param);
- }
- catch (DataAccessException e) {
- jlog.error("Operation (INSERT) not possible for '{}'",
- condition.toString());
- throw new DatabaseException(user.getId(), "group_store",
- StatusCodes.DB_INSERT_FAILED,
- "Operation (INSERT) is not possible for",
- condition.toString());
- }
- }
-
-
- //todo: check for unique constraint exception and exclude from throw!
- @Override
- public int addToCondition (String username, PolicyCondition condition,
- boolean admin) throws KustvaktException {
- final String insert = "INSERT INTO group_users (user_id, group_id, admin) "
- + "VALUES ((SELECT id FROM korap_users "
- + "WHERE username=:username), :group, :status);";
- try {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("group", condition.getSpecifier());
- param.addValue("username", username);
- param.addValue("status", BooleanUtils.getBoolean(admin));
- return this.jdbcTemplate.update(insert, param);
- }
- catch (DataAccessException e) {
- //todo: test with mysql
- if (!e.getMessage().toLowerCase()
- .contains("UNIQUE".toLowerCase())) {
- jlog.error(
- "Operation (INSERT) not possible for '{}' for user '{}'",
- condition.toString(), username);
- throw new DatabaseException(null, "group_store",
- StatusCodes.DB_INSERT_FAILED,
- "Operation (INSERT) on " + condition.toString()
- + " is not possible for user " + username,
- condition.toString());
- }
- return 0;
- }
- }
-
-
- /**
- * @param usernames
- * @param condition
- * @param admin
- * @return
- * @throws KustvaktException
- * userID and group_id have a unique constraint,
- * thus: if any of the supplied users is already a
- * member of the group, the entire chain will be
- * broken!
- */
- //todo definitely needs rework
- //todo: test the unique index constraints!
- @Override
- public int[] addToCondition (List<String> usernames,
- PolicyCondition condition, boolean admin) throws KustvaktException {
- MapSqlParameterSource[] sources = new MapSqlParameterSource[usernames
- .size()];
-
- // todo: use unique index for that! problematic though --> why? no special exception?
- // final String select = "select count(id) from group_users where userID=" +
- // "(select id from korap_users where username=:username) " +
- // "AND group_id=:group;";
-
- //todo: use index to create uniqueness. how to batch?
- final String insert = "INSERT INTO group_users (user_id, group_id, admin) "
- + "VALUES ((SELECT id FROM korap_users "
- + "WHERE username=:username), :group, :status);";
- try {
- for (int idx = 0; idx < usernames.size(); idx++) {
- //todo: dont do that here
- if (usernames.get(idx) == null || usernames.get(idx).isEmpty())
- throw new KustvaktException(StatusCodes.ILLEGAL_ARGUMENT);
-
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("group", condition.getSpecifier());
- param.addValue("username", usernames.get(idx));
- param.addValue("status", BooleanUtils.getBoolean(admin));
- // if primary keys uniqueness is determined by both keys, then use
- // that as checkup (may also be manageable via triggers)
- // if (this.jdbcTemplate
- // .queryForObject(select, param, Integer.class) == 0)
- sources[idx] = param;
- }
-
- // todo: only insert if user is not already a member of this group
- //fixme: problem - unique constraints throws exception. skip that user entry?!
- return this.jdbcTemplate.batchUpdate(insert, sources);
- }
- catch (DataAccessException e) {
- if (!e.getCause().toString().contains("UNIQUE")) {
- jlog.error(
- "Operation (INSERT) not possible for '{}' for user '{}'",
- condition.toString(), usernames, e);
- throw new KustvaktException(
- "Operation (INSERT) not possible for '"
- + condition.toString() + "' for user '"
- + usernames + "'",
- e, StatusCodes.CONNECTION_ERROR);
- }
- return null;
- }
- }
-
-
- @Override
- public void removeFromCondition (List<String> usernames,
- PolicyCondition condition) throws KustvaktException {
- MapSqlParameterSource[] sources = new MapSqlParameterSource[usernames
- .size()];
- int idx = 0;
- for (String s : usernames) {
- MapSqlParameterSource param = new MapSqlParameterSource();
- param.addValue("group", condition.getSpecifier());
- param.addValue("username", s);
- sources[idx++] = param;
- }
-
- final String del = "DELETE FROM group_users WHERE group_id=:group AND user_id=(SELECT id FROM "
- + "korap_users WHERE username=:username);";
-
- try {
- this.jdbcTemplate.batchUpdate(del, sources);
- }
- catch (DataAccessException e) {
- jlog.error("Operation (DELETE) not possible for '{}' for user '{}'",
- condition.toString(), usernames);
- throw new KustvaktException(e, StatusCodes.CONNECTION_ERROR);
- }
- }
-
-
- @Override
- public int createParamBinding (Parameter param) throws KustvaktException {
- MapSqlParameterSource source = new MapSqlParameterSource();
- source.addValue("key", param.getName());
- source.addValue("policy", param.getPolicy().getID());
- source.addValue("value", param.getValue());
- source.addValue("flag", param.isEqual());
-
- //todo:
- // if (!parameterExists(param.getName()))
- // createParameter(param.getName(), "", param.getOwner());
- final String insert = "INSERT INTO param_map (param_id, policy_id, value, flag) VALUES ((SELECT id FROM param_store "
- + "WHERE p_key=:key), (SELECT id FROM policy_store WHERE id=:policy), :value, :flag);";
- try {
- return this.jdbcTemplate.update(insert, source);
- }
- catch (DataAccessException e) {
- jlog.error("Operation (INSERT) not possible for '{}",
- param.toString());
- throw new KustvaktException(e, StatusCodes.CONNECTION_ERROR);
- }
- }
-
-
- @Override
- public List<String> getUsersFromCondition (PolicyCondition condition)
- throws KustvaktException {
- MapSqlParameterSource source = new MapSqlParameterSource();
- source.addValue("specifier", condition.getSpecifier());
- final String sql1 = "SELECT username FROM korap_users WHERE id IN (SELECT user_id FROM "
- + "group_users WHERE group_id=:specifier);";
- try {
- return this.jdbcTemplate.queryForList(sql1, source, String.class);
- }
- catch (DataAccessException e) {
- jlog.error("Operation (SELECT) not possible for '{}'",
- condition.toString());
- throw new KustvaktException(StatusCodes.CONNECTION_ERROR);
- }
- }
-
-
- private boolean parameterExists (String key) {
- MapSqlParameterSource source = new MapSqlParameterSource();
- source.addValue("key", key);
- final String select = "SELECT COUNT(*) FROM param_store WHERE p_key=:key;";
- return this.jdbcTemplate.queryForObject(select, source,
- Integer.class) == 1;
- }
-
-
- private void createParameter (String parameter, String value, Integer owner)
- throws KustvaktException {
- MapSqlParameterSource source = new MapSqlParameterSource();
- source.addValue("name", parameter);
- source.addValue("value", value);
- source.addValue("owner", owner);
- final String sql = "INSERT INTO param_store (p_key, p_value) VALUES (:name, :value);";
- try {
- this.jdbcTemplate.update(sql, source);
- }
- catch (DataAccessException e) {
- throw new KustvaktException(e, StatusCodes.CONNECTION_ERROR);
- }
- }
-
-
- @Override
- public int removeParamBinding (SecurityPolicy policy)
- throws KustvaktException {
- MapSqlParameterSource source = new MapSqlParameterSource();
- source.addValue("id", policy.getID());
- final String sql = "DELETE FROM param_map WHERE policy_id=:id";
- try {
- return this.jdbcTemplate.update(sql, source);
- }
- catch (DataAccessException e) {
- throw new KustvaktException(e, StatusCodes.CONNECTION_ERROR);
- }
- }
-
-
- @Override
- public int size () {
- String sql = "SELECT COUNT(*) FROM policy_view;";
- try {
- return this.jdbcTemplate.queryForObject(sql,
- new HashMap<String, Object>(), Integer.class);
- }
- catch (DataAccessException e) {
- return 0;
- }
- }
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyEvaluator.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyEvaluator.java
deleted file mode 100644
index 928ca77..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/PolicyEvaluator.java
+++ /dev/null
@@ -1,184 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.exceptions.NotAuthorizedException;
-import de.ids_mannheim.korap.exceptions.StatusCodes;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.security.PermissionsBuffer;
-import de.ids_mannheim.korap.security.SecurityPolicy;
-import de.ids_mannheim.korap.user.KorAPUser;
-import de.ids_mannheim.korap.user.User;
-import edu.emory.mathcs.backport.java.util.Collections;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Created by hanl on 5/22/14.
- */
-@Deprecated
-public class PolicyEvaluator {
-
- private static final Logger jlog = LoggerFactory
- .getLogger(PolicyEvaluator.class);
-
- private final User user;
- private final List<SecurityPolicy>[] policies;
- private String resourceID;
- private PermissionsBuffer permissions;
- private boolean processed;
- private int relationError = -1;
- @Deprecated
- private Map<String, Object> flags;
-
-
- public PolicyEvaluator (User user, List<SecurityPolicy>[] policies) {
- this.user = user;
- this.policies = policies;
- this.permissions = new PermissionsBuffer();
- this.flags = new HashMap<>();
- }
-
-
- private PolicyEvaluator (User user, KustvaktResource resource) {
- this.user = user;
- this.resourceID = resource.getPersistentID();
- this.permissions = new PermissionsBuffer();
- this.flags = new HashMap<>();
- this.policies = null;
- }
-
-
- public String getResourceID () {
- if (this.resourceID == null && policies[0] != null
- && policies[0].get(0) != null)
- this.resourceID = policies[0].get(0).getTarget();
- return this.resourceID;
- }
-
-
- // todo: test benchmarks
- private List<SecurityPolicy> evaluate (List<SecurityPolicy>[] policies,
- Permissions.Permission perm) throws NotAuthorizedException {
- //fixme: what happens in case a parent relation does not allow changing a resource, but the owner of child per default
- //todo: receives all rights? --> test casing
- if (isOwner()) {
- jlog.debug("Resource is owned by the user!");
- return policies[0];
- }
- if (!processed && policies != null) {
- for (int i = policies.length - 1; i >= 0; i--) {
- int idx = 0;
- if (policies[i] != null) {
- int ow = getOwner(policies[i]);
- for (int internal = 0; internal < policies[i].size(); internal++) {
- SecurityPolicy s = policies[i].get(internal);
- if (i == policies.length - 1) {
- if (ow == user.getId())
- this.permissions.addPermission(127);
- else if (!(s instanceof SecurityPolicy.OwnerPolicy))
- this.permissions.addPermission(s
- .getPermissionByte());
- }
- else {
- if (ow == user.getId())
- this.permissions.retain(127);
- else if (!(s instanceof SecurityPolicy.OwnerPolicy))
- this.permissions.retain(s.getPermissionByte());
- }
- idx++;
- }
- }
- // checks that there are valid policies on higher level resources, so that user is
- if (idx == 0) {
- relationError = i;
- throw new NotAuthorizedException(
- StatusCodes.ACCESS_DENIED, this.getResourceID());
- }
- }
- this.processed = true;
- if (this.permissions.containsPermission(perm))
- return policies[0];
- }
- else if (processed && relationError == -1
- && this.permissions.containsPermission(perm)) {
- jlog.debug("Done processing resource policies");
- jlog.debug("Will return policies to security manager: "
- + this.policies[0]);
- return this.policies[0];
- }
-
- return Collections.emptyList();
- }
-
-
- /**
- * checks read permission
- *
- * @return
- */
- public boolean isAllowed () {
- return isAllowed(Permissions.Permission.READ);
- }
-
-
- public boolean isAllowed (Permissions.Permission perm) {
- try {
- List s = evaluate(this.policies, perm);
- return s != null && !s.isEmpty();
- }
- catch (NotAuthorizedException e) {
- return false;
- }
- }
-
-
- public boolean isOwner () {
- return policies != null && this.user.getId() != null
- && getOwner(this.policies[0]) == this.user.getId();
- }
-
-
- private int getOwner (List<SecurityPolicy> policies) {
- if (policies != null && policies.get(0) != null
- && policies.get(0) instanceof SecurityPolicy.OwnerPolicy) {
- return ((SecurityPolicy.OwnerPolicy) policies.get(0)).getOwner();
- }
- return -1;
- }
-
-
- // todo: what is this supposed to do?
- @Deprecated
- public static PolicyEvaluator setFlags (User user, KustvaktResource resource) {
- PolicyEvaluator e = new PolicyEvaluator(user, resource);
- // e.setFlag("managed", resource.getOwner() == KorAPUser.ADMINISTRATOR_ID);
- // e.setFlag("shared", false);
- return e;
- }
-
-
- public <V> V getFlag (String key, V value) {
- return (V) this.flags.get(key);
- }
-
-
- private <V> void setFlag (String key, V value) {
- this.flags.put(key, value);
- }
-
-
- public boolean isManaged () {
- //return getOwner(this.policies[0]) == KorAPUser.ADMINISTRATOR_ID;
- return false;
- }
-
-
- public boolean isShared () {
- return !isManaged() && !isOwner();
- }
-
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/ResourceFinder.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/ResourceFinder.java
deleted file mode 100644
index c24d956..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/ResourceFinder.java
+++ /dev/null
@@ -1,227 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.config.ContextHolder;
-import de.ids_mannheim.korap.config.BeansFactory;
-import de.ids_mannheim.korap.exceptions.EmptyResultException;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.exceptions.StatusCodes;
-import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
-import de.ids_mannheim.korap.interfaces.db.ResourceOperationIface;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.resources.ResourceFactory;
-import de.ids_mannheim.korap.security.PermissionsBuffer;
-import de.ids_mannheim.korap.security.PolicyCondition;
-import de.ids_mannheim.korap.security.SecurityPolicy;
-import de.ids_mannheim.korap.config.Attributes;
-import de.ids_mannheim.korap.user.User;
-import lombok.NonNull;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-
-/**
- * Created by hanl on 3/20/14.
- */
-//todo: use factory pattern to init resourcefinder
-public class ResourceFinder {
-
- private static final Logger jlog = LoggerFactory
- .getLogger(ResourceFinder.class);
- private static PolicyHandlerIface policydao;
- private static Map<Class, ResourceOperationIface> resourcedaos = new HashMap<>();
-
- private List<KustvaktResource.Container> containers;
- private User user;
-
-
- private ResourceFinder (User user) {
- this();
- this.user = user;
- }
-
-
- private ResourceFinder () {
- this.containers = new ArrayList<>();
- overrideProviders(null);
- }
-
-
- public static void overrideProviders (ContextHolder beans) {
- if (beans == null)
- beans = BeansFactory.getKustvaktContext();
- if (policydao == null | resourcedaos == null) {
- ResourceFinder.policydao = beans.getPolicyDbProvider();
- for (ResourceOperationIface iface : beans.getResourceProviders())
- resourcedaos.put(iface.type(), iface);
- }
- if (policydao == null | resourcedaos.isEmpty())
- throw new RuntimeException("provider not set!");
- }
-
-
- public static <T extends KustvaktResource> Set<T> search (String path,
- boolean asParent, User user, Class<T> clazz,
- Permissions.Permission ... perms) throws KustvaktException {
- ResourceFinder cat = init(path, asParent, user, clazz, perms);
- return cat.getResources();
- }
-
-
- private static <T extends KustvaktResource> ResourceFinder init (
- String path, boolean asParent, User user, Class<T> clazz,
- Permissions.Permission ... perms) throws KustvaktException {
- ResourceFinder cat = new ResourceFinder(user);
- PermissionsBuffer buffer = new PermissionsBuffer();
- if (perms.length == 0)
- buffer.addPermissions(Permissions.Permission.READ);
- buffer.addPermissions(perms);
- cat.retrievePolicies(path, buffer.getPbyte(), clazz, asParent);
- return cat;
- }
-
-
- //todo: needs to be much faster!
- public static <T extends KustvaktResource> ResourceFinder init (
- @NonNull User user, Class<T> clazz) throws KustvaktException {
- return init(null, true, user, clazz, Permissions.Permission.READ);
- }
-
-
- public static <T extends KustvaktResource> Set<T> search (String name,
- boolean asParent, User user, String type) throws KustvaktException {
- return (Set<T>) search(name, asParent, user,
- ResourceFactory.getResourceClass(type),
- Permissions.Permission.READ);
- }
-
- @Deprecated
- public static <T extends KustvaktResource> Set<T> searchPublic (
- Class<T> clazz) throws KustvaktException {
- return searchPublicFiltered(clazz);
- }
-
- public static <T extends KustvaktResource> Set<T> searchPublicFilteredIntId (
- Class<T> clazz, int ... ids) throws KustvaktException {
-
- overrideProviders(null);
- Set<T> sets = new HashSet<>();
-
- List<SecurityPolicy> policies = policydao.getPolicies(
- new PolicyCondition(Attributes.PUBLIC_GROUP), clazz,
- Permissions.Permission.READ.toByte());
- ArrayList<Integer> id_set = new ArrayList<>(ids.length);
- for(int id : ids){
- id_set.add(id);
- }
-
- for (SecurityPolicy policy : policies) {
- jlog.debug("PolicyID retrieved: "+policy.getID()+" "+policy.getTarget());
- if (id_set.isEmpty() || id_set.contains(policy.getID())) {
- @SuppressWarnings("unchecked")
- T r = (T) resourcedaos.get(KustvaktResource.class).findbyId(
- policy.getID(), User.UserFactory.getDemoUser());
- sets.add(r);
- }
- }
-
- if (sets.isEmpty()){
- throw new KustvaktException(StatusCodes.NO_RESULT_FOUND,
- "Cannot found public "+clazz.getSimpleName()+" with ids: "+id_set.toString());
- }
- return sets;
- }
-
- @Deprecated
- public static <T extends KustvaktResource> Set<T> searchPublicFiltered (
- Class<T> clazz, String ... ids) throws KustvaktException {
- overrideProviders(null);
- Set<T> sets = new HashSet<>();
- List<SecurityPolicy> policies = policydao.getPolicies(
- new PolicyCondition(Attributes.PUBLIC_GROUP), clazz,
- Permissions.Permission.READ.toByte());
-
- List<String> id_set = Arrays.asList(ids);
- for (SecurityPolicy policy : policies) {
- if (id_set.isEmpty() || id_set.contains(policy.getTarget())) {
- @SuppressWarnings("unchecked")
- T r = (T) resourcedaos.get(KustvaktResource.class).findbyId(
- policy.getTarget(), User.UserFactory.getDemoUser());
- sets.add(r);
- }
- }
-
- if (sets.isEmpty()){
- throw new KustvaktException(StatusCodes.NO_RESULT_FOUND,
- "Cannot found public "+clazz.getSimpleName()+" with ids: "+id_set.toString());
- }
- return sets;
- }
-
-
- // todo: should this be working?
- public static <T extends KustvaktResource> Set<T> search (User user,
- Class<T> clazz) throws KustvaktException {
- Set set = new HashSet();
- if (user != null && !User.UserFactory.isDemo(user.getUsername()))
- set = search(null, true, user, clazz, Permissions.Permission.READ);
- if (set.isEmpty())
- set = searchPublic(clazz);
- return set;
- }
-
-
- private void retrievePolicies (String path, Byte b, Class type,
- boolean parent) throws KustvaktException {
- //fixme: throw exception to avoid susequent exceptions due to unknown origin
- if (user == null | type == null)
- return;
- if (parent)
- this.containers = policydao.getDescending(path, user, b, type);
- else
- this.containers = policydao.getAscending(path, user, b, type);
- }
-
-
- // fixme: only return field --> extra git repo!
- public <T extends KustvaktResource> Set<T> getResources () {
- return evaluateResources();
- }
-
-
- // todo: redo with less memory usage/faster
- private <T extends KustvaktResource> Set<T> evaluateResources () {
- Set<T> resources = new HashSet<>();
- if (this.containers != null) {
- for (KustvaktResource.Container c : this.containers) {
- try {
- T resource = (T) resourcedaos.get(KustvaktResource.class)
- .findbyId(c.getPersistentID(), this.user);
- if (resource != null) {
- PolicyEvaluator e = PolicyEvaluator.setFlags(user,
- resource);
- // resource.setManaged(e.getFlag("managed", false));
- resources.add(resource);
- }
- }
- catch (KustvaktException e) {
- // don't handle connection error or no handler registered!
- jlog.error("Error while retrieving containers '{}' ",
- this.containers);
- return Collections.emptySet();
- }
- }
- }
- return resources;
- }
-
-
- public Set<String> getIds () {
- Set<String> resources = new HashSet<>();
- for (KustvaktResource.Container c : this.containers)
- resources.add(c.getPersistentID());
- return resources;
- }
-
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/ResourceHandler.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/ResourceHandler.java
deleted file mode 100644
index 4d9f272..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/ResourceHandler.java
+++ /dev/null
@@ -1,183 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.config.KustvaktCacheable;
-import de.ids_mannheim.korap.exceptions.EmptyResultException;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.exceptions.NotAuthorizedException;
-import de.ids_mannheim.korap.exceptions.StatusCodes;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.resources.ResourceFactory;
-import de.ids_mannheim.korap.user.User;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Element;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collection;
-
-/**
- * @author hanl
- * @date 23/03/2014
- */
-
-//todo: use interface (maybe a cachable interface?) and bean instanceing
-// todo: if cachable, data integrity needs to be checked! either remove caching or check integrity!
-@SuppressWarnings("all")
-public class ResourceHandler extends KustvaktCacheable {
-
- private static Logger jlog = LoggerFactory.getLogger(ResourceHandler.class);
-
-
- public ResourceHandler () {
- super("resources", "key:resources");
- }
-
-
- @Deprecated
- public <T extends KustvaktResource> T getCache (Object id, Class<T> cz) {
- Element e = CacheManager.getInstance().getCache("resources").get(id);
- if (e != null)
- return (T) e.getObjectValue();
- else
- return null;
- }
-
-
- @Deprecated
- public <R extends KustvaktResource> void cache (R resource) {
- CacheManager.getInstance().getCache("resources")
- .put(new Element(resource.getPersistentID(), resource));
- }
-
-
- /**
- * @param id
- * @param user
- * @return
- * @throws KustvaktException
- * if there is no handler registered, resource might
- * still be valid,
- * only Notauthorized exception will cause a parsing
- * error here
- * @throws NotAuthorizedException
- */
- public <T extends KustvaktResource> T findbyIntId (Integer id, User user)
- throws KustvaktException, NotAuthorizedException {
- SecurityManager<T> p;
- try {
- p = SecurityManager.findbyId(id, user);
- }
- catch (EmptyResultException e) {
- throw new NotAuthorizedException(StatusCodes.NO_RESULT_FOUND,
- String.valueOf(id));
- }
- return p.getResource();
- }
-
-
- public <T extends KustvaktResource> T findbyStrId (String persistent_id,
- User user, String type) throws KustvaktException,
- NotAuthorizedException {
- return (T) findbyStrId(persistent_id, user,
- ResourceFactory.getResourceClass(type));
- }
-
-
- public <T extends KustvaktResource> T findbyStrId (String persistent_id,
- User user, Class<T> type) throws KustvaktException,
- NotAuthorizedException {
- SecurityManager<T> p;
- try {
- p = SecurityManager.findbyId(persistent_id, user, type);
- }
- catch (EmptyResultException e) {
- throw new NotAuthorizedException(StatusCodes.NO_RESULT_FOUND,
- persistent_id);
- }
- return p.getResource();
- }
-
-
- public <T extends KustvaktResource> Collection<T> findbyPath (String path,
- Class type, User user) throws KustvaktException,
- NotAuthorizedException {
- return ResourceFinder.search(path, false, user, type);
- }
-
-
- public <T extends KustvaktResource> void updateResources (User user,
- T ... resources) throws KustvaktException, NotAuthorizedException {
- // fixme: what if update fails? then i have a root policy lingering for a resource that is not available?!
- // fixme: transaction management
-
- for (T resource : resources) {
- SecurityManager policies;
- try {
- policies = SecurityManager.init(resource.getPersistentID(),
- user, Permissions.Permission.WRITE);
- }
- catch (EmptyResultException e) {
- return;
- }
- policies.updateResource(resource);
- }
- }
-
-
- public <T extends KustvaktResource> void storeResources (User user,
- T ... resources) throws KustvaktException, NotAuthorizedException {
- for (T resource : resources)
- SecurityManager.register(resource, user);
- }
-
-
- @Deprecated
- public <T extends KustvaktResource> void deleteResources (User user,
- String ... ids) throws KustvaktException, NotAuthorizedException {
- for (String id : ids) {
- SecurityManager policies;
- try {
- policies = SecurityManager.init(id, user,
- Permissions.Permission.DELETE);
- }
- catch (EmptyResultException e) {
- return;
- }
- policies.deleteResource();
- }
- }
-
-
- public <T extends KustvaktResource> void deleteResources (User user,
- T ... resources) throws KustvaktException, NotAuthorizedException {
- for (T r : resources) {
- SecurityManager manager;
- try {
- manager = SecurityManager.findbyId(r.getPersistentID(), user,
- r.getClass(), Permissions.Permission.DELETE);
- }
- catch (EmptyResultException e) {
- return;
- }
- manager.deleteResource();
- }
- }
-
-
- @Deprecated
- public <T extends KustvaktResource> void deleteResources (User user,
- Integer ... ids) throws KustvaktException, NotAuthorizedException {
- for (Integer id : ids) {
- SecurityManager policies;
- try {
- policies = SecurityManager.findbyId(id, user,
- Permissions.Permission.DELETE);
- }
- catch (EmptyResultException e) {
- return;
- }
- policies.deleteResource();
- }
- }
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManager.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManager.java
deleted file mode 100644
index f8f5990..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManager.java
+++ /dev/null
@@ -1,543 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.config.ContextHolder;
-import de.ids_mannheim.korap.config.BeansFactory;
-import de.ids_mannheim.korap.exceptions.EmptyResultException;
-import de.ids_mannheim.korap.exceptions.KustvaktException;
-import de.ids_mannheim.korap.exceptions.NotAuthorizedException;
-import de.ids_mannheim.korap.exceptions.StatusCodes;
-import de.ids_mannheim.korap.interfaces.EncryptionIface;
-import de.ids_mannheim.korap.interfaces.db.PolicyHandlerIface;
-import de.ids_mannheim.korap.interfaces.db.ResourceOperationIface;
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.Permissions;
-import de.ids_mannheim.korap.resources.ResourceFactory;
-import de.ids_mannheim.korap.security.Parameter;
-import de.ids_mannheim.korap.security.PermissionsBuffer;
-import de.ids_mannheim.korap.security.PolicyCondition;
-import de.ids_mannheim.korap.security.SecurityPolicy;
-import de.ids_mannheim.korap.user.User;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.*;
-
-/**
- * should only be used if a resource is uniquely identifiable by
- * either three methods: id, name or path!
- * In any other case, use categorypolicies to retrieve policies of a
- * certain type
- *
- * @author hanl
- * @date 15/01/2014
- */
-
-// todo: add auditing mechanism to this!
-@SuppressWarnings("all")
-public class SecurityManager<T extends KustvaktResource> {
-
- private static final Logger jlog = LoggerFactory
- .getLogger(SecurityManager.class);
-
- private static PolicyHandlerIface policydao;
- @Deprecated
- private static Map<Class<? extends KustvaktResource>, ResourceOperationIface> handlers;
- private static EncryptionIface crypto;
-
- private List<SecurityPolicy>[] policies;
- private User user;
-
- private boolean silent;
- private PolicyEvaluator evaluator;
- private T resource;
-
-
- //todo: use simple user id if possible! --> or if not check that user has valid integer id (or use username as fallback instead)
- private SecurityManager (User user) {
- this.policies = new List[1];
- this.policies[0] = new ArrayList<>();
- this.silent = true;
- this.user = user;
- overrideProviders(BeansFactory.getKustvaktContext());
- }
-
-
- public static void overrideProviders (ContextHolder beans) {
- if (policydao == null | crypto == null) {
- SecurityManager.policydao = beans.getPolicyDbProvider();
- SecurityManager.crypto = beans.getEncryption();
- SecurityManager.handlers = new HashMap<>();
- Collection<ResourceOperationIface> providers = beans
- .getResourceProviders();
- for (ResourceOperationIface op : providers)
- SecurityManager.handlers.put(op.type(), op);
- }
- if (policydao == null && crypto == null)
- throw new RuntimeException("providers not set!");
- }
-
-
- @Deprecated
- public static final void setProviders (PolicyHandlerIface policyHandler,
- EncryptionIface crypto, Collection<ResourceOperationIface> ifaces) {
- SecurityManager.policydao = policyHandler;
- SecurityManager.crypto = crypto;
- SecurityManager.handlers = new HashMap<>();
- jlog.info("Registering handlers: {}", Arrays.asList(ifaces));
- // for (ResourceOperationIface iface : ifaces)
- // handlers.put(iface.getType(), iface);
- }
-
-
- /**
- * only allowed if the resource is uniquely identifiable by the
- * name, if not, use path or id!
- * Shortcut so resource values do not need to be retrieved
- * afterwards!
- *
- * @param name
- * @param user
- * @param type
- * @return
- * @throws EmptyResultException
- * @throws KustvaktException
- */
- //todo: implement a fall back that throws an exception when the user NULL, but the resource has restrictions!
- public static SecurityManager findbyId (String id, User user, Class type,
- Permissions.Permission ... perms) throws KustvaktException {
- SecurityManager p = new SecurityManager(user);
- p.findPolicies(id, false, perms);
- p.resource = p.findResource(type);
- return p;
- }
-
-
- public static SecurityManager findbyId (String id, User user,
- Permissions.Permission ... perms) throws KustvaktException {
- SecurityManager p = new SecurityManager(user);
- p.findPolicies(id, false, perms);
- p.resource = p.findResource(null);
- return p;
- }
-
-
- public static SecurityManager findbyId (Integer id, User user,
- Permissions.Permission ... perms) throws KustvaktException {
- SecurityManager p = new SecurityManager(user);
- p.findPolicies(id, false, perms);
- p.resource = p.findResource(null);
- return p;
- }
-
-
- public static SecurityManager findbyPath (String path, User user,
- Permissions.Permission ... perms) throws KustvaktException {
- SecurityManager manager = new SecurityManager(user);
- manager.findPolicies(path, true, perms);
- //fixme: need a match count. if match not unique, exception. also, does parent -child relation match hold up here?
- return manager;
- }
-
-
- public static SecurityManager init (String id, User user,
- Permissions.Permission ... perms) throws KustvaktException {
- SecurityManager p = new SecurityManager(user);
- p.findPolicies(id, false, perms);
- return p;
- }
-
-
- /**
- * enables retrieval for read access only!
- *
- * @return
- * @throws NotAuthorizedException
- */
- public final T getResource () throws NotAuthorizedException {
- if (evaluator.isAllowed(Permissions.Permission.READ)) {
- return this.resource;
- }
- else {
- jlog.error("Reading the resource '{}' is not allowed for user '{}'",
- this.resource.getPersistentID(), this.user.getUsername());
- throw new NotAuthorizedException(StatusCodes.NO_POLICY_PERMISSION,
- evaluator.getResourceID());
- }
- }
-
-
- public void updateResource (T resource)
- throws NotAuthorizedException, KustvaktException {
- if (evaluator.isAllowed(Permissions.Permission.WRITE)) {
- ResourceOperationIface iface = handlers.get(resource.getClass());
- if (iface != null)
- iface.updateResource(resource, this.user);
- else
- handlers.get(KustvaktResource.class).updateResource(resource,
- this.user);
- }
- else {
- jlog.error(
- "Updating the resource '{}' is not allowed for user '{}'",
- this.resource.getPersistentID(), this.user.getUsername());
- throw new NotAuthorizedException(StatusCodes.NO_POLICY_PERMISSION,
- this.evaluator.getResourceID());
- }
-
- }
-
-
- /**
- * @throws NotAuthorizedException
- * @throws KustvaktException
- */
- // todo: delete only works with find, not with init constructor!
- public void deleteResource ()
- throws NotAuthorizedException, KustvaktException {
- if (evaluator.isAllowed(Permissions.Permission.DELETE)) {
- ResourceOperationIface iface = handlers
- .get(this.resource.getClass());
- if (iface != null)
- iface.deleteResource(this.evaluator.getResourceID(), this.user);
- else
- handlers.get(KustvaktResource.class).deleteResource(
- this.evaluator.getResourceID(), this.user);
- this.policydao.deleteResourcePolicies(
- this.evaluator.getResourceID(), this.user);
- }
- else
- throw new NotAuthorizedException(StatusCodes.NO_POLICY_PERMISSION,
- this.evaluator.getResourceID());
- }
-
-
- // todo: type should be deprecated and return type of policies should be containers!
- private boolean findPolicies (Object id, boolean path,
- Permissions.Permission ... perms) throws KustvaktException {
- PermissionsBuffer b = new PermissionsBuffer();
- if (perms.length == 0)
- b.addPermission(Permissions.Permission.READ.toByte());
- else
- b.addPermissions(perms);
- if (id instanceof String && !path)
- this.policies = policydao.getPolicies((String) id, this.user,
- b.getPbyte());
- if (id instanceof String && path)
- this.policies = policydao.findPolicies((String) id, this.user,
- b.getPbyte());
- if (id instanceof Integer)
- this.policies = policydao.getPolicies((Integer) id, this.user,
- b.getPbyte());
-
- this.evaluator = new PolicyEvaluator(this.user, this.policies);
-
- if (this.policies == null) {
- jlog.error("No policies found for resource id '{}' for user '{}'",
- id, user.getId());
- throw new KustvaktException(StatusCodes.NO_RESULT_FOUND,
- "Resource not found!", String.valueOf(id));
- }
- return true;
- }
-
-
- // todo: security log shows id 'null' --> better way?
- private T findResource (Class type) throws KustvaktException {
- if (!evaluator.isAllowed()) {
- jlog.error("Permission denied for resource id '{}' for user '{}'",
- this.evaluator.getResourceID(), user.getId());
- throw new KustvaktException(StatusCodes.NO_POLICY_PERMISSION,
- "Permission denied for resource id "
- + this.evaluator.getResourceID() + " for the user.",
- user.getUsername());
- }
-
- ResourceOperationIface iface = handlers.get(type);
- if (iface == null)
- iface = handlers.get(KustvaktResource.class);
- T resource = (T) iface.findbyId(this.evaluator.getResourceID(),
- this.user);
-
- if(type != null && !resource.getClass().equals(type)) {
- throw new KustvaktException(StatusCodes.NO_RESULT_FOUND,
- "Resource with id " + this.evaluator.getResourceID()
- + " and type " + type.getSimpleName()
- + " is not found. Found resource with id "
- + this.evaluator.getResourceID() + " and type "
- + resource.getClass().getSimpleName() + ".");
- }
-
- // fixme: this
- // fixme: deprecated!
- resource.setManaged(this.evaluator.isManaged());
- resource.setShared(this.evaluator.isShared());
- return resource;
- }
-
-
- private boolean checkResource (String persistentID, User user)
- throws KustvaktException {
- ResourceOperationIface iface = handlers.get(KustvaktResource.class);
- return iface.findbyId(persistentID, user) != null;
- }
-
-
- public static SecurityManager register (KustvaktResource resource,
- User user) throws KustvaktException, NotAuthorizedException {
- SecurityManager p = new SecurityManager(user);
- if (!User.UserFactory.isDemo(user.getUsername())) {
- if (resource.getParentID() != null) {
- try {
- // the owner has all rights per default, in order to be able derivate from a parent resource, he needs all permissions as well
- // this is mostly for convenvience and database consistency, since a request query would result in not authorized, based on missing parent relation dependencies
- // --> in order not to have a resource owner that is denied access due to missing parent relation dependency
- SecurityManager.findbyId(resource.getParentID(), user,
- Permissions.Permission.ALL);
- }
- catch (EmptyResultException e) {
- jlog.error(
- "No policies found for parent '{}' for user '{}'",
- resource.getParentID(), user.getId());
- throw new KustvaktException(StatusCodes.NO_RESULT_FOUND);
- }
- }
- boolean newid = false;
- // create persistent identifier for the resource
- if (resource.getPersistentID() == null
- || resource.getPersistentID().isEmpty()) {
- ResourceFactory.createID(resource);
- newid = true;
- }
-
- if (newid | !p.checkResource(resource.getPersistentID(), user)) {
- // resource.setOwner(user.getId());
-
- jlog.info("Creating Access Control structure for resource '"
- + resource.getPersistentID() + "@" + resource.getId()
- + "', name: " + resource.getName());
- // storing resource is called twice. first when this is register and later in idsbootstrap to create cstorage entry. how to unify this?
- ResourceOperationIface iface = p.handlers
- .get(resource.getClass());
- if (iface != null)
- resource.setId(iface.storeResource(resource, user));
- else
- // retrieve default handler for resource!
- resource.setId(p.handlers.get(KustvaktResource.class)
- .storeResource(resource, user));
- }
- p.resource = resource;
- try {
- // todo: which is better? Integer id or String persistentID?
- p.findPolicies(resource.getPersistentID(), false,
- Permissions.Permission.CREATE_POLICY,
- Permissions.Permission.READ_POLICY,
- Permissions.Permission.MODIFY_POLICY);
- }
- catch (EmptyResultException e) {
- // todo: improve this!
- jlog.error(
- "No policies found for '{}' for user '{}'. Resource could not be registered!",
- resource.getPersistentID(), user.getId());
- throw new KustvaktException(user.getId(),
- StatusCodes.POLICY_ERROR_DEFAULT,
- "Resource could not be registered",
- resource.toString());
- }
- }
- return p;
- }
-
-
- @Deprecated
- public List<SecurityPolicy> getPoliciesList (int i) {
- if (i < this.policies.length)
- return this.policies[i];
- return Collections.emptyList();
- }
-
-
- // fixme: make protected
- public SecurityPolicy getPolicy (Integer id) {
- for (SecurityPolicy p : this.policies[0])
- if (p.getID() == id)
- return p;
- return null;
- }
-
-
- // fixme: make protected
- public PolicyCondition getExtensional (Permissions.Permission ... pps) {
- for (SecurityPolicy p : this.policies[0]) {
- if (p.equalsPermission(pps)) {
- for (PolicyCondition c : p.getConditions()) {
- if (c.isExtensional())
- return c;
- }
- }
- }
- return null;
- }
-
-
- private boolean matchTarget (String target) {
- return this.resource.getPersistentID() != null
- && (this.resource.getPersistentID() == target);
- }
-
-
- public void addPolicy (SecurityPolicy policy, Parameter ... params)
- throws KustvaktException, NotAuthorizedException {
- if (policy.getConditions().isEmpty()) {
- jlog.error("No conditions set for '{}' for user '{}'",
- policy.toString(), this.user.getId());
- throw new NotAuthorizedException(StatusCodes.ILLEGAL_ARGUMENT,
- policy.getTarget());
- }
-
- if (this.policies[0] == null) {
- jlog.error("No policies found for '{}' for user '{}'",
- this.evaluator.getResourceID(), this.user.getId());
- throw new NotAuthorizedException(StatusCodes.UNSUPPORTED_OPERATION,
- policy.getTarget());
- }
-
- if (contains(policy)) {
- modifyPolicy(policy);
- return;
- }
-
- if (evaluator.isAllowed(Permissions.Permission.CREATE_POLICY)) {
- policydao.createPolicy(policy, this.user);
- }
- else if (silent) {
- jlog.error(
- "Permission Denied (CREATE_POLICY) on '{}' for user '{}'",
- this.evaluator.getResourceID(), this.user.getId());
- throw new NotAuthorizedException(StatusCodes.NO_POLICY_PERMISSION,
- policy.getTarget());
- }
-
- if (params != null && params.length > 0) {
- for (Parameter p : params) {
- p.setPolicy(policy);
- policydao.createParamBinding(p);
- }
- }
- this.policies[0].add(policy);
- try {
- Thread.sleep(5);
- }
- catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
-
- public void deletePolicies ()
- throws NotAuthorizedException, KustvaktException {
- for (SecurityPolicy p : new ArrayList<>(this.policies[0]))
- deletePolicy(p);
- }
-
-
- public void retainPolicies (List<SecurityPolicy> policies)
- throws NotAuthorizedException, KustvaktException {
- for (SecurityPolicy p : new ArrayList<>(this.policies[0])) {
- if (!policies.contains(p))
- this.deletePolicy(p);
- }
- }
-
-
- // todo:
- public void deletePolicy (SecurityPolicy policy)
- throws KustvaktException, NotAuthorizedException {
- // todo: get rid of this: use sql to match policy id and target according to evaluator!
- if (!matchTarget(policy.getTarget()))
- // adjust message
- throw new NotAuthorizedException(StatusCodes.ILLEGAL_ARGUMENT,
- this.evaluator.getResourceID());
-
- if (this.policies[0] == null) {
- jlog.error("No policies found (DELETE_POLICY) on '{}' for '{}'",
- this.evaluator.getResourceID(), this.user.getId());
- throw new KustvaktException(user.getId(), StatusCodes.NO_POLICIES,
- this.evaluator.getResourceID());
- }
- if (contains(policy) && (evaluator
- .isAllowed(Permissions.Permission.DELETE_POLICY))) {
- policydao.deletePolicy(policy, this.user);
- }
- else if (silent) {
- jlog.error("Permission Denied (DELETE_POLICY) on '{}' for '{}'",
- this.evaluator.getResourceID(), this.user.getId());
- throw new NotAuthorizedException(StatusCodes.NO_POLICY_PERMISSION,
- "no policy desicion possible",
- this.evaluator.getResourceID());
- }
- policydao.removeParamBinding(policy);
-
- this.policies[0].remove(policy);
- }
-
-
- public void modifyPolicy (SecurityPolicy policy)
- throws KustvaktException, NotAuthorizedException {
- if (!matchTarget(policy.getTarget()))
- throw new NotAuthorizedException(StatusCodes.ILLEGAL_ARGUMENT);
-
- if (this.policies[0] == null) {
- jlog.error(
- "Operation not possible (MODIFY_POLICY) on '{}' for '{}'",
- this.evaluator.getResourceID(), this.user.getId());
- throw new KustvaktException(user.getId(), StatusCodes.NO_POLICIES,
- "no policy desicion possible",
- this.evaluator.getResourceID());
- }
-
- if (contains(policy) && (evaluator
- .isAllowed(Permissions.Permission.MODIFY_POLICY))) {
- policydao.updatePolicy(policy, this.user);
- }
- else if (silent) {
- jlog.error("Permission Denied (DELETE_POLICY) on '{}' for '{}'",
- this.evaluator.getResourceID(), this.user.getId());
- throw new NotAuthorizedException(StatusCodes.NO_POLICY_PERMISSION,
- this.evaluator.getResourceID());
- }
- this.policies = policydao.getPolicies((int) this.resource.getId(),
- this.user, null);
- }
-
-
- /**
- * standard function for READ access on the resource
- *
- * @return boolean is action allowed for resource
- */
- public boolean isAllowed () {
- return evaluator.isAllowed();
- }
-
-
- public boolean isAllowed (Permissions.Permission ... perm) {
- return evaluator.isAllowed();
- }
-
-
- /**
- * checks if that exact object already exists (compares name,
- * conditional parameter)
- *
- * @param policy
- * @return
- */
- public boolean contains (SecurityPolicy policy) {
- try {
- return policydao.checkPolicy(policy, this.user) == 1;
- }
- catch (KustvaktException e) {
- return false;
- }
- }
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManagerFactory.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManagerFactory.java
deleted file mode 100644
index b129373..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityManagerFactory.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-/**
- * @author hanl
- * @date 22/11/2015
- */
-public class SecurityManagerFactory {
-
- // make security manager and policydao transferable and exchangable
- // resource finder
- // resource handler
-
-
-
-}
diff --git a/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityRowMappers.java b/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityRowMappers.java
deleted file mode 100644
index 5c36e5c..0000000
--- a/core/src/main/java/de/ids_mannheim/korap/security/ac/SecurityRowMappers.java
+++ /dev/null
@@ -1,268 +0,0 @@
-package de.ids_mannheim.korap.security.ac;
-
-import de.ids_mannheim.korap.resources.KustvaktResource;
-import de.ids_mannheim.korap.resources.ResourceFactory;
-import de.ids_mannheim.korap.security.PolicyCondition;
-import de.ids_mannheim.korap.security.PolicyContext;
-import de.ids_mannheim.korap.security.SecurityPolicy;
-import de.ids_mannheim.korap.utils.PrefixTreeMap;
-import lombok.Data;
-import org.springframework.dao.DataAccessException;
-import org.springframework.jdbc.core.ResultSetExtractor;
-import org.springframework.jdbc.core.RowMapper;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.*;
-
-/**
- * @author hanl
- * @date 03/03/2014
- */
-public class SecurityRowMappers {
-
- public static class PolicyRowMapper implements RowMapper<SecurityPolicy> {
-
- @Override
- public SecurityPolicy mapRow (ResultSet rs, int rowNum)
- throws SQLException {
- String perms = rs.getString("perm");
- SecurityPolicy p = new SecurityPolicy();
- p.setID(rs.getInt("pid")).setTarget(rs.getString("persistent_id"))
- .setPOSIX(perms);
-
- PolicyContext context = new PolicyContext();
- context.setIPMask(rs.getString("iprange"));
- long enable = rs.getLong("enable");
- long expire = rs.getLong("expire");
- if (enable != -1)
- context.setEnableTime(enable);
- if (expire != -1)
- context.setExpirationTime(expire);
- // context.addFlag("export", rs.getBoolean("export"));
- // context.addFlag("sym_use", rs.getInt("sym_use"));
- p.setContext(context);
- return p;
- }
- }
-
- @Data
- public static class FlagContext extends PolicyContext {
-
- private Map<String, Object> flags;
-
-
- public FlagContext () {
- this.flags = new HashMap<>();
- }
-
-
- public FlagContext addFlag (String key, Object value) {
- this.flags.put(key, value);
- return this;
- }
-
-
- public FlagContext removeFlag (String key) {
- this.flags.remove(key);
- return this;
- }
-
-
- public FlagContext clearFlags () {
- this.flags.clear();
- return this;
- }
- }
-
-
- @SuppressWarnings(value = "all")
- public static List<SecurityPolicy>[] mapResourcePolicies (ResultSet rs)
- throws SQLException {
- List<SecurityPolicy>[] policyArray = null;
- List<Integer>[] idx = null;
- loop: while (rs.next()) {
- // user has no permission here, thus skip
- if (rs.getInt("allowed") == 0)
- continue loop;
-
- if (policyArray == null) {
- int v = rs.getInt("max_depth") + 1;
- policyArray = new List[v];
- idx = new List[v];
- }
-
- int depth = rs.getInt("depth");
- if (policyArray[depth] == null) {
- policyArray[depth] = new ArrayList<>();
- idx[depth] = new ArrayList<>();
- }
-
- Integer pid = rs.getInt("pid");
- String grouping = rs.getString("group_id");
- Integer index = idx[depth].indexOf(pid);
-
- SecurityPolicy policy;
- if (index == -1) {
- if (pid == -1 && grouping.equalsIgnoreCase("self")) {
- policy = new SecurityPolicy.OwnerPolicy(
- rs.getString("persistent_id"), rs.getInt("creator"));
- policyArray[depth].add(0, policy);
- idx[depth].add(0, pid);
- }
- else {
- policy = new SecurityRowMappers.PolicyRowMapper().mapRow(
- rs, 0);
- policyArray[depth].add(policy);
- idx[depth].add(pid);
-
- //todo:
- // if (policy.isActive(user)) {
- // policyArray[depth].add(policy);
- // idx[depth].add(pid);
- // }
- }
- }
- else
- policy = policyArray[depth].get(index);
-
- PolicyCondition c = new PolicyCondition(rs.getString("group_id"));
- if (!policy.contains(c))
- policy.addCondition(c);
- }
- return policyArray;
- }
-
-
- public static List<SecurityPolicy> mapConditionPolicies (ResultSet rs)
- throws SQLException {
- Map<Integer, SecurityPolicy> policyMap = new HashMap<>();
- while (rs.next()) {
- if (rs.getInt("allowed") == 0)
- continue;
-
- Integer pid = rs.getInt("pid");
- SecurityPolicy policy;
- if ((policy = policyMap.get(pid)) == null) {
- policy = new SecurityRowMappers.PolicyRowMapper().mapRow(rs, 0);
- policyMap.put(pid, policy);
- }
- PolicyCondition c = new PolicyCondition(rs.getString("group_id"));
-
- if (!policy.contains(c))
- policy.addNewCondition(c);
- }
- return new ArrayList<>(policyMap.values());
- }
-
-
- @Deprecated
- public static List<SecurityPolicy>[] map (ResultSet rs) throws SQLException {
- Map<Integer, SecurityPolicy>[] policyArray = null;
- while (rs.next()) {
- // user has no permission here!
- if (rs.getInt("allowed") == 0)
- continue;
-
- if (policyArray == null)
- policyArray = new Map[rs.getInt("max_depth") + 1];
-
- int depth = rs.getInt("depth");
- Map<Integer, SecurityPolicy> cursor = policyArray[depth];
- if (cursor == null)
- cursor = new HashMap<>();
-
- Integer pid = rs.getInt("pid");
- SecurityPolicy policy = cursor.get(pid);
- if (policy == null) {
- policy = new SecurityRowMappers.PolicyRowMapper().mapRow(rs, 0);
- cursor.put(pid, policy);
- }
- PolicyCondition c = new PolicyCondition(rs.getString("group_id"));
-
- if (!policy.contains(c))
- policy.addNewCondition(c);
- }
-
- List<SecurityPolicy>[] results;
- if (policyArray == null) {
- results = new List[1];
- results[0] = new ArrayList<>();
- }
- else {
- results = new List[policyArray.length];
- for (int idx = 0; idx < policyArray.length; idx++) {
- if (policyArray[idx] != null)
- results[idx] = new ArrayList<>(policyArray[idx].values());
- else
- results[idx] = new ArrayList<>();
- }
- }
- return results;
- }
-
- public static class HierarchicalResultExtractor implements
- ResultSetExtractor<List<KustvaktResource.Container>> {
-
- private boolean _withpid;
-
-
- // public HierarchicalResultExtractor(boolean wpid) {
- // this._withpid = wpid;
- // }
-
- // todo: in order for this to work, all parent flags need to be matched in sql!
- public List<KustvaktResource.Container> extractData (ResultSet rs)
- throws SQLException, DataAccessException {
- // contains the container with the highest available name_path to retrieve partial matches!
- PrefixTreeMap<KustvaktResource.Container[]> containerMap = new PrefixTreeMap<>();
- Map<Integer, SecurityPolicy> trace = new HashMap<>();
-
- while (rs.next()) {
- KustvaktResource.Container[] cursor;
- Integer pid = rs.getInt("pid");
-
- SecurityPolicy policy = trace.get(pid);
- if (policy == null | pid == -1) {
- // Integer id = rs.getInt("id");
- String persistentId = rs.getString("persistent_id");
- int depth = rs.getInt("depth");
- String namePath = rs.getString("name_path");
- policy = new SecurityRowMappers.PolicyRowMapper().mapRow(
- rs, 0);
-
- //todo: put active status here!
- trace.put(pid, policy);
-
- //fixme: since leaves are mentioned first, maybe retrieve
- SortedMap<String, KustvaktResource.Container[]> submatch;
- if ((submatch = containerMap.getPrefixSubMap(namePath)) == null) {
- //create container for last child node
- cursor = new KustvaktResource.Container[depth + 1];
- cursor[depth] = new KustvaktResource.Container(
- persistentId, ResourceFactory.getResource(
- rs.getInt("type")).getClass());
- containerMap.put(namePath, cursor);
- }
- else {
- KustvaktResource.Container[] values = submatch
- .get(submatch.firstKey());
- values[depth] = new KustvaktResource.Container(
- persistentId, ResourceFactory.getResource(
- rs.getInt("type")).getClass());
- }
- }
- }
-
- List<KustvaktResource.Container> result = new ArrayList<>();
- for (KustvaktResource.Container[] values : containerMap.values()) {
- for (KustvaktResource.Container container : values)
- if (container == null)
- containerMap.remove(values);
- result.add(values[values.length - 1]);
- }
- return result;
- }
- }
-
-}