/** * Builds a user Id. * * @param applicationUser the application user. * @param httpHeaders the HTTP headers. * @param headerName the header name for the user Id. */ protected void buildUserId(ApplicationUser applicationUser, Map<String, String> httpHeaders, String headerName) { String userId = getHeaderValueString(headerName, httpHeaders); if (userId == null) { throw new IllegalArgumentException("userId is required. No value for userId was found in the header " + headerName); } applicationUser.setUserId(userId); }
/** * Builds the application user. * * @param request the HTTP servlet request. * @param includeRoles If true, the user's roles will be included. Otherwise, not. * * @return the application user. */ protected ApplicationUser buildUser(HttpServletRequest request, boolean includeRoles) { ApplicationUser applicationUser = new ApplicationUser(this.getClass()); applicationUser.setUserId(TRUSTED_USER_ID); applicationUser.setFirstName(TRUSTED_USER_FIRST_NAME); applicationUser.setLastName(TRUSTED_USER_LAST_NAME); applicationUser.setEmail(TRUSTED_USER_EMAIL); applicationUser.setSessionId(request.getSession().getId()); applicationUser.setNamespaceAuthorizations(userNamespaceAuthorizationHelper.getAllNamespaceAuthorizations()); if (includeRoles) { Set<String> roles = new HashSet<>(); roles.add(TRUSTED_USER_ROLE); applicationUser.setRoles(roles); } return applicationUser; } }
@Override public Object getPrincipal() { List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority(SECURITY_FUNCTION), new SimpleGrantedAuthority(SECURITY_FUNCTION_2)); ApplicationUser applicationUser = new ApplicationUser(this.getClass()); applicationUser.setUserId(USER_ID); applicationUser.setRoles(roles); applicationUser.setNamespaceAuthorizations(namespaceAuthorizations); return new SecurityUserWrapper(USER_ID, STRING_VALUE, true, true, true, true, authorities, applicationUser); }
@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 getPrincipal() { List<SimpleGrantedAuthority> authorities = Lists.newArrayList(new SimpleGrantedAuthority(SECURITY_FUNCTION)); ApplicationUser applicationUser = new ApplicationUser(this.getClass()); applicationUser.setUserId(USER_ID); applicationUser.setRoles(roles); applicationUser.setNamespaceAuthorizations(namespaceAuthorizations); return new SecurityUserWrapper(USER_ID, STRING_VALUE, true, true, true, true, authorities, applicationUser); }
/** * Sets specified namespace authorizations for the current user by updating the security context. * * @param namespace the namespace * @param namespacePermissions the list of namespace permissions */ public void setCurrentUserNamespaceAuthorizations(String namespace, List<NamespacePermissionEnum> namespacePermissions) { String username = AbstractServiceTest.USER_ID; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(username); Set<NamespaceAuthorization> namespaceAuthorizations = new LinkedHashSet<>(); namespaceAuthorizations.add(new NamespaceAuthorization(namespace, namespacePermissions)); applicationUser.setNamespaceAuthorizations(namespaceAuthorizations); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); }
@Test public void checkPermissionAssertNoErrorWhenMethodDoesNotHaveAnnotations() throws Exception { // Mock a join point of the method call // mockMethod(1); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod"); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); } catch (AccessDeniedException e) { fail(); } }
@Test public void checkPermissionAssertNoExceptionWhenNamespaceBlank() throws Exception { // Mock a join point of the method call // mockMethod(" "); 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}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); } catch (AccessDeniedException e) { fail(); } }
@Test public void testBuildNamespaceAuthorizationsAssertWildcardEntityNotAddedIfMatchFails() { ApplicationUser applicationUser = new ApplicationUser(getClass()); String userId = "userId"; applicationUser.setUserId(userId); when(configurationHelper.getBooleanProperty(any())).thenReturn(true); List<UserNamespaceAuthorizationEntity> wildcardEntities = new ArrayList<>(); UserNamespaceAuthorizationEntity wildcardEntity = new UserNamespaceAuthorizationEntity(); wildcardEntity.setUserId("wildcardEntityUserId"); NamespaceEntity namespaceEntity = new NamespaceEntity(); namespaceEntity.setCode("namespace"); wildcardEntity.setNamespace(namespaceEntity); wildcardEntities.add(wildcardEntity); when(userNamespaceAuthorizationDao.getUserNamespaceAuthorizationsByUserIdStartsWith(any())).thenReturn(wildcardEntities); when(wildcardHelper.matches(any(), any())).thenReturn(false); userNamespaceAuthorizationHelper.buildNamespaceAuthorizations(applicationUser); assertEquals(0, applicationUser.getNamespaceAuthorizations().size()); verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserId(eq(userId)); verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserIdStartsWith(eq(WildcardHelper.WILDCARD_TOKEN)); verify(wildcardHelper).matches(eq(userId.toUpperCase()), eq(wildcardEntity.getUserId().toUpperCase())); verifyNoMoreInteractions(userNamespaceAuthorizationDao, wildcardHelper); } }
@Test public void checkPermissionAssertNoErrorWhenUserHasMultiplePermissions() 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.getMethod()).thenReturn(method); when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"}); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); applicationUser.getNamespaceAuthorizations() .add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ, NamespacePermissionEnum.WRITE))); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); } catch (AccessDeniedException e) { fail(); } }
/** * Retrieves application user per last updater of the current process instance's job definition. * * @param execution the delegate execution * * @return the application user */ protected ApplicationUser getApplicationUser(DelegateExecution execution) { String processDefinitionId = execution.getProcessDefinitionId(); // Get process definition by process definition ID from Activiti. ProcessDefinition processDefinition = activitiService.getProcessDefinitionById(processDefinitionId); // Validate that we retrieved the process definition from Activiti. if (processDefinition == null) { throw new ObjectNotFoundException(String.format("Failed to find Activiti process definition for processDefinitionId=\"%s\".", processDefinitionId)); } // Retrieve the process definition key. String processDefinitionKey = processDefinition.getKey(); // Get the job definition key. JobDefinitionAlternateKeyDto jobDefinitionKey = jobDefinitionHelper.getJobDefinitionKey(processDefinitionKey); // Get the job definition from the Herd repository and validate that it exists. JobDefinitionEntity jobDefinitionEntity = jobDefinitionDaoHelper.getJobDefinitionEntity(jobDefinitionKey.getNamespace(), jobDefinitionKey.getJobName()); // Set the security context per last updater of the job definition. String updatedByUserId = jobDefinitionEntity.getUpdatedBy(); ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(updatedByUserId); return applicationUser; }
@Test public void testBuildNamespaceAuthorizationsAssertWildcardQueryExecuted() { ApplicationUser applicationUser = new ApplicationUser(getClass()); String userId = "userId"; applicationUser.setUserId(userId); when(configurationHelper.getBooleanProperty(any())).thenReturn(true); List<UserNamespaceAuthorizationEntity> wildcardEntities = new ArrayList<>(); UserNamespaceAuthorizationEntity wildcardEntity = new UserNamespaceAuthorizationEntity(); wildcardEntity.setUserId("wildcardEntityUserId"); NamespaceEntity namespaceEntity = new NamespaceEntity(); namespaceEntity.setCode("namespace"); wildcardEntity.setNamespace(namespaceEntity); wildcardEntities.add(wildcardEntity); when(userNamespaceAuthorizationDao.getUserNamespaceAuthorizationsByUserIdStartsWith(any())).thenReturn(wildcardEntities); when(wildcardHelper.matches(any(), any())).thenReturn(true); userNamespaceAuthorizationHelper.buildNamespaceAuthorizations(applicationUser); assertEquals(1, applicationUser.getNamespaceAuthorizations().size()); NamespaceAuthorization namespaceAuthorization = IterableUtils.get(applicationUser.getNamespaceAuthorizations(), 0); assertEquals(namespaceEntity.getCode(), namespaceAuthorization.getNamespace()); verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserId(eq(userId)); verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserIdStartsWith(eq(WildcardHelper.WILDCARD_TOKEN)); verify(wildcardHelper).matches(eq(userId.toUpperCase()), eq(wildcardEntity.getUserId().toUpperCase())); verifyNoMoreInteractions(userNamespaceAuthorizationDao, wildcardHelper); }
@Test public void testBuildNamespaceAuthorizationsAssertAuthLookupByUserId() { ApplicationUser applicationUser = new ApplicationUser(getClass()); String userId = "userId"; applicationUser.setUserId(userId); when(configurationHelper.getBooleanProperty(any())).thenReturn(true); List<UserNamespaceAuthorizationEntity> userNamespaceAuthorizationEntities = new ArrayList<>(); UserNamespaceAuthorizationEntity userNamespaceAuthorizationEntity = new UserNamespaceAuthorizationEntity(); userNamespaceAuthorizationEntity.setUserId("userNamespaceAuthorizationEntityUserId"); NamespaceEntity namespaceEntity = new NamespaceEntity(); namespaceEntity.setCode("namespace"); userNamespaceAuthorizationEntity.setNamespace(namespaceEntity); userNamespaceAuthorizationEntities.add(userNamespaceAuthorizationEntity); when(userNamespaceAuthorizationDao.getUserNamespaceAuthorizationsByUserId(any())).thenReturn(userNamespaceAuthorizationEntities); userNamespaceAuthorizationHelper.buildNamespaceAuthorizations(applicationUser); assertEquals(1, applicationUser.getNamespaceAuthorizations().size()); NamespaceAuthorization namespaceAuthorization = IterableUtils.get(applicationUser.getNamespaceAuthorizations(), 0); assertEquals(namespaceEntity.getCode(), namespaceAuthorization.getNamespace()); verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserId(eq(userId)); verify(userNamespaceAuthorizationDao).getUserNamespaceAuthorizationsByUserIdStartsWith(eq(WildcardHelper.WILDCARD_TOKEN)); verifyNoMoreInteractions(userNamespaceAuthorizationDao, wildcardHelper); }
/** * Asserts that the namespace security advice is enabled. Try calling a secured method with a mock user in the context with invalid permissions. The * expectation is that the method call fails with AccessDeniedException if the advice is enabled. */ @Test public void assertAdviceEnabled() { // put a fake user with no permissions into the security context // the security context is cleared on the after() method of this test suite String username = "username"; Class<?> generatedByClass = getClass(); ApplicationUser applicationUser = new ApplicationUser(generatedByClass); applicationUser.setUserId(username); applicationUser.setNamespaceAuthorizations(Collections.emptySet()); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); try { businessObjectDefinitionServiceImpl .createBusinessObjectDefinition(new BusinessObjectDefinitionCreateRequest(NAMESPACE, BDEF_NAME, DATA_PROVIDER_NAME, null, null, null)); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); } }
@Test public void testGetJobAssertNoErrorGivenJobCompletedAndUserDoesHasPermissions() throws Exception { jobDefinitionServiceTestHelper.createJobDefinition(null); Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME)); String username = "username"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(username); applicationUser.setNamespaceAuthorizations(new HashSet<>()); applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.READ))); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); try { jobService.getJob(job.getId(), false); } catch (AccessDeniedException e) { fail(); } }
@Test public void testGetJobAssertAccessDeniedGivenJobCompletedAndUserDoesNotHavePermissions() throws Exception { jobDefinitionServiceTestHelper.createJobDefinition(null); Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME)); String username = "username"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(username); applicationUser.setNamespaceAuthorizations(new HashSet<>()); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); try { jobService.getJob(job.getId(), false); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"%s\"", username, TEST_ACTIVITI_NAMESPACE_CD), e.getMessage()); } }
@Test public void testGetJobAssertAccessDeniedGivenJobRunningAndUserDoesNotHavePermissions() throws Exception { jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_USER_TASK_WITH_CLASSPATH); Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME)); String username = "username"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(username); applicationUser.setNamespaceAuthorizations(new HashSet<>()); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); try { jobService.getJob(job.getId(), false); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"%s\"", username, TEST_ACTIVITI_NAMESPACE_CD), e.getMessage()); } }
@Test public void testGetJobAssertNoErrorGivenJobRunningAndUserDoesHasPermissions() throws Exception { jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_USER_TASK_WITH_CLASSPATH); Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME)); String username = "username"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(username); applicationUser.setNamespaceAuthorizations(new HashSet<>()); applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.READ))); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); try { jobService.getJob(job.getId(), false); } catch (AccessDeniedException e) { fail(); } }
@Test public void testDeleteJobAssertAccessDeniedWhenUserHasNoPermissions() throws Exception { // Start a job that will wait in a receive task jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_RECEIVE_TASK_WITH_CLASSPATH); Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME)); String username = "username"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(username); applicationUser.setNamespaceAuthorizations(new HashSet<>()); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); try { jobService.deleteJob(job.getId(), new JobDeleteRequest("test delete reason")); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals(String.format("User \"%s\" does not have \"[EXECUTE]\" permission(s) to the namespace \"%s\"", username, TEST_ACTIVITI_NAMESPACE_CD), e.getMessage()); } }
@Test public void testDeleteJobAssertNoErrorWhenUserHasPermissions() throws Exception { // Start a job that will wait in a receive task jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_TEST_RECEIVE_TASK_WITH_CLASSPATH); Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME)); String username = "username"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(username); applicationUser.setNamespaceAuthorizations(new HashSet<>()); applicationUser.getNamespaceAuthorizations() .add(new NamespaceAuthorization(TEST_ACTIVITI_NAMESPACE_CD, Arrays.asList(NamespacePermissionEnum.EXECUTE))); SecurityContextHolder.getContext().setAuthentication( new TestingAuthenticationToken(new SecurityUserWrapper(username, "password", false, false, false, false, Collections.emptyList(), applicationUser), null)); try { jobService.deleteJob(job.getId(), new JobDeleteRequest("test delete reason")); } catch (AccessDeniedException e) { fail(); } }