You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ambari.apache.org by rl...@apache.org on 2015/11/24 00:57:55 UTC
[3/3] ambari git commit: AMBARI-13977. Enforce granular role-based
access control for user functions (rlevas)
AMBARI-13977. Enforce granular role-based access control for user functions (rlevas)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/7d45f1f7
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/7d45f1f7
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/7d45f1f7
Branch: refs/heads/trunk
Commit: 7d45f1f71f9b569d3d541ebb7cbd6b79bfd8fdb4
Parents: e158472
Author: Robert Levas <rl...@hortonworks.com>
Authored: Mon Nov 23 18:57:44 2015 -0500
Committer: Robert Levas <rl...@hortonworks.com>
Committed: Mon Nov 23 18:57:44 2015 -0500
----------------------------------------------------------------------
.../controller/AmbariManagementController.java | 5 +-
.../AmbariManagementControllerImpl.java | 96 +--
.../internal/AbstractResourceProvider.java | 5 +-
.../ActiveWidgetLayoutResourceProvider.java | 43 +-
.../AmbariPrivilegeResourceProvider.java | 8 +
.../ClusterPrivilegeResourceProvider.java | 29 +-
.../internal/PrivilegeResourceProvider.java | 10 +-
.../UserAuthorizationResourceProvider.java | 22 +-
.../internal/UserPrivilegeResourceProvider.java | 18 +
.../internal/UserResourceProvider.java | 14 +-
.../AmbariAuthorizationFilter.java | 46 +-
.../authorization/AuthorizationHelper.java | 33 +-
.../AmbariManagementControllerImplTest.java | 11 +
.../AmbariManagementControllerTest.java | 11 +
.../ActiveWidgetLayoutResourceProviderTest.java | 458 ++++++++-----
.../AmbariPrivilegeResourceProviderTest.java | 626 +++++++++++++-----
.../ClusterPrivilegeResourceProviderTest.java | 501 +++++++++++---
.../UserAuthorizationResourceProviderTest.java | 172 +++--
.../UserPrivilegeResourceProviderTest.java | 140 ++--
.../internal/UserResourceProviderTest.java | 646 +++++++++----------
.../ViewPrivilegeResourceProviderTest.java | 4 +
.../security/TestAuthenticationFactory.java | 164 +++++
.../AmbariAuthorizationFilterTest.java | 77 +--
23 files changed, 2157 insertions(+), 982 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementController.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementController.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementController.java
index ea7603f..b446121 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementController.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementController.java
@@ -32,6 +32,7 @@ import org.apache.ambari.server.controller.internal.RequestStageContainer;
import org.apache.ambari.server.controller.metrics.timeline.cache.TimelineMetricCacheProvider;
import org.apache.ambari.server.metadata.RoleCommandOrder;
import org.apache.ambari.server.scheduler.ExecutionScheduleManager;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.security.ldap.LdapBatchDto;
import org.apache.ambari.server.security.ldap.LdapSyncDto;
import org.apache.ambari.server.stageplanner.RoleGraphFactory;
@@ -182,7 +183,7 @@ public interface AmbariManagementController {
* @throws AmbariException if the users could not be read
*/
public Set<UserResponse> getUsers(Set<UserRequest> requests)
- throws AmbariException;
+ throws AmbariException, AuthorizationException;
/**
* Gets the user groups identified by the given request objects.
@@ -235,7 +236,7 @@ public interface AmbariManagementController {
*
* @throws AmbariException if the resources cannot be updated
*/
- public void updateUsers(Set<UserRequest> requests) throws AmbariException;
+ public void updateUsers(Set<UserRequest> requests) throws AmbariException, AuthorizationException;
/**
* Updates the groups specified.
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java
index 443c715..7cb7f7d 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariManagementControllerImpl.java
@@ -100,16 +100,15 @@ import org.apache.ambari.server.orm.dao.WidgetLayoutDAO;
import org.apache.ambari.server.orm.entities.ClusterEntity;
import org.apache.ambari.server.orm.entities.ClusterVersionEntity;
import org.apache.ambari.server.orm.entities.OperatingSystemEntity;
-import org.apache.ambari.server.orm.entities.PermissionEntity;
-import org.apache.ambari.server.orm.entities.PrivilegeEntity;
import org.apache.ambari.server.orm.entities.RepositoryEntity;
import org.apache.ambari.server.orm.entities.RepositoryVersionEntity;
import org.apache.ambari.server.orm.entities.WidgetEntity;
import org.apache.ambari.server.orm.entities.WidgetLayoutEntity;
import org.apache.ambari.server.orm.entities.WidgetLayoutUserWidgetEntity;
import org.apache.ambari.server.scheduler.ExecutionScheduleManager;
-import org.apache.ambari.server.security.SecurityHelper;
-import org.apache.ambari.server.security.authorization.AmbariGrantedAuthority;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
+import org.apache.ambari.server.security.authorization.ResourceType;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
import org.apache.ambari.server.security.authorization.AuthorizationHelper;
import org.apache.ambari.server.security.authorization.Group;
import org.apache.ambari.server.security.authorization.User;
@@ -170,7 +169,6 @@ import org.apache.commons.lang.math.NumberUtils;
import org.apache.http.client.utils.URIBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.springframework.security.core.GrantedAuthority;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
@@ -262,9 +260,6 @@ public class AmbariManagementControllerImpl implements AmbariManagementControlle
*/
private KerberosHelper kerberosHelper;
- @Inject
- private SecurityHelper securityHelper;
-
final private String masterHostname;
final private Integer masterPort;
final private String masterProtocol;
@@ -2780,22 +2775,30 @@ public class AmbariManagementControllerImpl implements AmbariManagementControlle
* the requested properties
*/
@Override
- public synchronized void updateUsers(Set<UserRequest> requests) throws AmbariException {
+ public synchronized void updateUsers(Set<UserRequest> requests) throws AmbariException, AuthorizationException {
+ boolean isUserAdministrator = AuthorizationHelper.isAuthorized(ResourceType.AMBARI, null,
+ RoleAuthorization.AMBARI_MANAGE_USERS);
+ String authenticatedUsername = AuthorizationHelper.getAuthenticatedName();
+
for (UserRequest request : requests) {
- User u = users.getAnyUser(request.getUsername());
- if (null == u) {
- continue;
+ String requestedUsername = request.getUsername();
+
+ // An administrator can modify any user, else a user can only modify themself.
+ if (!isUserAdministrator && (!authenticatedUsername.equalsIgnoreCase(requestedUsername))) {
+ throw new AuthorizationException();
}
- if (null != request.getOldPassword() && null != request.getPassword()) {
- users.modifyPassword(u.getUserName(), request.getOldPassword(),
- request.getPassword());
+ User u = users.getAnyUser(requestedUsername);
+ if (null == u) {
+ continue;
}
if (null != request.isActive()) {
// If this value is being set, make sure the authenticated user is an administrator before
// allowing to change it. Only administrators should be able to change a user's active state
- verifyAuthorization();
+ if (!isUserAdministrator) {
+ throw new AuthorizationException("The authenticated user is not authorized to update the requested resource property");
+ }
users.setUserActive(u.getUserName(), request.isActive());
}
@@ -2803,13 +2806,21 @@ public class AmbariManagementControllerImpl implements AmbariManagementControlle
// If this value is being set, make sure the authenticated user is an administrator before
// allowing to change it. Only administrators should be able to change a user's administrative
// privileges
- verifyAuthorization();
+ if (!isUserAdministrator) {
+ throw new AuthorizationException("The authenticated user is not authorized to update the requested resource property");
+ }
+
if (request.isAdmin()) {
users.grantAdminPrivilege(u.getUserId());
} else {
users.revokeAdminPrivilege(u.getUserId());
}
}
+
+ if (null != request.getOldPassword() && null != request.getPassword()) {
+ users.modifyPassword(u.getUserName(), request.getOldPassword(),
+ request.getPassword());
+ }
}
}
@@ -3162,7 +3173,7 @@ public class AmbariManagementControllerImpl implements AmbariManagementControlle
@Override
public Set<UserResponse> getUsers(Set<UserRequest> requests)
- throws AmbariException {
+ throws AmbariException, AuthorizationException {
Set<UserResponse> responses = new HashSet<UserResponse>();
@@ -3172,8 +3183,25 @@ public class AmbariManagementControllerImpl implements AmbariManagementControlle
LOG.debug("Received a getUsers request"
+ ", userRequest=" + r.toString());
}
+
+ String requestedUsername = r.getUsername();
+ String authenticatedUsername = AuthorizationHelper.getAuthenticatedName();
+
+ // A user resource may be retrieved by an administrator or the same user.
+ if(!AuthorizationHelper.isAuthorized(ResourceType.AMBARI, null, RoleAuthorization.AMBARI_MANAGE_USERS)) {
+ if (null == requestedUsername) {
+ // Since the authenticated user is not the administrator, force only that user's resource
+ // to be returned
+ requestedUsername = authenticatedUsername;
+ } else if (!requestedUsername.equalsIgnoreCase(authenticatedUsername)) {
+ // Since the authenticated user is not the administrator and is asking for a different user,
+ // throw an AuthorizationException
+ throw new AuthorizationException();
+ }
+ }
+
// get them all
- if (null == r.getUsername()) {
+ if (null == requestedUsername) {
for (User u : users.getAllUsers()) {
UserResponse resp = new UserResponse(u.getUserName(), u.getUserType(), u.isLdapUser(), u.isActive(), u
.isAdmin());
@@ -3182,13 +3210,13 @@ public class AmbariManagementControllerImpl implements AmbariManagementControlle
}
} else {
- User u = users.getAnyUser(r.getUsername());
+ User u = users.getAnyUser(requestedUsername);
if (null == u) {
if (requests.size() == 1) {
// only throw exceptin if there is a single request
// if there are multiple requests, this indicates an OR predicate
throw new ObjectNotFoundException("Cannot find user '"
- + r.getUsername() + "'");
+ + requestedUsername + "'");
}
} else {
UserResponse resp = new UserResponse(u.getUserName(), u.getUserType(), u.isLdapUser(), u.isActive(), u
@@ -4378,32 +4406,6 @@ public class AmbariManagementControllerImpl implements AmbariManagementControlle
}
}
- /**
- * Determine whether or not the authenticated user has administrator privileges
- *
- * @throws IllegalArgumentException if the authenticated user does not have administrator privileges.
- */
- protected void verifyAuthorization() throws AmbariException {
- boolean isAuthorized = false;
-
- for (GrantedAuthority grantedAuthority : securityHelper.getCurrentAuthorities()) {
- if (grantedAuthority instanceof AmbariGrantedAuthority) {
- AmbariGrantedAuthority authority = (AmbariGrantedAuthority) grantedAuthority;
- PrivilegeEntity privilegeEntity = authority.getPrivilegeEntity();
- Integer permissionId = privilegeEntity.getPermission().getId();
-
- if (permissionId.equals(PermissionEntity.AMBARI_ADMINISTRATOR_PERMISSION)) {
- isAuthorized = true;
- break;
- }
- }
- }
-
- if (!isAuthorized) {
- throw new IllegalArgumentException("You do not have authorization to update the requested resource property.");
- }
- }
-
@Override
public TimelineMetricCacheProvider getTimelineMetricCacheProvider() {
return injector.getInstance(TimelineMetricCacheProvider.class);
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractResourceProvider.java
index 3464c19..ac9935d 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractResourceProvider.java
@@ -38,6 +38,7 @@ import org.apache.ambari.server.controller.predicate.EqualsPredicate;
import org.apache.ambari.server.controller.spi.*;
import org.apache.ambari.server.controller.utilities.PredicateHelper;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.utils.RetryHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -441,7 +442,7 @@ public abstract class AbstractResourceProvider extends BaseProvider implements R
}
//invoke command with retry support in case of database fail
- private <T> T invokeWithRetry(Command<T> command) throws AmbariException {
+ private <T> T invokeWithRetry(Command<T> command) throws AmbariException, AuthorizationException {
RetryHelper.clearAffectedClusters();
int retryAttempts = RetryHelper.getOperationsRetryAttempts();
do {
@@ -485,6 +486,6 @@ public abstract class AbstractResourceProvider extends BaseProvider implements R
*
* @throws AmbariException thrown if a problem occurred during invocation
*/
- public T invoke() throws AmbariException;
+ public T invoke() throws AmbariException, AuthorizationException;
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProvider.java
index 52b0d56..10eecac 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProvider.java
@@ -21,7 +21,6 @@ import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.ObjectNotFoundException;
import org.apache.ambari.server.StaticallyInject;
import org.apache.ambari.server.controller.AmbariManagementController;
import org.apache.ambari.server.controller.WidgetResponse;
@@ -43,14 +42,14 @@ import org.apache.ambari.server.orm.entities.UserEntity;
import org.apache.ambari.server.orm.entities.WidgetEntity;
import org.apache.ambari.server.orm.entities.WidgetLayoutEntity;
import org.apache.ambari.server.orm.entities.WidgetLayoutUserWidgetEntity;
-import org.apache.commons.lang.ObjectUtils;
-import org.apache.commons.lang.StringUtils;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
+import org.apache.ambari.server.security.authorization.AuthorizationHelper;
+import org.apache.ambari.server.security.authorization.ResourceType;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -111,6 +110,16 @@ public class ActiveWidgetLayoutResourceProvider extends AbstractControllerResour
private static Gson gson;
/**
+ * For testing purposes
+ */
+ public static void init(UserDAO userDAO, WidgetDAO widgetDAO, WidgetLayoutDAO widgetLayoutDAO, Gson gson){
+ ActiveWidgetLayoutResourceProvider.userDAO = userDAO;
+ ActiveWidgetLayoutResourceProvider.widgetDAO = widgetDAO;
+ ActiveWidgetLayoutResourceProvider.widgetLayoutDAO = widgetLayoutDAO;
+ ActiveWidgetLayoutResourceProvider.gson = gson;
+ }
+
+ /**
* Create a new resource provider.
*
*/
@@ -137,9 +146,18 @@ public class ActiveWidgetLayoutResourceProvider extends AbstractControllerResour
List<WidgetLayoutEntity> layoutEntities = new ArrayList<WidgetLayoutEntity>();
+ boolean isUserAdministrator = AuthorizationHelper.isAuthorized(ResourceType.AMBARI, null,
+ RoleAuthorization.AMBARI_MANAGE_USERS);
+
for (Map<String, Object> propertyMap: propertyMaps) {
final String userName = propertyMap.get(WIDGETLAYOUT_USERNAME_PROPERTY_ID).toString();
- java.lang.reflect.Type type = new TypeToken<Set<Map<String, String>>>(){}.getType();
+
+ // Ensure that the authenticated user has authorization to get this information
+ if (!isUserAdministrator && !AuthorizationHelper.getAuthenticatedName().equalsIgnoreCase(userName)) {
+ throw new AuthorizationException();
+ }
+
+ java.lang.reflect.Type type = new TypeToken<Set<Map<String, String>>>(){}.getType();
Set<Map<String, String>> activeWidgetLayouts = gson.fromJson(userDAO.findUserByName(userName).getActiveWidgetLayouts(), type);
if (activeWidgetLayouts != null) {
for (Map<String, String> widgetLayoutId : activeWidgetLayouts) {
@@ -187,8 +205,17 @@ public class ActiveWidgetLayoutResourceProvider extends AbstractControllerResour
modifyResources(new Command<Void>() {
@Override
- public Void invoke() throws AmbariException {
+ public Void invoke() throws AmbariException, AuthorizationException {
+ boolean isUserAdministrator = AuthorizationHelper.isAuthorized(ResourceType.AMBARI, null,
+ RoleAuthorization.AMBARI_MANAGE_USERS);
+
for (Map<String, Object> propertyMap : propertyMaps) {
+ // Ensure that the authenticated user has authorization to get this information
+ String userName = propertyMap.get(WIDGETLAYOUT_USERNAME_PROPERTY_ID).toString();
+ if (!isUserAdministrator && !AuthorizationHelper.getAuthenticatedName().equalsIgnoreCase(userName)) {
+ throw new AuthorizationException();
+ }
+
Set<HashMap> widgetLayouts = (Set) propertyMap.get(WIDGETLAYOUT);
for (HashMap<String, String> widgetLayout : widgetLayouts) {
final Long layoutId;
@@ -202,7 +229,7 @@ public class ActiveWidgetLayoutResourceProvider extends AbstractControllerResour
throw new AmbariException("There is no widget layout with id " + layoutId);
}
}
- UserEntity user = userDAO.findUserByName(propertyMap.get(WIDGETLAYOUT_USERNAME_PROPERTY_ID).toString());
+ UserEntity user = userDAO.findUserByName(userName);
user.setActiveWidgetLayouts(gson.toJson(propertyMap.get(WIDGETLAYOUT)));
userDAO.merge(user);
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProvider.java
index 3670775..e5c95cb 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariPrivilegeResourceProvider.java
@@ -29,8 +29,10 @@ import org.apache.ambari.server.orm.entities.UserEntity;
import org.apache.ambari.server.orm.entities.ViewEntity;
import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
import org.apache.ambari.server.security.authorization.ResourceType;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
import org.apache.ambari.server.view.ViewRegistry;
+import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -88,6 +90,12 @@ public class AmbariPrivilegeResourceProvider extends PrivilegeResourceProvider<O
*/
public AmbariPrivilegeResourceProvider() {
super(propertyIds, keyPropertyIds, Resource.Type.AmbariPrivilege);
+
+ EnumSet<RoleAuthorization> requiredAuthorizations = EnumSet.of(RoleAuthorization.AMBARI_ASSIGN_ROLES);
+ setRequiredCreateAuthorizations(requiredAuthorizations);
+ setRequiredDeleteAuthorizations(requiredAuthorizations);
+ setRequiredGetAuthorizations(requiredAuthorizations);
+ setRequiredUpdateAuthorizations(requiredAuthorizations);
}
// ----- AmbariPrivilegeResourceProvider ---------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ClusterPrivilegeResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ClusterPrivilegeResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ClusterPrivilegeResourceProvider.java
index bbcd4a1..8f37764 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ClusterPrivilegeResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/ClusterPrivilegeResourceProvider.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -28,8 +28,10 @@ import org.apache.ambari.server.orm.entities.PermissionEntity;
import org.apache.ambari.server.orm.entities.PrivilegeEntity;
import org.apache.ambari.server.orm.entities.ResourceEntity;
import org.apache.ambari.server.orm.entities.UserEntity;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
import java.util.Collections;
+import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@@ -74,17 +76,6 @@ public class ClusterPrivilegeResourceProvider extends PrivilegeResourceProvider<
keyPropertyIds.put(Resource.Type.ClusterPrivilege, PRIVILEGE_ID_PROPERTY_ID);
}
- /**
- * The built-in VIEW.USER permission.
- */
- private final PermissionEntity clusterReadPermission;
-
- /**
- * The built-in VIEW.USER permission.
- */
- private final PermissionEntity clusterOperatePermission;
-
-
// ----- Constructors ------------------------------------------------------
/**
@@ -92,8 +83,12 @@ public class ClusterPrivilegeResourceProvider extends PrivilegeResourceProvider<
*/
public ClusterPrivilegeResourceProvider() {
super(propertyIds, keyPropertyIds, Resource.Type.ClusterPrivilege);
- clusterReadPermission = permissionDAO.findById(PermissionEntity.CLUSTER_USER_PERMISSION);
- clusterOperatePermission = permissionDAO.findById(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION);
+
+ EnumSet<RoleAuthorization> requiredAuthorizations = EnumSet.of(RoleAuthorization.AMBARI_ASSIGN_ROLES);
+ setRequiredCreateAuthorizations(requiredAuthorizations);
+ setRequiredDeleteAuthorizations(requiredAuthorizations);
+ setRequiredGetAuthorizations(requiredAuthorizations);
+ setRequiredUpdateAuthorizations(requiredAuthorizations);
}
@@ -105,7 +100,7 @@ public class ClusterPrivilegeResourceProvider extends PrivilegeResourceProvider<
* @param dao the cluster data access object
*/
public static void init(ClusterDAO dao) {
- clusterDAO = dao;
+ clusterDAO = dao;
}
@@ -165,9 +160,7 @@ public class ClusterPrivilegeResourceProvider extends PrivilegeResourceProvider<
@Override
protected PermissionEntity getPermission(String permissionName, ResourceEntity resourceEntity) throws AmbariException {
- return (permissionName.equals(PermissionEntity.CLUSTER_USER_PERMISSION_NAME)) ? clusterReadPermission :
- permissionName.equals(PermissionEntity.CLUSTER_ADMINISTRATOR_PERMISSION_NAME) ? clusterOperatePermission :
- super.getPermission(permissionName, resourceEntity);
+ return super.getPermission(permissionName, resourceEntity);
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PrivilegeResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PrivilegeResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PrivilegeResourceProvider.java
index 88e9906..4a44375 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PrivilegeResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/PrivilegeResourceProvider.java
@@ -55,7 +55,7 @@ import org.apache.ambari.server.orm.entities.UserEntity;
/**
* Abstract resource provider for privilege resources.
*/
-public abstract class PrivilegeResourceProvider<T> extends AbstractResourceProvider {
+public abstract class PrivilegeResourceProvider<T> extends AbstractAuthorizedResourceProvider {
/**
* Data access object used to obtain privilege entities.
@@ -160,7 +160,7 @@ public abstract class PrivilegeResourceProvider<T> extends AbstractResourceProvi
// ----- ResourceProvider --------------------------------------------------
@Override
- public RequestStatus createResources(Request request)
+ public RequestStatus createResourcesAuthorized(Request request)
throws SystemException, UnsupportedPropertyException,
ResourceAlreadyExistsException, NoSuchParentResourceException {
for (Map<String, Object> properties : request.getProperties()) {
@@ -172,7 +172,7 @@ public abstract class PrivilegeResourceProvider<T> extends AbstractResourceProvi
}
@Override
- public Set<Resource> getResources(Request request, Predicate predicate)
+ public Set<Resource> getResourcesAuthorized(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
Set<Resource> resources = new HashSet<Resource>();
Set<String> requestedIds = getRequestPropertyIds(request, predicate);
@@ -233,7 +233,7 @@ public abstract class PrivilegeResourceProvider<T> extends AbstractResourceProvi
}
@Override
- public RequestStatus updateResources(Request request, Predicate predicate)
+ public RequestStatus updateResourcesAuthorized(Request request, Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
modifyResources(getUpdateCommand(request, predicate));
notifyUpdate(resourceType, request, predicate);
@@ -241,7 +241,7 @@ public abstract class PrivilegeResourceProvider<T> extends AbstractResourceProvi
}
@Override
- public RequestStatus deleteResources(Predicate predicate)
+ public RequestStatus deleteResourcesAuthorized(Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
modifyResources(getDeleteCommand(predicate));
notifyDelete(resourceType, predicate);
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProvider.java
index 15aa0ec..ef3cd32 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserAuthorizationResourceProvider.java
@@ -39,8 +39,11 @@ import org.apache.ambari.server.orm.dao.ResourceTypeDAO;
import org.apache.ambari.server.orm.entities.PermissionEntity;
import org.apache.ambari.server.orm.entities.ResourceTypeEntity;
import org.apache.ambari.server.orm.entities.RoleAuthorizationEntity;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
+import org.apache.ambari.server.security.authorization.AuthorizationHelper;
+import org.apache.ambari.server.security.authorization.ResourceType;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
@@ -112,6 +115,14 @@ public class UserAuthorizationResourceProvider extends ReadOnlyResourceProvider
private final ClusterController clusterController;
/**
+ * For testing purposes
+ */
+ public static void init(PermissionDAO permissionDAO, ResourceTypeDAO resourceTypeDAO) {
+ UserAuthorizationResourceProvider.permissionDAO = permissionDAO;
+ UserAuthorizationResourceProvider.resourceTypeDAO = resourceTypeDAO;
+ }
+
+ /**
* Create a new resource provider.
*/
public UserAuthorizationResourceProvider(AmbariManagementController managementController) {
@@ -131,8 +142,17 @@ public class UserAuthorizationResourceProvider extends ReadOnlyResourceProvider
// is used to generate a composite set of authorizations the user has been granted.
ResourceProvider userPrivilegeProvider = clusterController.ensureResourceProvider(Type.UserPrivilege);
+ boolean isUserAdministrator = AuthorizationHelper.isAuthorized(ResourceType.AMBARI, null,
+ RoleAuthorization.AMBARI_MANAGE_USERS);
+
for (Map<String, Object> propertyMap : getPropertyMaps(predicate)) {
String username = (String) propertyMap.get(USERNAME_PROPERTY_ID);
+
+ // Ensure that the authenticated user has authorization to get this information
+ if (!isUserAdministrator && !AuthorizationHelper.getAuthenticatedName().equalsIgnoreCase(username)) {
+ throw new AuthorizationException();
+ }
+
Request internalRequest = createUserPrivilegeRequest();
Predicate internalPredicate = createUserPrivilegePredicate(username);
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserPrivilegeResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserPrivilegeResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserPrivilegeResourceProvider.java
index a8a9909..cef8a11 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserPrivilegeResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserPrivilegeResourceProvider.java
@@ -17,6 +17,7 @@
*/
package org.apache.ambari.server.controller.internal;
+import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -41,7 +42,10 @@ import org.apache.ambari.server.orm.entities.PrivilegeEntity;
import org.apache.ambari.server.orm.entities.UserEntity;
import org.apache.ambari.server.orm.entities.ViewEntity;
import org.apache.ambari.server.orm.entities.ViewInstanceEntity;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
+import org.apache.ambari.server.security.authorization.AuthorizationHelper;
import org.apache.ambari.server.security.authorization.ResourceType;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
import org.apache.ambari.server.security.authorization.UserType;
/**
@@ -137,6 +141,12 @@ public class UserPrivilegeResourceProvider extends ReadOnlyResourceProvider {
*/
public UserPrivilegeResourceProvider() {
super(propertyIds, keyPropertyIds, null);
+
+ EnumSet<RoleAuthorization> requiredAuthorizations = EnumSet.of(RoleAuthorization.AMBARI_ASSIGN_ROLES);
+ setRequiredCreateAuthorizations(requiredAuthorizations);
+ setRequiredDeleteAuthorizations(requiredAuthorizations);
+ setRequiredGetAuthorizations(requiredAuthorizations);
+ setRequiredUpdateAuthorizations(requiredAuthorizations);
}
// ----- PrivilegeResourceProvider -----------------------------------------
@@ -153,9 +163,17 @@ public class UserPrivilegeResourceProvider extends ReadOnlyResourceProvider {
final Set<Resource> resources = new HashSet<Resource>();
final Set<String> requestedIds = getRequestPropertyIds(request, predicate);
+ boolean isUserAdministrator = AuthorizationHelper.isAuthorized(ResourceType.AMBARI, null,
+ RoleAuthorization.AMBARI_MANAGE_USERS);
+
for (Map<String, Object> propertyMap : getPropertyMaps(predicate)) {
final String userName = (String) propertyMap.get(PRIVILEGE_USER_NAME_PROPERTY_ID);
+ // Ensure that the authenticated user has authorization to get this information
+ if (!isUserAdministrator && !AuthorizationHelper.getAuthenticatedName().equalsIgnoreCase(userName)) {
+ throw new AuthorizationException();
+ }
+
if (userName != null) {
UserEntity userEntity = userDAO.findLocalUserByName(userName);
if (userEntity == null) {
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserResourceProvider.java
index b993450..fee1826 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/UserResourceProvider.java
@@ -23,8 +23,11 @@ import org.apache.ambari.server.controller.UserRequest;
import org.apache.ambari.server.controller.UserResponse;
import org.apache.ambari.server.controller.spi.*;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
import java.util.Arrays;
+import java.util.EnumSet;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@@ -57,10 +60,13 @@ class UserResourceProvider extends AbstractControllerResourceProvider {
Map<Resource.Type, String> keyPropertyIds,
AmbariManagementController managementController) {
super(propertyIds, keyPropertyIds, managementController);
+
+ setRequiredCreateAuthorizations(EnumSet.of(RoleAuthorization.AMBARI_MANAGE_USERS));
+ setRequiredDeleteAuthorizations(EnumSet.of(RoleAuthorization.AMBARI_MANAGE_USERS));
}
@Override
- public RequestStatus createResources(Request request)
+ public RequestStatus createResourcesAuthorized(Request request)
throws SystemException,
UnsupportedPropertyException,
ResourceAlreadyExistsException,
@@ -97,7 +103,7 @@ class UserResourceProvider extends AbstractControllerResourceProvider {
Set<UserResponse> responses = getResources(new Command<Set<UserResponse>>() {
@Override
- public Set<UserResponse> invoke() throws AmbariException {
+ public Set<UserResponse> invoke() throws AmbariException, AuthorizationException {
return getManagementController().getUsers(requests);
}
});
@@ -151,7 +157,7 @@ class UserResourceProvider extends AbstractControllerResourceProvider {
modifyResources(new Command<Void>() {
@Override
- public Void invoke() throws AmbariException {
+ public Void invoke() throws AmbariException, AuthorizationException {
getManagementController().updateUsers(requests);
return null;
}
@@ -161,7 +167,7 @@ class UserResourceProvider extends AbstractControllerResourceProvider {
}
@Override
- public RequestStatus deleteResources(Predicate predicate)
+ public RequestStatus deleteResourcesAuthorized(Predicate predicate)
throws SystemException, UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
final Set<UserRequest> requests = new HashSet<UserRequest>();
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilter.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilter.java b/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilter.java
index 81794d8..7a2f7d2 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilter.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AmbariAuthorizationFilter.java
@@ -19,8 +19,6 @@
package org.apache.ambari.server.security.authorization;
import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -57,8 +55,8 @@ public class AmbariAuthorizationFilter implements Filter {
private static final String VIEWS_CONTEXT_PATH_PATTERN = VIEWS_CONTEXT_PATH_PREFIX + "([^/]+)/([^/]+)/([^/]+)(.*)";
private static final String VIEWS_CONTEXT_ALL_PATTERN = VIEWS_CONTEXT_PATH_PREFIX + ".*";
- private static final String API_USERS_USERNAME_PATTERN = API_VERSION_PREFIX + "/users/([^/?]+)(.*)";
private static final String API_USERS_ALL_PATTERN = API_VERSION_PREFIX + "/users.*";
+ private static final String API_PRIVILEGES_ALL_PATTERN = API_VERSION_PREFIX + "/privileges.*";
private static final String API_GROUPS_ALL_PATTERN = API_VERSION_PREFIX + "/groups.*";
private static final String API_CLUSTERS_ALL_PATTERN = API_VERSION_PREFIX + "/clusters.*";
private static final String API_VIEWS_ALL_PATTERN = API_VERSION_PREFIX + "/views.*";
@@ -106,7 +104,7 @@ public class AmbariAuthorizationFilter implements Filter {
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Authentication required");
}
}
- } else {
+ } else if(!authorizationPerformedInternally(requestURI)) {
boolean authorized = false;
for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
@@ -168,19 +166,11 @@ public class AmbariAuthorizationFilter implements Filter {
authorized = getViewRegistry().checkPermission(dto.getViewName(), dto.getVersion(), dto.getInstanceName(), true);
}
- // allow all types of requests for /users/{current_user}
- if (!authorized && requestURI.matches(API_USERS_USERNAME_PATTERN)) {
- final SecurityContext securityContext = getSecurityContext();
- final String currentUserName = securityContext.getAuthentication().getName();
- final String urlUserName = parseUserName(requestURI);
- authorized = currentUserName.equalsIgnoreCase(urlUserName);
- }
// allow GET for everything except /views, /api/v1/users, /api/v1/groups, /api/v1/ldap_sync_events
if (!authorized &&
(!httpRequest.getMethod().equals("GET")
|| requestURI.matches(VIEWS_CONTEXT_ALL_PATTERN)
- || requestURI.matches(API_USERS_ALL_PATTERN)
|| requestURI.matches(API_GROUPS_ALL_PATTERN)
|| requestURI.matches(API_CREDENTIALS_ALL_PATTERN)
|| requestURI.matches(API_LDAP_SYNC_EVENTS_ALL_PATTERN))) {
@@ -198,6 +188,18 @@ public class AmbariAuthorizationFilter implements Filter {
chain.doFilter(request, response);
}
+ /**
+ * Tests the URI to determine if authorization checks are performed internally or should be
+ * performed in the filter.
+ *
+ * @param requestURI the request uri
+ * @return true if handled internally; otherwise false
+ */
+ private boolean authorizationPerformedInternally(String requestURI) {
+ return requestURI.matches(API_USERS_ALL_PATTERN) ||
+ requestURI.matches(API_PRIVILEGES_ALL_PATTERN);
+ }
+
@Override
public void destroy() {
// do nothing
@@ -244,26 +246,6 @@ public class AmbariAuthorizationFilter implements Filter {
}
}
- /**
- * Parses url to get user name.
- *
- * @param url the url
- * @return null if url doesn't match correct pattern
- */
- static String parseUserName(String url) {
- final Pattern pattern = Pattern.compile(API_USERS_USERNAME_PATTERN);
- final Matcher matcher = pattern.matcher(url);
- if (!matcher.matches()) {
- return null;
- } else {
- try {
- return URLDecoder.decode(matcher.group(1), "UTF-8");
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException("Unable to decode URI: " + e, e);
- }
- }
- }
-
SecurityContext getSecurityContext() {
return SecurityContextHolder.getContext();
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java b/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java
index 198e209..e303066 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/AuthorizationHelper.java
@@ -77,7 +77,22 @@ public class AuthorizationHelper {
/**
* Determines if the authenticated user (from application's security context) is authorized to
- * perform an operation on the the specific resource by matching the authenticated user's
+ * perform an operation on the specific resource by matching the authenticated user's
+ * authorizations with the one indicated.
+ *
+ * @param resourceType a resource type being acted upon
+ * @param resourceId the resource id (relative to the resource type) being acted upon
+ * @param requiredAuthorization the required authorization
+ * @return true if authorized; otherwise false
+ * @see #isAuthorized(Authentication, ResourceType, Long, Set)
+ */
+ public static boolean isAuthorized(ResourceType resourceType, Long resourceId, RoleAuthorization requiredAuthorization) {
+ return isAuthorized(getAuthentication(), resourceType, resourceId, EnumSet.of(requiredAuthorization));
+ }
+
+ /**
+ * Determines if the authenticated user (from application's security context) is authorized to
+ * perform an operation on the specific resource by matching the authenticated user's
* authorizations with one from the provided set of authorizations.
*
* @param resourceType a resource type being acted upon
@@ -92,6 +107,22 @@ public class AuthorizationHelper {
/**
* Determines if the specified authenticated user is authorized to perform an operation on the
+ * specific resource by matching the authenticated user's authorizations with the one indicated.
+ *
+ * @param authentication the authenticated user and associated access privileges
+ * @param resourceType a resource type being acted upon
+ * @param resourceId the resource id (relative to the resource type) being acted upon
+ * @param requiredAuthorization the required authorization
+ * @return true if authorized; otherwise false
+ * @see #isAuthorized(Authentication, ResourceType, Long, Set)
+ */
+ public static boolean isAuthorized(Authentication authentication, ResourceType resourceType, Long resourceId,
+ RoleAuthorization requiredAuthorization) {
+ return isAuthorized(authentication, resourceType, resourceId, EnumSet.of(requiredAuthorization));
+ }
+
+ /**
+ * Determines if the specified authenticated user is authorized to perform an operation on the
* the specific resource by matching the authenticated user's authorizations with one from the
* provided set of authorizations.
* <p/>
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerImplTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerImplTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerImplTest.java
index 1d9e53d..ca3ca36 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerImplTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerImplTest.java
@@ -44,6 +44,7 @@ import org.apache.ambari.server.orm.entities.ClusterVersionEntity;
import org.apache.ambari.server.orm.entities.LdapSyncSpecEntity;
import org.apache.ambari.server.orm.entities.RepositoryVersionEntity;
import org.apache.ambari.server.security.authorization.Users;
+import org.apache.ambari.server.security.authorization.internal.InternalAuthenticationToken;
import org.apache.ambari.server.security.encryption.CredentialStoreService;
import org.apache.ambari.server.security.encryption.CredentialStoreType;
import org.apache.ambari.server.security.ldap.AmbariLdapDataPopulator;
@@ -64,7 +65,9 @@ import org.apache.ambari.server.state.StackId;
import org.apache.ambari.server.state.State;
import org.easymock.Capture;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Test;
+import org.springframework.security.core.context.SecurityContextHolder;
import javax.persistence.RollbackException;
import java.lang.reflect.Field;
@@ -103,6 +106,14 @@ public class AmbariManagementControllerImplTest {
private static final Users users = createMock(Users.class);
private static final AmbariSessionManager sessionManager = createNiceMock(AmbariSessionManager.class);
+ @BeforeClass
+ public static void setupAuthentication() {
+ // Set authenticated user so that authorization checks will pass
+ InternalAuthenticationToken authenticationToken = new InternalAuthenticationToken("admin");
+ authenticationToken.setAuthenticated(true);
+ SecurityContextHolder.getContext().setAuthentication(authenticationToken);
+ }
+
@Before
public void before() throws Exception {
reset(ldapDataPopulator, clusters, actionDBAccessor, ambariMetaInfo, users, sessionManager);
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerTest.java
index 385e3f7..3bf6cad 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/AmbariManagementControllerTest.java
@@ -105,6 +105,7 @@ import org.apache.ambari.server.orm.entities.WidgetEntity;
import org.apache.ambari.server.orm.entities.WidgetLayoutEntity;
import org.apache.ambari.server.orm.entities.WidgetLayoutUserWidgetEntity;
import org.apache.ambari.server.security.authorization.Users;
+import org.apache.ambari.server.security.authorization.internal.InternalAuthenticationToken;
import org.apache.ambari.server.serveraction.ServerAction;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
@@ -146,6 +147,7 @@ import org.easymock.Capture;
import org.easymock.EasyMock;
import org.junit.After;
import org.junit.Before;
+import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
@@ -161,6 +163,7 @@ import com.google.inject.Injector;
import com.google.inject.persist.PersistService;
import junit.framework.Assert;
+import org.springframework.security.core.context.SecurityContextHolder;
public class AmbariManagementControllerTest {
@@ -215,6 +218,14 @@ public class AmbariManagementControllerTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
+ @BeforeClass
+ public static void setupAuthentication() {
+ // Set authenticated user so that authorization checks will pass
+ InternalAuthenticationToken authenticationToken = new InternalAuthenticationToken("admin");
+ authenticationToken.setAuthenticated(true);
+ SecurityContextHolder.getContext().setAuthentication(authenticationToken);
+ }
+
@Before
public void setup() throws Exception {
InMemoryDefaultTestModule module = new InMemoryDefaultTestModule();
http://git-wip-us.apache.org/repos/asf/ambari/blob/7d45f1f7/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProviderTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProviderTest.java
index e74520e..9b47bf7 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProviderTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/ActiveWidgetLayoutResourceProviderTest.java
@@ -1,4 +1,4 @@
-/**
+/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@@ -17,243 +17,383 @@
*/
package org.apache.ambari.server.controller.internal;
-import com.google.inject.Binder;
+import com.google.gson.Gson;
+import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
-import com.google.inject.Module;
-import com.google.inject.util.Modules;
+import org.apache.ambari.server.actionmanager.ActionDBAccessor;
+import org.apache.ambari.server.actionmanager.ActionManager;
+import org.apache.ambari.server.actionmanager.StageFactory;
+import org.apache.ambari.server.api.services.AmbariMetaInfo;
+import org.apache.ambari.server.controller.AbstractRootServiceResponseFactory;
import org.apache.ambari.server.controller.AmbariManagementController;
+import org.apache.ambari.server.controller.AmbariManagementControllerImpl;
+import org.apache.ambari.server.controller.KerberosHelper;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.spi.ResourceProvider;
+import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.utilities.PredicateBuilder;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
-import org.apache.ambari.server.metadata.ActionMetadata;
-import org.apache.ambari.server.orm.InMemoryDefaultTestModule;
+import org.apache.ambari.server.orm.DBAccessor;
import org.apache.ambari.server.orm.dao.UserDAO;
+import org.apache.ambari.server.orm.dao.WidgetDAO;
import org.apache.ambari.server.orm.dao.WidgetLayoutDAO;
import org.apache.ambari.server.orm.entities.UserEntity;
import org.apache.ambari.server.orm.entities.WidgetLayoutEntity;
import org.apache.ambari.server.orm.entities.WidgetLayoutUserWidgetEntity;
+import org.apache.ambari.server.scheduler.ExecutionScheduler;
+import org.apache.ambari.server.security.TestAuthenticationFactory;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
+import org.apache.ambari.server.security.authorization.UserType;
+import org.apache.ambari.server.security.authorization.Users;
+import org.apache.ambari.server.security.encryption.CredentialStoreService;
+import org.apache.ambari.server.security.encryption.CredentialStoreServiceImpl;
+import org.apache.ambari.server.stack.StackManagerFactory;
+import org.apache.ambari.server.stageplanner.RoleGraphFactory;
+import org.apache.ambari.server.stageplanner.RoleGraphFactoryImpl;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
-import org.easymock.EasyMock;
+import org.apache.ambari.server.state.ConfigFactory;
+import org.apache.ambari.server.state.ServiceComponentFactory;
+import org.apache.ambari.server.state.ServiceComponentHostFactory;
+import org.apache.ambari.server.state.ServiceFactory;
+import org.apache.ambari.server.state.configgroup.ConfigGroupFactory;
+import org.apache.ambari.server.state.scheduler.RequestExecutionFactory;
+import org.apache.ambari.server.state.stack.OsFamily;
+import org.easymock.Capture;
+import org.easymock.EasyMockSupport;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.crypto.password.PasswordEncoder;
-import java.util.ArrayList;
+import javax.persistence.EntityManager;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
-import static org.easymock.EasyMock.anyLong;
-import static org.easymock.EasyMock.anyObject;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.replay;
-import static org.easymock.EasyMock.verify;
-import static org.junit.Assert.assertEquals;
+import static org.easymock.EasyMock.expectLastCall;
+import static org.easymock.EasyMock.newCapture;
/**
* ActiveWidgetLayout tests
*/
-public class ActiveWidgetLayoutResourceProviderTest {
-
- private WidgetLayoutDAO widgetLayoutDAO = null;
- private UserDAO userDAO = null;
- private Injector m_injector;
+public class ActiveWidgetLayoutResourceProviderTest extends EasyMockSupport {
@Before
public void before() {
- widgetLayoutDAO = createStrictMock(WidgetLayoutDAO.class);
- userDAO = createStrictMock(UserDAO.class);
+ resetAll();
+ }
- m_injector = Guice.createInjector(Modules.override(
- new InMemoryDefaultTestModule()).with(new MockModule()));
+
+ @Test
+ public void testGetResources_Administrator() throws Exception {
+ getResourcesTest(TestAuthenticationFactory.createAdministrator("admin"), "User1");
}
- /**
- * @throws Exception
- */
@Test
- public void testGetSingleResource() throws Exception {
- Request request = PropertyHelper.getReadRequest(
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_CLUSTER_NAME_PROPERTY_ID,
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_ID_PROPERTY_ID,
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_DISPLAY_NAME_PROPERTY_ID,
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_LAYOUT_NAME_PROPERTY_ID,
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_SECTION_NAME_PROPERTY_ID,
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID,
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_SCOPE_PROPERTY_ID,
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_WIDGETS_PROPERTY_ID);
-
- AmbariManagementController amc = createMock(AmbariManagementController.class);
- Clusters clusters = createMock(Clusters.class);
- Cluster cluster = createMock(Cluster.class);
- UserEntity userEntity = createMock(UserEntity.class);
- expect(amc.getClusters()).andReturn(clusters).atLeastOnce();
- expect(clusters.getClusterById(1L)).andReturn(cluster).atLeastOnce();
- expect(cluster.getClusterName()).andReturn("c1").anyTimes();
+ public void testGetResources_NonAdministrator_Self() throws Exception {
+ getResourcesTest(TestAuthenticationFactory.createClusterAdministrator("User1"), "User1");
+ }
- Predicate predicate = new PredicateBuilder().property(
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID).equals("username").toPredicate();
+ @Test(expected = AuthorizationException.class)
+ public void testGetResources_NonAdministrator_Other() throws Exception {
+ getResourcesTest(TestAuthenticationFactory.createClusterAdministrator("User1"), "User10");
+ }
+ @Test(expected = SystemException.class)
+ public void testCreateResources_Administrator() throws Exception {
+ createResourcesTest(TestAuthenticationFactory.createAdministrator("admin"), "User1");
+ }
- expect(userDAO.findUserByName("username")).andReturn(userEntity);
- expect(userEntity.getActiveWidgetLayouts()).andReturn("[{\"id\":\"1\"},{\"id\":\"2\"}]");
- expect(widgetLayoutDAO.findById(1L)).andReturn(getMockEntities().get(0));
- expect(widgetLayoutDAO.findById(2L)).andReturn(getMockEntities().get(1));
+ @Test(expected = SystemException.class)
+ public void testCreateResources_NonAdministrator_Self() throws Exception {
+ createResourcesTest(TestAuthenticationFactory.createClusterAdministrator("User1"), "User1");
+ }
- replay(amc, clusters, cluster, widgetLayoutDAO, userEntity, userDAO);
+ @Test(expected = SystemException.class)
+ public void testCreateResources_NonAdministrator_Other() throws Exception {
+ createResourcesTest(TestAuthenticationFactory.createClusterAdministrator("User1"), "User10");
+ }
- ActiveWidgetLayoutResourceProvider provider = createProvider(amc);
- Set<Resource> results = provider.getResources(request, predicate);
+ @Test
+ public void testUpdateResources_Administrator() throws Exception {
+ updateResourcesTest(TestAuthenticationFactory.createAdministrator("admin"), "User1");
+ }
- assertEquals(2, results.size());
+ @Test
+ public void testUpdateResources_NonAdministrator_Self() throws Exception {
+ updateResourcesTest(TestAuthenticationFactory.createClusterAdministrator("User1"), "User1");
+ }
- Resource r = results.iterator().next();
- Assert.assertEquals("section0", r.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_SECTION_NAME_PROPERTY_ID));
- Assert.assertEquals("CLUSTER", r.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_SCOPE_PROPERTY_ID));
- Assert.assertEquals("username", r.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID));
- Assert.assertEquals("displ_name", r.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_DISPLAY_NAME_PROPERTY_ID));
- Assert.assertEquals("layout name0", r.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_LAYOUT_NAME_PROPERTY_ID));
+ @Test(expected = AuthorizationException.class)
+ public void testUpdateResources_NonAdministrator_Other() throws Exception {
+ updateResourcesTest(TestAuthenticationFactory.createClusterAdministrator("User1"), "User10");
+ }
- Assert.assertEquals("[]", r.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_WIDGETS_PROPERTY_ID).toString());
+ @Test(expected = SystemException.class)
+ public void testDeleteResources_Administrator() throws Exception {
+ deleteResourcesTest(TestAuthenticationFactory.createAdministrator("admin"), "User1");
+ }
- verify(amc, clusters, cluster, widgetLayoutDAO, userEntity, userDAO);
+ @Test(expected = SystemException.class)
+ public void testDeleteResources_NonAdministrator_Self() throws Exception {
+ deleteResourcesTest(TestAuthenticationFactory.createClusterAdministrator("User1"), "User1");
}
+ @Test(expected = SystemException.class)
+ public void testDeleteResources_NonAdministrator_Other() throws Exception {
+ deleteResourcesTest(TestAuthenticationFactory.createClusterAdministrator("User1"), "User10");
+ }
- /**
- * @throws Exception
- */
- @Test
- public void testCreateResources() throws Exception {
- AmbariManagementController amc = createMock(AmbariManagementController.class);
+ private void getResourcesTest(Authentication authentication, String requestedUsername) throws Exception {
+ Injector injector = createInjector();
- replay(amc);
+ UserEntity userEntity = createMockUserEntity(requestedUsername);
- ActiveWidgetLayoutResourceProvider provider = createProvider(amc);
+ UserDAO userDAO = injector.getInstance(UserDAO.class);
+ expect(userDAO.findUserByName(requestedUsername)).andReturn(userEntity).atLeastOnce();
- Map<String, Object> requestProps = new HashMap<String, Object>();
+ WidgetLayoutDAO widgetLayoutDAO = injector.getInstance(WidgetLayoutDAO.class);
+ expect(widgetLayoutDAO.findById(1L)).andReturn(createMockWidgetLayout(1L, requestedUsername)).atLeastOnce();
+ expect(widgetLayoutDAO.findById(2L)).andReturn(createMockWidgetLayout(2L, requestedUsername)).atLeastOnce();
- Request request = PropertyHelper.getCreateRequest(Collections.singleton(requestProps), null);
- try {
- provider.createResources(request);
- } catch (Exception e) {
- //Expected exception
+ Cluster cluster = createNiceMock(Cluster.class);
+ expect(cluster.getClusterName()).andReturn("c1").atLeastOnce();
+
+ Clusters clusters = injector.getInstance(Clusters.class);
+ expect(clusters.getClusterById(2L)).andReturn(cluster).atLeastOnce();
+
+ replayAll();
+
+ AmbariMetaInfo ambariMetaInfo = injector.getInstance(AmbariMetaInfo.class);
+ ambariMetaInfo.init();
+
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+
+ AmbariManagementController managementController = injector.getInstance(AmbariManagementController.class);
+
+ ResourceProvider provider = getResourceProvider(injector, managementController);
+
+ Set<String> propertyIds = PropertyHelper.getPropertyIds(Resource.Type.ActiveWidgetLayout);
+
+ Request request = PropertyHelper.getReadRequest(propertyIds);
+
+ Set<Resource> resources = provider.getResources(request, createPredicate(requestedUsername));
+
+ Assert.assertEquals(2, resources.size());
+ for (Resource resource : resources) {
+
+ Long id = (Long) resource.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_ID_PROPERTY_ID);
+
+ Assert.assertEquals("section" + id, resource.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_SECTION_NAME_PROPERTY_ID));
+ Assert.assertEquals("CLUSTER", resource.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_SCOPE_PROPERTY_ID));
+ Assert.assertEquals(requestedUsername, resource.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID));
+ Assert.assertEquals("display name" + id, resource.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_DISPLAY_NAME_PROPERTY_ID));
+ Assert.assertEquals("layout name" + id, resource.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_LAYOUT_NAME_PROPERTY_ID));
+
+ Assert.assertEquals("[]", resource.getPropertyValue(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_WIDGETS_PROPERTY_ID).toString());
}
+ verifyAll();
}
- /**
- * @throws Exception
- */
- @Test
- public void testUpdateResources() throws Exception {
- AmbariManagementController amc = createMock(AmbariManagementController.class);
+ private void createResourcesTest(Authentication authentication, String requestedUsername) throws Exception {
+ Injector injector = createInjector();
+
+ replayAll();
+
+ AmbariMetaInfo ambariMetaInfo = injector.getInstance(AmbariMetaInfo.class);
+ ambariMetaInfo.init();
+
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+
+ AmbariManagementController managementController = injector.getInstance(AmbariManagementController.class);
+
+ ResourceProvider provider = getResourceProvider(injector, managementController);
- expect(widgetLayoutDAO.findById(anyLong())).andReturn(getMockEntities().get(0)).anyTimes();
- UserEntity userEntity = new UserEntity();
- expect(userDAO.findUserByName("username")).andReturn(userEntity);
- expect(userDAO.merge((UserEntity) anyObject())).andReturn(userEntity).anyTimes();
+ // add the property map to a set for the request. add more maps for multiple creates
+ Set<Map<String, Object>> propertySet = new LinkedHashSet<Map<String, Object>>();
- replay(amc, widgetLayoutDAO, userDAO);
+ Map<String, Object> properties = new LinkedHashMap<String, Object>();
+
+ // add properties to the request map
+ properties.put(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID, requestedUsername);
+
+ propertySet.add(properties);
+
+ // create the request
+ Request request = PropertyHelper.getCreateRequest(propertySet, null);
+
+ provider.createResources(request);
+
+ verifyAll();
+ }
+
+ private void updateResourcesTest(Authentication authentication, String requestedUsername) throws Exception {
+ Injector injector = createInjector();
+
+ Capture<? extends String> widgetLayoutJsonCapture = newCapture();
+
+ UserEntity userEntity = createMockUserEntity(requestedUsername);
+ userEntity.setActiveWidgetLayouts(capture(widgetLayoutJsonCapture));
+ expectLastCall().once();
+
+ UserDAO userDAO = injector.getInstance(UserDAO.class);
+ expect(userDAO.findUserByName(requestedUsername)).andReturn(userEntity).atLeastOnce();
+ expect(userDAO.merge(userEntity)).andReturn(userEntity).atLeastOnce();
+
+ WidgetLayoutDAO widgetLayoutDAO = injector.getInstance(WidgetLayoutDAO.class);
+ expect(widgetLayoutDAO.findById(1L)).andReturn(createMockWidgetLayout(1L, requestedUsername)).atLeastOnce();
+ expect(widgetLayoutDAO.findById(2L)).andReturn(createMockWidgetLayout(2L, requestedUsername)).atLeastOnce();
+
+ replayAll();
+
+ AmbariMetaInfo ambariMetaInfo = injector.getInstance(AmbariMetaInfo.class);
+ ambariMetaInfo.init();
+
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+
+ AmbariManagementController managementController = injector.getInstance(AmbariManagementController.class);
- Predicate predicate = new PredicateBuilder().property(
- ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID).equals("username").toPredicate();
Set<Map<String, String>> widgetLayouts = new HashSet<Map<String, String>>();
- HashMap<String, String> layout = new HashMap<String, String>();
- layout.put("id","1");
+ HashMap<String, String> layout;
+
+ layout = new HashMap<String, String>();
+ layout.put("id", "1");
widgetLayouts.add(layout);
- layout.put("id","2");
+
+ layout = new HashMap<String, String>();
+ layout.put("id", "2");
widgetLayouts.add(layout);
+
HashMap<String, Object> requestProps = new HashMap<String, Object>();
requestProps.put(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT, widgetLayouts);
- requestProps.put(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID, "username");
+ requestProps.put(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID, requestedUsername);
Request request = PropertyHelper.getUpdateRequest(requestProps, null);
- ActiveWidgetLayoutResourceProvider provider = createProvider(amc);
- provider.updateResources(request, predicate);
+ ResourceProvider provider = getResourceProvider(injector, managementController);
+
+ provider.updateResources(request, createPredicate(requestedUsername));
- Assert.assertTrue(userEntity.getActiveWidgetLayouts().equals("[{\"id\":\"2\"},{\"id\":\"2\"}]"));
- verify(amc, widgetLayoutDAO, userDAO);
+ verifyAll();
+
+ String json = widgetLayoutJsonCapture.getValue();
+ Assert.assertNotNull(json);
+
+ Set capturedWidgetLayouts = new Gson().fromJson(json, widgetLayouts.getClass());
+ Assert.assertEquals(widgetLayouts, capturedWidgetLayouts);
}
- /**
- * @throws Exception
- */
- @Test
- public void testDeleteResources() throws Exception {
- AmbariManagementController amc = createMock(AmbariManagementController.class);
+ private void deleteResourcesTest(Authentication authentication, String requestedUsername) throws Exception {
+ Injector injector = createInjector();
- replay(amc);
+ UserEntity userEntity = createMockUserEntity(requestedUsername);
- ActiveWidgetLayoutResourceProvider provider = createProvider(amc);
+ UserDAO userDAO = injector.getInstance(UserDAO.class);
+ expect(userDAO.findUserByName(requestedUsername)).andReturn(userEntity).atLeastOnce();
- Map<String, Object> requestProps = new HashMap<String, Object>();
- Predicate predicate = new PredicateBuilder().property(
- WidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID).equals("username").toPredicate();
- try {
- provider.deleteResources(predicate);
- } catch (Exception e) {
- //Expected exception
- }
+ replayAll();
+
+ AmbariMetaInfo ambariMetaInfo = injector.getInstance(AmbariMetaInfo.class);
+ ambariMetaInfo.init();
+
+ SecurityContextHolder.getContext().setAuthentication(authentication);
+
+ AmbariManagementController managementController = injector.getInstance(AmbariManagementController.class);
+
+ ResourceProvider provider = getResourceProvider(injector, managementController);
+
+ provider.deleteResources(createPredicate(requestedUsername));
+
+ verifyAll();
}
- /**
- * @param amc
- * @return
- */
- private ActiveWidgetLayoutResourceProvider createProvider(AmbariManagementController amc) {
- return new ActiveWidgetLayoutResourceProvider(amc);
+ private ResourceProvider getResourceProvider(Injector injector, AmbariManagementController managementController) throws Exception {
+ ActiveWidgetLayoutResourceProvider.init(injector.getInstance(UserDAO.class),
+ injector.getInstance(WidgetDAO.class),
+ injector.getInstance(WidgetLayoutDAO.class),
+ new Gson());
+
+ return AbstractControllerResourceProvider.getResourceProvider(
+ Resource.Type.ActiveWidgetLayout,
+ PropertyHelper.getPropertyIds(Resource.Type.ActiveWidgetLayout),
+ PropertyHelper.getKeyPropertyIds(Resource.Type.ActiveWidgetLayout),
+ managementController);
}
- /**
- * @return
- */
- private List<WidgetLayoutEntity> getMockEntities() throws Exception {
- List<WidgetLayoutEntity> widgetLayoutEntities = new ArrayList<WidgetLayoutEntity>();
- for (int i=1; i<3; i++) {
- WidgetLayoutEntity widgetLayoutEntity = new WidgetLayoutEntity();
- widgetLayoutEntity.setId((long) i);
- widgetLayoutEntity.setClusterId(Long.valueOf(1L));
- widgetLayoutEntity.setLayoutName("layout name0");
- widgetLayoutEntity.setSectionName("section0");
- widgetLayoutEntity.setUserName("username");
- widgetLayoutEntity.setScope("CLUSTER");
- widgetLayoutEntity.setDisplayName("displ_name");
- List<WidgetLayoutUserWidgetEntity> layoutUserWidgetEntityList = new LinkedList<WidgetLayoutUserWidgetEntity>();
- widgetLayoutEntity.setListWidgetLayoutUserWidgetEntity(layoutUserWidgetEntityList);
-
- widgetLayoutEntities.add(widgetLayoutEntity);
- }
- return widgetLayoutEntities;
+ private Predicate createPredicate(String requestedUsername) {
+ return new PredicateBuilder()
+ .property(ActiveWidgetLayoutResourceProvider.WIDGETLAYOUT_USERNAME_PROPERTY_ID)
+ .equals(requestedUsername)
+ .toPredicate();
}
- /**
- *
- */
- private class MockModule implements Module {
- /**
- *
- */
- @Override
- public void configure(Binder binder) {
- binder.bind(WidgetLayoutDAO.class).toInstance(widgetLayoutDAO);
- binder.bind(UserDAO.class).toInstance(userDAO);
- binder.bind(Clusters.class).toInstance(
- EasyMock.createNiceMock(Clusters.class));
- binder.bind(Cluster.class).toInstance(
- EasyMock.createNiceMock(Cluster.class));
- binder.bind(ActionMetadata.class);
- }
+ private WidgetLayoutEntity createMockWidgetLayout(Long id, String username) {
+ WidgetLayoutEntity widgetLayoutEntity = createMock(WidgetLayoutEntity.class);
+ expect(widgetLayoutEntity.getId()).andReturn(id).anyTimes();
+ expect(widgetLayoutEntity.getUserName()).andReturn(username).anyTimes();
+ expect(widgetLayoutEntity.getLayoutName()).andReturn("layout name" + id).anyTimes();
+ expect(widgetLayoutEntity.getSectionName()).andReturn("section" + id).anyTimes();
+ expect(widgetLayoutEntity.getScope()).andReturn("CLUSTER").anyTimes();
+ expect(widgetLayoutEntity.getDisplayName()).andReturn("display name" + id).anyTimes();
+ expect(widgetLayoutEntity.getClusterId()).andReturn(2L).anyTimes();
+ expect(widgetLayoutEntity.getListWidgetLayoutUserWidgetEntity()).andReturn(Collections.<WidgetLayoutUserWidgetEntity>emptyList()).anyTimes();
+ return widgetLayoutEntity;
+ }
+
+ private UserEntity createMockUserEntity(String username) {
+ UserEntity userEntity = createMock(UserEntity.class);
+ expect(userEntity.getUserId()).andReturn(username.hashCode()).anyTimes();
+ expect(userEntity.getUserName()).andReturn(username).anyTimes();
+ expect(userEntity.getUserType()).andReturn(UserType.LOCAL).anyTimes();
+ expect(userEntity.getActiveWidgetLayouts()).andReturn("[{\"id\":\"1\"},{\"id\":\"2\"}]").anyTimes();
+
+ return userEntity;
+ }
+
+ private Injector createInjector() throws Exception {
+ return Guice.createInjector(new AbstractModule() {
+ @Override
+ protected void configure() {
+ bind(EntityManager.class).toInstance(createNiceMock(EntityManager.class));
+ bind(DBAccessor.class).toInstance(createNiceMock(DBAccessor.class));
+ bind(ActionDBAccessor.class).toInstance(createNiceMock(ActionDBAccessor.class));
+ bind(ExecutionScheduler.class).toInstance(createNiceMock(ExecutionScheduler.class));
+ bind(OsFamily.class).toInstance(createNiceMock(OsFamily.class));
+ bind(AmbariMetaInfo.class).toInstance(createMock(AmbariMetaInfo.class));
+ bind(ActionManager.class).toInstance(createNiceMock(ActionManager.class));
+ bind(org.apache.ambari.server.actionmanager.RequestFactory.class).toInstance(createNiceMock(org.apache.ambari.server.actionmanager.RequestFactory.class));
+ bind(RequestExecutionFactory.class).toInstance(createNiceMock(RequestExecutionFactory.class));
+ bind(StageFactory.class).toInstance(createNiceMock(StageFactory.class));
+ bind(RoleGraphFactory.class).to(RoleGraphFactoryImpl.class);
+ bind(Clusters.class).toInstance(createNiceMock(Clusters.class));
+ bind(AbstractRootServiceResponseFactory.class).toInstance(createNiceMock(AbstractRootServiceResponseFactory.class));
+ bind(StackManagerFactory.class).toInstance(createNiceMock(StackManagerFactory.class));
+ bind(ConfigFactory.class).toInstance(createNiceMock(ConfigFactory.class));
+ bind(ConfigGroupFactory.class).toInstance(createNiceMock(ConfigGroupFactory.class));
+ bind(ServiceFactory.class).toInstance(createNiceMock(ServiceFactory.class));
+ bind(ServiceComponentFactory.class).toInstance(createNiceMock(ServiceComponentFactory.class));
+ bind(ServiceComponentHostFactory.class).toInstance(createNiceMock(ServiceComponentHostFactory.class));
+ bind(PasswordEncoder.class).toInstance(createNiceMock(PasswordEncoder.class));
+ bind(KerberosHelper.class).toInstance(createNiceMock(KerberosHelper.class));
+ bind(Users.class).toInstance(createMock(Users.class));
+ bind(AmbariManagementController.class).to(AmbariManagementControllerImpl.class);
+ bind(CredentialStoreService.class).to(CredentialStoreServiceImpl.class);
+ bind(UserDAO.class).toInstance(createMock(UserDAO.class));
+ bind(WidgetLayoutDAO.class).toInstance(createMock(WidgetLayoutDAO.class));
+ }
+ });
}
}