Search in sources :

Example 36 with ApplicationUser

use of org.finra.herd.model.dto.ApplicationUser in project herd by FINRAOS.

the class CurrentUserServiceTest method testGetCurrentUserNoSecurityRolesAndFunctions.

@Test
public void testGetCurrentUserNoSecurityRolesAndFunctions() throws Exception {
    // Create a set of test namespace authorizations.
    Set<NamespaceAuthorization> namespaceAuthorizations = new LinkedHashSet<>();
    namespaceAuthorizations.add(new NamespaceAuthorization(NAMESPACE, SUPPORTED_NAMESPACE_PERMISSIONS));
    namespaceAuthorizations.add(new NamespaceAuthorization(NAMESPACE_2, SUPPORTED_NAMESPACE_PERMISSIONS));
    // Override the security context to return an application user populated with test values.
    Authentication originalAuthentication = SecurityContextHolder.getContext().getAuthentication();
    try {
        SecurityContextHolder.getContext().setAuthentication(new Authentication() {

            @Override
            public String getName() {
                return null;
            }

            @Override
            public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
            }

            @Override
            public boolean isAuthenticated() {
                return false;
            }

            @Override
            public Object getPrincipal() {
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                ApplicationUser applicationUser = new ApplicationUser(this.getClass());
                applicationUser.setUserId(USER_ID);
                applicationUser.setNamespaceAuthorizations(namespaceAuthorizations);
                return new SecurityUserWrapper(USER_ID, STRING_VALUE, true, true, true, true, authorities, applicationUser);
            }

            @Override
            public Object getDetails() {
                return null;
            }

            @Override
            public Object getCredentials() {
                return null;
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                return null;
            }
        });
        // Get the current user information.
        UserAuthorizations userAuthorizations = currentUserService.getCurrentUser();
        // Validate the response object.
        assertEquals(new UserAuthorizations(USER_ID, new ArrayList<>(namespaceAuthorizations), NO_SECURITY_ROLES, NO_SECURITY_FUNCTIONS), userAuthorizations);
    } finally {
        // Restore the original authentication.
        SecurityContextHolder.getContext().setAuthentication(originalAuthentication);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ApplicationUser(org.finra.herd.model.dto.ApplicationUser) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) NamespaceAuthorization(org.finra.herd.model.api.xml.NamespaceAuthorization) Authentication(org.springframework.security.core.Authentication) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) UserAuthorizations(org.finra.herd.model.api.xml.UserAuthorizations) Test(org.junit.Test)

Example 37 with ApplicationUser

use of org.finra.herd.model.dto.ApplicationUser in project herd by FINRAOS.

the class CurrentUserServiceImpl method getCurrentUser.

@Override
public UserAuthorizations getCurrentUser() {
    // Create the user authorizations.
    UserAuthorizations userAuthorizations = new UserAuthorizations();
    // Get the application user.
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        SecurityUserWrapper securityUserWrapper = (SecurityUserWrapper) authentication.getPrincipal();
        ApplicationUser applicationUser = securityUserWrapper.getApplicationUser();
        userAuthorizations.setUserId(applicationUser.getUserId());
        // If roles are present on the application user then filter the herd-specific security roles and add that information to the Current user.
        if (CollectionUtils.isNotEmpty(applicationUser.getRoles())) {
            userAuthorizations.setSecurityRoles(new ArrayList<>(getValidSecurityRoles(applicationUser.getRoles())));
        }
        // Get all granted authorities for this user.
        Collection<GrantedAuthority> grantedAuthorities = securityUserWrapper.getAuthorities();
        // Add relative security functions as per granted authorities, if any are present.
        if (CollectionUtils.isNotEmpty(grantedAuthorities)) {
            userAuthorizations.setSecurityFunctions(grantedAuthorities.stream().map(grantedAuthority -> new String(grantedAuthority.getAuthority())).collect(Collectors.toList()));
        }
        userAuthorizations.setNamespaceAuthorizations(new ArrayList<>(applicationUser.getNamespaceAuthorizations()));
    }
    return userAuthorizations;
}
Also used : ApplicationUser(org.finra.herd.model.dto.ApplicationUser) Authentication(org.springframework.security.core.Authentication) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserAuthorizations(org.finra.herd.model.api.xml.UserAuthorizations)

Example 38 with ApplicationUser

use of org.finra.herd.model.dto.ApplicationUser in project herd by FINRAOS.

the class NamespaceSecurityHelper method checkPermission.

/**
 * Checks the current user's permissions against the given namespace.
 *
 * @param namespace The namespace
 * @param permissions The permissions the current user must have for the given namespace
 */
public void checkPermission(String namespace, NamespacePermissionEnum[] permissions) {
    // Skip the permission check if there is no authentication or namespace is not specified.
    if (!isAuthenticated() || StringUtils.isBlank(namespace)) {
        return;
    }
    // Trim the namespace.
    String namespaceTrimmed = namespace.trim();
    // Check if the current user is authorized to the given namespace and has the given permissions.
    ApplicationUser applicationUser = getApplicationUser();
    if (!isAuthorized(applicationUser, namespaceTrimmed, permissions)) {
        String permissionsString = Arrays.asList(permissions).stream().map(n -> n.toString()).collect(Collectors.joining(" OR "));
        permissionsString = "[" + permissionsString + "]";
        // The current user is not authorized to access the given namespace, so log a warning and throw an exception.
        LOGGER.warn(String.format("User does not have permission(s) to the namespace. %s namespace=\"%s\" permissions=\"%s\"", applicationUser, namespaceTrimmed, permissionsString));
        if (applicationUser != null) {
            throw new AccessDeniedException(String.format("User \"%s\" does not have \"%s\" permission(s) to the namespace \"%s\"", applicationUser.getUserId(), permissionsString, namespaceTrimmed));
        } else {
            throw new AccessDeniedException(String.format("Current user does not have \"%s\" permission(s) to the namespace \"%s\"", permissionsString, namespaceTrimmed));
        }
    }
}
Also used : ApplicationUser(org.finra.herd.model.dto.ApplicationUser) Arrays(java.util.Arrays) Logger(org.slf4j.Logger) NamespacePermissionEnum(org.finra.herd.model.api.xml.NamespacePermissionEnum) NamespaceAuthorization(org.finra.herd.model.api.xml.NamespaceAuthorization) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) ApplicationUser(org.finra.herd.model.dto.ApplicationUser) AccessDeniedException(org.springframework.security.access.AccessDeniedException) Collectors(java.util.stream.Collectors) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) Component(org.springframework.stereotype.Component) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) Collections(java.util.Collections) AccessDeniedException(org.springframework.security.access.AccessDeniedException)

Example 39 with ApplicationUser

use of org.finra.herd.model.dto.ApplicationUser in project herd by FINRAOS.

the class NamespaceSecurityAdviceTest method checkPermissionAssertNoExceptionWhenComplexCaseAndUserHasAllPermissions.

@Test
public void checkPermissionAssertNoExceptionWhenComplexCaseAndUserHasAllPermissions() throws Exception {
    // Mock a join point of the method call
    // mockMethod(request);
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", BusinessObjectDataNotificationRegistrationCreateRequest.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "request" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    BusinessObjectDataNotificationRegistrationCreateRequest request = new BusinessObjectDataNotificationRegistrationCreateRequest();
    request.setBusinessObjectDataNotificationRegistrationKey(new NotificationRegistrationKey("ns1", null));
    request.setBusinessObjectDataNotificationFilter(new BusinessObjectDataNotificationFilter("ns2", null, null, null, null, null, null, null));
    request.setJobActions(Arrays.asList(new JobAction("ns3", null, null), new JobAction("ns4", null, null)));
    when(joinPoint.getArgs()).thenReturn(new Object[] { request });
    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("ns1", Arrays.asList(NamespacePermissionEnum.WRITE)));
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("ns2", Arrays.asList(NamespacePermissionEnum.READ)));
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("ns3", Arrays.asList(NamespacePermissionEnum.EXECUTE)));
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("ns4", Arrays.asList(NamespacePermissionEnum.EXECUTE)));
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));
    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
    } catch (AccessDeniedException e) {
        fail();
    }
}
Also used : ApplicationUser(org.finra.herd.model.dto.ApplicationUser) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MethodSignature(org.aspectj.lang.reflect.MethodSignature) BusinessObjectDataNotificationRegistrationCreateRequest(org.finra.herd.model.api.xml.BusinessObjectDataNotificationRegistrationCreateRequest) BusinessObjectDataNotificationFilter(org.finra.herd.model.api.xml.BusinessObjectDataNotificationFilter) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) NamespaceAuthorization(org.finra.herd.model.api.xml.NamespaceAuthorization) Method(java.lang.reflect.Method) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) JoinPoint(org.aspectj.lang.JoinPoint) JobAction(org.finra.herd.model.api.xml.JobAction) NotificationRegistrationKey(org.finra.herd.model.api.xml.NotificationRegistrationKey) AbstractServiceTest(org.finra.herd.service.AbstractServiceTest) Test(org.junit.Test)

Example 40 with ApplicationUser

use of org.finra.herd.model.dto.ApplicationUser in project herd by FINRAOS.

the class NamespaceSecurityAdviceTest method checkPermissionAssertAccessDeniedWhenNoPermissionsNamespaceTrimmed.

@Test
public void checkPermissionAssertAccessDeniedWhenNoPermissionsNamespaceTrimmed() throws Exception {
    // Mock a join point of the method call
    // mockMethod(" foo ");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { BLANK_TEXT + "foo" + BLANK_TEXT });
    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    // User has permission to "bar" but the actual namespace given is " foo "
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("bar", Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));
    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    } catch (Exception e) {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"foo\"", userId), e.getMessage());
    }
}
Also used : ApplicationUser(org.finra.herd.model.dto.ApplicationUser) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MethodSignature(org.aspectj.lang.reflect.MethodSignature) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) NamespaceAuthorization(org.finra.herd.model.api.xml.NamespaceAuthorization) Method(java.lang.reflect.Method) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) AccessDeniedException(org.springframework.security.access.AccessDeniedException) JoinPoint(org.aspectj.lang.JoinPoint) AbstractServiceTest(org.finra.herd.service.AbstractServiceTest) Test(org.junit.Test)

Aggregations

ApplicationUser (org.finra.herd.model.dto.ApplicationUser)50 SecurityUserWrapper (org.finra.herd.model.dto.SecurityUserWrapper)41 Test (org.junit.Test)36 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)31 AccessDeniedException (org.springframework.security.access.AccessDeniedException)29 NamespaceAuthorization (org.finra.herd.model.api.xml.NamespaceAuthorization)26 AbstractServiceTest (org.finra.herd.service.AbstractServiceTest)22 Method (java.lang.reflect.Method)21 JoinPoint (org.aspectj.lang.JoinPoint)21 MethodSignature (org.aspectj.lang.reflect.MethodSignature)21 ArrayList (java.util.ArrayList)6 Job (org.finra.herd.model.api.xml.Job)6 Authentication (org.springframework.security.core.Authentication)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)5 HashSet (java.util.HashSet)4 LinkedHashSet (java.util.LinkedHashSet)4 ObjectNotFoundException (org.finra.herd.model.ObjectNotFoundException)4 Collection (java.util.Collection)3 List (java.util.List)3 UserAuthorizations (org.finra.herd.model.api.xml.UserAuthorizations)3