@Before public void setup() { resource = new ResourceOwnerPasswordResourceDetails(); resource.setAccessTokenUri(serverRunning.getUrl("/sparklr2/oauth/token")); resource.setClientId("my-trusted-client"); resource.setId("sparklr"); resource.setScope(Arrays.asList("trust")); resource.setUsername("marissa"); resource.setPassword("koala"); OAuth2RestTemplate template = new OAuth2RestTemplate(resource); existingToken = template.getAccessToken(); ((DefaultOAuth2AccessToken) existingToken).setExpiration(new Date(0L)); SecurityContextImpl securityContext = new SecurityContextImpl(); securityContext.setAuthentication(new TestingAuthenticationToken("marissa", "koala", "ROLE_USER")); SecurityContextHolder.setContext(securityContext); }
@Test public void shouldRefuseRequestFromKonkerPlataform() throws Exception { SecurityContext context = SecurityContextHolder.getContext(); Authentication auth = new TestingAuthenticationToken("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883", null); context.setAuthentication(auth); when(oAuthClientDetailsService.loadClientByIdAsRoot("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883")) .thenReturn(ServiceResponseBuilder.<OauthClientDetails>ok() .withResult(OauthClientDetails.builder().parentGateway(gateway).build()).build()); when(jsonParsingService.isValid(json)).thenReturn(true); getMockMvc().perform( post("/gateway/pub") .flashAttr("principal", gateway) .header("X-Konker-Version", "0.1") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isForbidden()) .andExpect(content().string(org.hamcrest.Matchers.containsString("origin"))); }
@Test public void shouldRaiseExceptionInvalidJsonPub() throws Exception { SecurityContext context = SecurityContextHolder.getContext(); Authentication auth = new TestingAuthenticationToken("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883", null); context.setAuthentication(auth); when(oAuthClientDetailsService.loadClientByIdAsRoot("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883")) .thenReturn(ServiceResponseBuilder.<OauthClientDetails>ok() .withResult(OauthClientDetails.builder().parentGateway(gateway).build()).build()); when(jsonParsingService.isValid("[{'a': 10}")).thenReturn(false); getMockMvc().perform( post("/gateway/pub") .flashAttr("principal", gateway) .contentType(MediaType.APPLICATION_JSON) .content("[{'a': 10}")) .andExpect(status().isBadRequest()) .andExpect(content().string(org.hamcrest.Matchers.containsString("{\"code\":\"integration.rest.invalid.body\",\"message\":\"Event content is in invalid format. Expected to be a valid JSON string\"}"))); }
@Test public void shouldPubToKonkerPlataform() throws Exception { SecurityContext context = SecurityContextHolder.getContext(); Authentication auth = new TestingAuthenticationToken("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883", null); context.setAuthentication(auth); when(oAuthClientDetailsService.loadClientByIdAsRoot("gateway://i3k9jfe5/1c6e7df7-fe10-4c53-acae-913e0ceec883")) .thenReturn(ServiceResponseBuilder.<OauthClientDetails>ok() .withResult(OauthClientDetails.builder().parentGateway(gateway).build()).build()); when(jsonParsingService.isValid(json)).thenReturn(true); getMockMvc().perform( post("/gateway/pub") .flashAttr("principal", gateway) .contentType(MediaType.APPLICATION_JSON) .content(json)) .andExpect(status().isOk()) .andExpect(content().string(org.hamcrest.Matchers.containsString("{\"code\":\"200\",\"message\":\"OK\"}"))); }
public static void main(String[] args) { String user = null; if (args != null && args.length > 0) { user = args[0]; } if (user == null || user.isEmpty()) { user = "rod"; } // create the provider and initialize it with the 'configure' method LdapAuthorizationsProvider provider = new LdapAuthorizationsProvider(); provider.configure(new HashMap<String, Serializable>()); // set dummy authentication token corresponding to user 'rod' SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(user, null)); System.out.println("Checking auths from LDAP for user '" + user + "'"); // get the authorizations - this will connect to ldap using the values in geomesa-ldap.properties List<String> auths = provider.getAuthorizations(); System.out.println("Retrieved auths: " + auths); }
/** * 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 checkPermissionAssertAccessDeniedWhenPrincipalIsNotSecurityUserWrapper() 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[] {"foo"}); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("streetcreds", null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage()); } }
@Test public void checkPermissionAssertAccessDeniedWhenPrincipalIsNull() 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[] {"foo"}); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(null, null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", 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(); } }
@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 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 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(); } }
@Before public void setUp() throws Exception { reset(violationServiceMock, mockTeamOperations, mockViolationConverter); violationRequest = new Violation(); violationRequest.setAccountId(ACCOUNT_ID); violationRequest.setRegion(REGION); violationRequest.setEventId(UUID.randomUUID().toString()); violationResult = INITIALIZER.create(violation().id(0L).version(0L)); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test-user", null)); mockMvc = MockMvcBuilders.webAppContextSetup(wac).alwaysDo(print()).build(); objectMapper = new ObjectMapper(); when(mockViolationConverter.convert(any(ViolationEntity.class))).thenAnswer(invocationOnMock -> { final ViolationEntity entity = (ViolationEntity) invocationOnMock.getArguments()[0]; final Violation dto = new Violation(); dto.setId(entity.getId()); return dto; }); }
@Test public void principalChanged() { MockHttpServletRequest request = new MockHttpServletRequest(); assertFalse(filter.principalChanged(request, new TestingAuthenticationToken(new FederatedUser( "uid", "mock-idp", "John Doe", emptySet(), emptySet(), AuthorityUtils.createAuthorityList("USER")), "N/A") ) ); assertTrue(filter.principalChanged(request, new TestingAuthenticationToken(new RunAsFederatedUser( "uid", "mock-idp", "John Doe", emptySet(), emptySet(), AuthorityUtils.createAuthorityList("USER")), "N/A") ) ); request.addHeader(X_IMPERSONATE, true); assertTrue(filter.principalChanged(request, null)); }
@Test public void testGetAuthorizedLogAccessConfigs() throws Exception { // given Set<LogAccessConfig> allLogAccessConfigs = new HashSet<LogAccessConfig>(); LogAccessConfig logAccessConfig = new LogAccessConfig("log-with-onerole-authorized", LogAccessType.LOCAL, "localhost", "/log"); logAccessConfig.setAuthorizedRoles(Arrays.asList("onerole")); allLogAccessConfigs.add(logAccessConfig); logAccessConfig = new LogAccessConfig("log-with-oneuser-authorized", LogAccessType.LOCAL, "localhost", "/log"); logAccessConfig.setAuthorizedUsers(Arrays.asList("oneuser")); allLogAccessConfigs.add(logAccessConfig); TestingAuthenticationToken authenticatedUser = new TestingAuthenticationToken("anyuser", null, "onerole"); // when Set<LogAccessConfig> authorizedLogAccessConfigs = authorizationService.getAuthorizedLogAccessConfigs(allLogAccessConfigs, authenticatedUser); // then assertEquals(1, authorizedLogAccessConfigs.size()); assertEquals("log-with-onerole-authorized", authorizedLogAccessConfigs.iterator().next().getId()); }
@Test public void cumulativePermissions() { Authentication auth = new TestingAuthenticationToken("ben", "ignored", "ROLE_ADMINISTRATOR"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity topParentOid = new ObjectIdentityImpl(TARGET_CLASS, "110"); MutableAcl topParent = mongodbMutableAclService.createAcl(topParentOid); // Add an ACE permission entry Permission cm = new CumulativePermission().set(BasePermission.READ).set(BasePermission.ADMINISTRATION); assertEquals(17, cm.getMask()); Sid benSid = new PrincipalSid(auth); topParent.insertAce(0, cm, benSid, true); assertEquals(1, topParent.getEntries().size()); // Explicitly save the changed ACL topParent = mongodbMutableAclService.updateAcl(topParent); // Check the mask was retrieved correctly assertEquals(17, topParent.getEntries().get(0).getPermission().getMask()); assertTrue(topParent.isGranted(Arrays.asList(cm), Arrays.asList(benSid), true)); SecurityContextHolder.clearContext(); }
@Test public void testAutoAddUserParameter() { WorkflowEngine engine = mock(WorkflowEngine.class); ServiceRegistration<WorkflowEngine> registration = bc.registerService(WorkflowEngine.class, engine, null); URL test1 = getClass().getClassLoader().getResource(TEST1_FILE); Deployment deploy1 = workflowService.createDeployment().key("testAutoAddUserParameter").addURL(test1) .enableDuplicateFiltering().deploy(); WorkflowDefinition def = workflowService.getLastWorkflowDefinitionByKey(TEST1_KEY); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("testUser", "testCredentials")); workflowService.startProcess(def.getId()); ArgumentCaptor<Map> captor = ArgumentCaptor.forClass(Map.class); verify(engine).startProcess(eq(def.getId()), captor.capture()); Map<String, Object> parameters = captor.getValue(); assertEquals("testUser", parameters.get(org.openeos.wf.Constants.LANUCHER_USER_PARAMETER)); registration.unregister(); workflowService.revertDeployment(deploy1.getId()); SecurityContextHolder.getContext().setAuthentication(null); }
@Test public void home() throws Exception { final Authentication originalAuthentication = SecurityContextHolder.getContext().getAuthentication(); try { final String userFullName = "John Smith"; final TestingAuthenticationToken authentication = new TestingAuthenticationToken("principal", "cred"); authentication.setDetails(new DashboardAuthenticationDetails(new MockHttpServletRequest(), true, userFullName)); SecurityContextHolder.getContext().setAuthentication(authentication); final MvcResult mvcResult = mvc .perform( request(HttpMethod.GET, "/dashboard/") ) .andExpect(status().is(HttpStatus.OK.value())) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)) .andReturn(); assertEquals(userFullName, mvcResult.getModelAndView().getModelMap().get(DashboardController.USER_FULL_NAME)); assertEquals(DashboardController.HOME_VIEW, mvcResult.getModelAndView().getViewName()); } finally { SecurityContextHolder.getContext().setAuthentication(originalAuthentication); } }
@Test public void shouldSaveAccessToken() { //Given final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build(); final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next()); final OAuth2AccessToken oAuth2AccessToken = oAuth2AccessTokenBuilder().build(); //And final String authenticationId = string().next(); given(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).willReturn(authenticationId); //When mongoClientTokenServices.saveAccessToken(oAuth2ProtectedResourceDetails, authentication, oAuth2AccessToken); //Then verify(keyGenerator, atLeastOnce()).extractKey(oAuth2ProtectedResourceDetails, authentication); verify(mongoOAuth2ClientTokenRepository).save(any(MongoOAuth2ClientToken.class)); verify(mongoOAuth2ClientTokenRepository).deleteByAuthenticationId(authenticationId); }
@Test public void shouldGetAccessToken() { //Given final OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails = oAuth2ProtectedResourceDetailsBuilder().build(); final TestingAuthenticationToken authentication = new TestingAuthenticationToken(userBuilder().build(), string().next()); //And final String authenticationId = string().next(); given(keyGenerator.extractKey(oAuth2ProtectedResourceDetails, authentication)).willReturn(authenticationId); //And final OAuth2AccessToken expectedToken = oAuth2AccessTokenBuilder().build(); given(mongoOAuth2ClientTokenRepository.findByAuthenticationId(authenticationId)).willReturn(mongoOAuth2ClientTokenBuilder().token(expectedToken).build()); //When final OAuth2AccessToken accessToken = mongoClientTokenServices.getAccessToken(oAuth2ProtectedResourceDetails, authentication); //Then assertThat(accessToken).isEqualTo(expectedToken); }
@Test @Rollback(false) @Transactional(rollbackFor = Exception.class) public void test2UpdateAcl() { Authentication auth = new TestingAuthenticationToken("shazin", "N/A"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity oid = new ObjectIdentityImpl("my.test.Class", 1l); MutableAcl acl = (MutableAcl) mutableAclService.readAclById(oid); acl.insertAce(0, BasePermission.CREATE, new GrantedAuthoritySid( "ROLE_USER"), true); acl.insertAce(1, BasePermission.DELETE, new GrantedAuthoritySid( "ROLE_ADMIN"), true); mutableAclService.updateAcl(acl); }
@Test(expected = NotFoundException.class) @Rollback(false) @Transactional(rollbackFor = Exception.class) public void test3DeleteAcl() { Authentication auth = new TestingAuthenticationToken("shazin", "N/A"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); ObjectIdentity oid = new ObjectIdentityImpl("my.test.Class", 1l); MutableAcl acl = (MutableAcl) mutableAclService.readAclById(oid); assertEquals(acl.getEntries().size(), 2); for (AccessControlEntry ace : acl.getEntries()) { assertEquals(ace.getAcl().getObjectIdentity(), oid); } mutableAclService.deleteAcl(oid, true); mutableAclService.readAclById(oid); }
@Test @Rollback(false) @Transactional(rollbackFor = Exception.class) public void test4readAclById() { Authentication auth = new TestingAuthenticationToken("shazin", "N/A"); auth.setAuthenticated(true); SecurityContextHolder.getContext().setAuthentication(auth); List<Sid> sids = Arrays.<Sid> asList(new PrincipalSid("USER_0"), new GrantedAuthoritySid("ROLE_1")); long start = System.nanoTime(); Acl acl = mutableAclService.readAclById(new ObjectIdentityImpl( "com.test.Shazin1", 1l), sids); long end = System.nanoTime(); System.out.println("Reading 1 objects in " + (end - start)); assertNotNull(acl); assertEquals(2, acl.getEntries().size()); }
@Test public void addWithKnownBackend() { SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("anonymous", null, "ROLE_SU")); EntityType entityType = when(mock(EntityType.class).getId()).thenReturn("entity").getMock(); when(entityType.getAttributes()).thenReturn(emptyList()); String backendName = "knownBackend"; when(entityType.getBackend()).thenReturn(backendName); MetaDataService metaDataService = mock(MetaDataService.class); RepositoryCollection repoCollection = mock(RepositoryCollection.class); when(metaDataService.getBackend(entityType)).thenReturn(repoCollection); when(dataService.getMeta()).thenReturn(metaDataService); repo.add(entityType); verify(delegateRepository).add(entityType); }
@Test(expectedExceptions = MolgenisDataAccessException.class) public void addStreamNoPermission() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null, "ROLE_ENTITY_READ_" + entityId); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); Stream<Entity> entities = Stream.empty(); try { repositorySecurityDecorator.add(entities); } catch (MolgenisDataAccessException e) { verify(delegateRepository, times(1)).getEntityType(); verifyNoMoreInteractions(delegateRepository); throw e; } }
@Test public void findAllPermission() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null, "ROLE_ENTITY_READ_" + entityId); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); Stream<Object> ids = Stream.of(0, 1); Fetch fetch = new Fetch(); Entity entity0 = mock(Entity.class); Entity entity1 = mock(Entity.class); Stream<Entity> entities = Stream.of(entity0, entity1); when(delegateRepository.findAll(ids, fetch)).thenReturn(Stream.of(entity0, entity1)); assertEquals(entities.collect(toList()), repositorySecurityDecorator.findAll(ids, fetch).collect(toList())); verify(delegateRepository, times(1)).findAll(ids, fetch); }
@Test(expectedExceptions = MolgenisDataAccessException.class) public void deleteStreamNoPermission() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null, "ROLE_ENTITY_READ_" + entityId); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); Stream<Entity> entities = Stream.empty(); try { repositorySecurityDecorator.delete(entities); } catch (MolgenisDataAccessException e) { verify(delegateRepository, times(1)).getEntityType(); verifyNoMoreInteractions(delegateRepository); throw e; } }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void updateStream() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null, "ROLE_ENTITY_WRITE_" + entityId); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); Entity entity0 = mock(Entity.class); Stream<Entity> entities = Stream.of(entity0); ArgumentCaptor<Stream<Entity>> captor = ArgumentCaptor.forClass(Stream.class); doNothing().when(delegateRepository).update(captor.capture()); repositorySecurityDecorator.update(entities); assertEquals(captor.getValue().collect(Collectors.toList()), singletonList(entity0)); }
@Test(expectedExceptions = MolgenisDataAccessException.class) public void updateStreamNoPermission() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null, "ROLE_ENTITY_READ_" + entityId); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); Stream<Entity> entities = Stream.empty(); try { repositorySecurityDecorator.update(entities); } catch (MolgenisDataAccessException e) { verify(delegateRepository, times(1)).getEntityType(); verifyNoMoreInteractions(delegateRepository); throw e; } }
@Test public void findAllStream() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null, "ROLE_ENTITY_READ_" + entityId); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); Object id0 = "id0"; Object id1 = "id1"; Entity entity0 = mock(Entity.class); Entity entity1 = mock(Entity.class); Stream<Object> entityIds = Stream.of(id0, id1); when(delegateRepository.findAll(entityIds)).thenReturn(Stream.of(entity0, entity1)); Stream<Entity> expectedEntities = repositorySecurityDecorator.findAll(entityIds); assertEquals(expectedEntities.collect(Collectors.toList()), Arrays.asList(entity0, entity1)); }
@Test public void findAllStreamFetch() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null, "ROLE_ENTITY_READ_" + entityId); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); Fetch fetch = new Fetch(); Object id0 = "id0"; Object id1 = "id1"; Entity entity0 = mock(Entity.class); Entity entity1 = mock(Entity.class); Stream<Object> entityIds = Stream.of(id0, id1); when(delegateRepository.findAll(entityIds, fetch)).thenReturn(Stream.of(entity0, entity1)); Stream<Entity> expectedEntities = repositorySecurityDecorator.findAll(entityIds, fetch); assertEquals(expectedEntities.collect(Collectors.toList()), Arrays.asList(entity0, entity1)); }
@Test(expectedExceptions = MolgenisDataAccessException.class) public void findAllStreamFetchNoPermission() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); Fetch fetch = new Fetch(); Object id0 = "id0"; Object id1 = "id1"; Entity entity0 = mock(Entity.class); Entity entity1 = mock(Entity.class); Stream<Object> entityIds = Stream.of(id0, id1); when(delegateRepository.findAll(entityIds, fetch)).thenReturn(Stream.of(entity0, entity1)); repositorySecurityDecorator.findAll(entityIds, fetch); }
@Test public void addStreamExtendsOwned() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); when(entityType.getExtends()).thenReturn(new OwnedEntityType(mock(SecurityPackage.class))); Entity entity0 = mock(Entity.class); when(entity0.getIdValue()).thenReturn("0"); Entity entity1 = mock(Entity.class); when(entity1.getIdValue()).thenReturn("0"); Stream<Entity> entities = Stream.of(entity0, entity1); ownedEntityRepositoryDecorator.add(entities); @SuppressWarnings({ "unchecked", "rawtypes" }) ArgumentCaptor<Stream<Entity>> captor = ArgumentCaptor.forClass(Stream.class); verify(delegateRepository, times(1)).add(captor.capture()); List<Entity> myEntities = captor.getValue().collect(Collectors.toList()); assertEquals(myEntities, asList(entity0, entity1)); verify(entity0, times(1)).set(OwnedEntityType.OWNER_USERNAME, "username"); verify(entity1, times(1)).set(OwnedEntityType.OWNER_USERNAME, "username"); }
@SuppressWarnings("rawtypes") @Test public void deleteStreamEntityExtendsOwned() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); when(entityType.getExtends()).thenReturn(new OwnedEntityType(mock(SecurityPackage.class))); Entity myEntity = when(mock(Entity.class).getString(OWNER_USERNAME)).thenReturn("username").getMock(); Entity notMyEntity = when(mock(Entity.class).getString(OWNER_USERNAME)).thenReturn("notme").getMock(); ownedEntityRepositoryDecorator.delete(Stream.of(myEntity, notMyEntity)); @SuppressWarnings("unchecked") ArgumentCaptor<Stream<Entity>> captor = ArgumentCaptor.forClass(Stream.class); verify(delegateRepository, times(1)).delete(captor.capture()); List<Entity> myEntities = captor.getValue().collect(Collectors.toList()); assertEquals(myEntities, asList(myEntity)); }
@SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void updateStreamExtendsOwned() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); when(entityType.getExtends()).thenReturn(new OwnedEntityType(mock(SecurityPackage.class))); Entity entity0 = mock(Entity.class); when(entity0.get(OwnedEntityType.OWNER_USERNAME)).thenReturn("usernameUpdate"); Stream<Entity> entities = Stream.of(entity0); ArgumentCaptor<Stream<Entity>> captor = ArgumentCaptor.forClass(Stream.class); doNothing().when(delegateRepository).update(captor.capture()); ownedEntityRepositoryDecorator.update(entities); List<Entity> entityList = captor.getValue().collect(Collectors.toList()); assertEquals(entityList, asList(entity0)); verify(entityList.get(0)).set(OwnedEntityType.OWNER_USERNAME, "username"); }
@Test public void findOneByIdObjectFetchExtendsOwned() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); when(entityType.getExtends()).thenReturn(new OwnedEntityType(mock(SecurityPackage.class))); Object id = 0; Fetch fetch = new Fetch(); Entity myEntity = when(mock(Entity.class).getString(OWNER_USERNAME)).thenReturn("username").getMock(); Fetch decoratedFetch = new Fetch().field(OWNER_USERNAME); when(delegateRepository.findOneById(id, decoratedFetch)).thenReturn(myEntity); assertEquals(myEntity, ownedEntityRepositoryDecorator.findOneById(id, fetch)); verify(delegateRepository, times(1)).findOneById(id, fetch); }
@Test public void findOneByIdObjectFetchExtendsOwnedBySomeoneElse() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); when(entityType.getExtends()).thenReturn(new OwnedEntityType(mock(SecurityPackage.class))); Object id = 0; Fetch fetch = new Fetch(); Entity myEntity = when(mock(Entity.class).getString(OWNER_USERNAME)).thenReturn("notme").getMock(); Fetch decoratedFetch = new Fetch().field(OWNER_USERNAME); when(delegateRepository.findOneById(id, decoratedFetch)).thenReturn(myEntity); assertNull(ownedEntityRepositoryDecorator.findOneById(id, fetch)); verify(delegateRepository, times(1)).findOneById(id, fetch); }
@Test public void findAllStreamExtendsOwned() { TestingAuthenticationToken authentication = new TestingAuthenticationToken("username", null); authentication.setAuthenticated(false); SecurityContextHolder.getContext().setAuthentication(authentication); when(entityType.getExtends()).thenReturn(new OwnedEntityType(mock(SecurityPackage.class))); Object id0 = "id0"; Object id1 = "id1"; Entity entity0 = when(mock(Entity.class).getString(OWNER_USERNAME)).thenReturn("username").getMock(); Entity entity1 = when(mock(Entity.class).getString(OWNER_USERNAME)).thenReturn("username").getMock(); Stream<Object> entityIds = Stream.of(id0, id1); when(delegateRepository.findAll(entityIds)).thenReturn(Stream.of(entity0, entity1)); Stream<Entity> expectedEntities = ownedEntityRepositoryDecorator.findAll(entityIds); assertEquals(expectedEntities.collect(Collectors.toList()), asList(entity0, entity1)); }