src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
BasicService implements EntityService, AccessibilityCheck { protected void checkFieldAccess(NeutralQuery query, boolean isSelf) { if (query != null) { Collection<GrantedAuthority> auths = getAuths(isSelf); rightAccessValidator.checkFieldAccess(query, defn.getType(), auths); } } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
@Test public void testCheckFieldAccessAdmin() { securityContextInjector.setAdminContextWithElevatedRights(); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria("economicDisadvantaged", "=", "true")); NeutralQuery query1 = new NeutralQuery(query); service.checkFieldAccess(query, false); assertTrue("Should match", query1.equals(query)); } @Test (expected = QueryParseException.class) public void testCheckFieldAccessEducator() { securityContextInjector.setEducatorContext(); NeutralQuery query = new NeutralQuery(); query.addCriteria(new NeutralCriteria("economicDisadvantaged", "=", "true")); service.checkFieldAccess(query, false); }
AuthRequestService { public Request processRequest(String encodedSamlRequest, String realm, String developer) { if (encodedSamlRequest == null) { return null; } SamlRequest request = samlDecoder.decode(encodedSamlRequest); return new Request(realm, developer, request); } Request processRequest(String encodedSamlRequest, String realm, String developer); }
@Test public void testHappy() { SamlRequest request = Mockito.mock(SamlRequest.class); Mockito.when(request.getId()).thenReturn("id"); Mockito.when(request.getIdpDestination()).thenReturn("http: Mockito.when(samlDecoder.decode("samlRequest")).thenReturn(request); Request processed = authService.processRequest("samlRequest", "myrealm", null); Mockito.verify(samlDecoder).decode("samlRequest"); assertEquals("id", processed.getRequestId()); assertEquals("myrealm", processed.getRealm()); assertEquals(null, authService.processRequest(null, null, null)); } @Test public void testForceAuthn() { SamlRequest request = Mockito.mock(SamlRequest.class); Mockito.when(request.getId()).thenReturn("id"); Mockito.when(request.getIdpDestination()).thenReturn("http: Mockito.when(request.isForceAuthn()).thenReturn(true); Mockito.when(samlDecoder.decode("samlRequest")).thenReturn(request); Request processed = authService.processRequest("samlRequest", "myrealm", null); Mockito.verify(samlDecoder).decode("samlRequest"); assertEquals("id", processed.getRequestId()); assertEquals("myrealm", processed.getRealm()); assertEquals(true, processed.isForceAuthn()); assertEquals(null, authService.processRequest(null, null, null)); }
BasicService implements EntityService, AccessibilityCheck { protected boolean isSelf(NeutralQuery query) { List<NeutralCriteria> allTheCriteria = query.getCriteria(); for (NeutralQuery orQuery: query.getOrQueries()) { if(!isSelf(orQuery)) { return false; } } for(NeutralCriteria criteria: allTheCriteria) { if (criteria.getOperator().equals(NeutralCriteria.CRITERIA_IN) && criteria.getValue() instanceof List) { List<?> value = (List<?>) criteria.getValue(); if (value.size() == 1 && isSelf(value.get(0).toString())) { return true; } } else if (criteria.getOperator().equals(NeutralCriteria.OPERATOR_EQUAL) && criteria.getValue() instanceof String) { if (isSelf((String) criteria.getValue())){ return true; } } } return false; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
@Test public void testIsSelf() { BasicService basicService = (BasicService) context.getBean("basicService", "teacher", new ArrayList<Treatment>(), securityRepo); basicService.setDefn(definitionStore.lookupByEntityType("teacher")); securityContextInjector.setEducatorContext("my-id"); assertTrue(basicService.isSelf(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.OPERATOR_EQUAL, "my-id")))); NeutralQuery query = new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList("my-id"))); assertTrue(basicService.isSelf(query)); query.addCriteria(new NeutralCriteria("someOtherProperty", NeutralCriteria.OPERATOR_EQUAL, "somethingElse")); assertTrue(basicService.isSelf(query)); query.addOrQuery(new NeutralQuery(new NeutralCriteria("refProperty", NeutralCriteria.OPERATOR_EQUAL, "my-id"))); assertTrue(basicService.isSelf(query)); query.addOrQuery(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.OPERATOR_EQUAL, "someoneElse"))); assertFalse(basicService.isSelf(query)); assertFalse(basicService.isSelf(new NeutralQuery(new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList("my-id", "someoneElse"))))); }
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> list(NeutralQuery neutralQuery) { LOG.debug(">>>BasicService.list(neutralQuery)"); listSecurityCheck(neutralQuery); return listImplementationAfterSecurityChecks(neutralQuery); } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
@SuppressWarnings("unchecked") @Test public void testList() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { securityContextInjector.setEducatorContext(); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); EntityBody entityBody2 = new EntityBody(); entityBody2.put("studentUniqueStateId", "student2"); Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>()); Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>()); Iterable<Entity> entities = Arrays.asList(entity1, entity2); Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities); Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(2L); Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity1), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.any(Collection.class), Mockito.any(Collection.class))).thenReturn(entityBody1); Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity2), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.any(Collection.class), Mockito.any(Collection.class))).thenReturn(entityBody2); RequestUtil.setCurrentRequestId(); Iterable<EntityBody> listResult = service.list(new NeutralQuery()); List<EntityBody> bodies= new ArrayList<EntityBody>(); for (EntityBody body : listResult) { bodies.add(body); } Assert.assertEquals("EntityBody mismatch", entityBody1, bodies.toArray()[0]); Assert.assertEquals("EntityBody mismatch", entityBody2, bodies.toArray()[1]); long count = service.count(new NeutralQuery()); Assert.assertEquals(2, count); }
BasicService implements EntityService, AccessibilityCheck { @Override public Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery) { boolean isSelf = isSelf(neutralQuery); boolean noDataInDB = true; Map<String, UserContext> entityContexts = null; injectSecurity(neutralQuery); boolean findSpecial = userHasMultipleContextsOrDifferingRights() && (!EntityNames.isPublic(defn.getType())); Collection<Entity> entities = new HashSet<Entity>(); if (findSpecial) { entities = getResponseEntities(neutralQuery, isSelf); entityContexts = getEntityContexts(); } else { entities = (Collection<Entity>) repo.findAll(collectionName, neutralQuery); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { entityContexts = getEntityContextMap(entities, true); } } Collection<Entity> bodylessEntities = new HashSet<Entity>(); for(Entity ent : entities) { if(ent.getBody() == null || ent.getBody().size() == 0) { bodylessEntities.add(ent); } } entities.removeAll(bodylessEntities); noDataInDB = entities.isEmpty(); List<EntityBody> results = new ArrayList<EntityBody>(); for (Entity entity : entities) { UserContext context = getEntityContext(entity.getEntityId(), entityContexts); try { Collection<GrantedAuthority> auths = null; if (!findSpecial) { auths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); rightAccessValidator.checkAccess(true, isSelf, entity, defn.getType(), auths); rightAccessValidator.checkFieldAccess(neutralQuery, entity, defn.getType(), auths); } else { auths = getEntityAuthorities(entity.getEntityId()); } results.add(entityRightsFilter.makeEntityBody(entity, treatments, defn, isSelf, auths, context)); } catch (AccessDeniedException aex) { if (entities.size() == 1) { throw aex; } else { LOG.error(aex.getMessage()); } } } if (results.isEmpty()) { validateQuery(neutralQuery, isSelf); return noEntitiesFound(noDataInDB); } return results; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
@SuppressWarnings("unchecked") @Test public void testListBasedOnContextualRoles() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { securityContextInjector.setEducatorContext(); SecurityUtil.setUserContext(SecurityUtil.UserContext.TEACHER_CONTEXT); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); Collection<GrantedAuthority> teacherContextRights = new HashSet<GrantedAuthority>(Arrays.asList(Right.TEACHER_CONTEXT, Right.READ_PUBLIC, Right.WRITE_PUBLIC)); EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); EntityBody entityBody2 = new EntityBody(); entityBody2.put("studentUniqueStateId", "student2"); Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>()); Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>()); Iterable<Entity> entities = Arrays.asList(entity1, entity2); Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities); Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(2L); Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity1), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.anyBoolean(), Mockito.any(Collection.class), Mockito.any(SecurityUtil.UserContext.class))).thenReturn(entityBody1); Mockito.when(mockRightsFilter.makeEntityBody(Mockito.eq(entity2), Mockito.any(List.class), Mockito.any(EntityDefinition.class), Mockito.anyBoolean(), Mockito.any(Collection.class), Mockito.any(SecurityUtil.UserContext.class))).thenReturn(entityBody2); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(false), Matchers.eq(entity1), Matchers.eq(SecurityUtil.UserContext.TEACHER_CONTEXT), Matchers.eq(true))).thenReturn(teacherContextRights); ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class); Field contextValidator = BasicService.class.getDeclaredField("contextValidator"); contextValidator.setAccessible(true); contextValidator.set(service, mockContextValidator); Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>(); studentContext.put(entity1.getEntityId(), SecurityUtil.UserContext.TEACHER_CONTEXT); studentContext.put(entity2.getEntityId(), SecurityUtil.UserContext.TEACHER_CONTEXT); Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext); NeutralQuery query = new NeutralQuery(); query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT); RequestUtil.setCurrentRequestId(); Iterable<EntityBody> listResult = service.listBasedOnContextualRoles(query); List<EntityBody> bodies= new ArrayList<EntityBody>(); for (EntityBody body : listResult) { bodies.add(body); } Assert.assertEquals("EntityBody mismatch", entityBody1, bodies.toArray()[0]); Assert.assertEquals("EntityBody mismatch", entityBody2, bodies.toArray()[1]); long count = service.countBasedOnContextualRoles(new NeutralQuery()); Assert.assertEquals(2, count); }
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> create(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(create(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
@SuppressWarnings("unchecked") @Test public void testCreate() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { securityContextInjector.setEducatorContext(); try { Thread.currentThread().sleep(5L); } catch (InterruptedException is) { } RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); try { Thread.currentThread().sleep(5L); } catch (InterruptedException is) { } EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); EntityBody entityBody2 = new EntityBody(); entityBody2.put("studentUniqueStateId", "student2"); List<EntityBody> entityBodies = Arrays.asList(entityBody1, entityBody2); Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>()); Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>()); Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody1), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity1); Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody2), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity2); LOG.debug(ToStringBuilder.reflectionToString(entityBodies, ToStringStyle.MULTI_LINE_STYLE)); try { Thread.currentThread().sleep(5L); } catch (InterruptedException is) { } List<String> listResult = service.create(entityBodies); Assert.assertEquals("EntityBody mismatch", entity1.getEntityId(), listResult.toArray()[0]); Assert.assertEquals("EntityBody mismatch", entity2.getEntityId(), listResult.toArray()[1]); }
BasicService implements EntityService, AccessibilityCheck { @Override public List<String> createBasedOnContextualRoles(List<EntityBody> content) { List<String> entityIds = new ArrayList<String>(); for (EntityBody entityBody : content) { entityIds.add(createBasedOnContextualRoles(entityBody)); } if (entityIds.size() != content.size()) { for (String id : entityIds) { delete(id); } } return entityIds; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
@SuppressWarnings("unchecked") @Test public void testCreateBasedOnContextualRoles() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { securityContextInjector.setEducatorContext(); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); EntityBody entityBody2 = new EntityBody(); entityBody2.put("studentUniqueStateId", "student2"); List<EntityBody> entityBodies = Arrays.asList(entityBody1, entityBody2); Entity entity1 = new MongoEntity("student", "student1", entityBody1, new HashMap<String,Object>()); Entity entity2 = new MongoEntity("student", "student2", entityBody2, new HashMap<String,Object>()); Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody1), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity1); Mockito.when(mockRepo.create(Mockito.eq("student"), Mockito.eq(entityBody2), Mockito.any(Map.class), Mockito.eq("student"))).thenReturn(entity2); List<String> listResult = service.createBasedOnContextualRoles(entityBodies); Assert.assertEquals("EntityBody mismatch", entity1.getEntityId(), listResult.toArray()[0]); Assert.assertEquals("EntityBody mismatch", entity2.getEntityId(), listResult.toArray()[1]); }
BasicService implements EntityService, AccessibilityCheck { protected Collection<GrantedAuthority> getEntityContextAuthorities(Entity entity, boolean isSelf, boolean isRead) { UserContext context = SecurityUtil.getUserContext(); if (context == UserContext.DUAL_CONTEXT) { Map<String, UserContext> entityContext = getEntityContextMap(Arrays.asList(entity), isRead); if (entityContext != null) { context = entityContext.get(entity.getEntityId()); } } return rightAccessValidator.getContextualAuthorities(isSelf, entity, context, isRead); } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
@Test public void testgetEntityContextAuthorities() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException { securityContextInjector.setDualContext(); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); boolean isSelf = true; boolean isRead = true; EntityBody entityBody1 = new EntityBody(); entityBody1.put("studentUniqueStateId", "student1"); Entity student = securityRepo.create(EntityNames.STUDENT, entityBody1); Collection<GrantedAuthority> staffContextRights = SecurityUtil.getSLIPrincipal().getEdOrgContextRights().get(SecurityContextInjector.ED_ORG_ID).get(SecurityUtil.UserContext.STAFF_CONTEXT); Collection<GrantedAuthority> teacherContextRights = SecurityUtil.getSLIPrincipal().getEdOrgContextRights().get(SecurityContextInjector.ED_ORG_ID).get(SecurityUtil.UserContext.TEACHER_CONTEXT); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(isSelf), Matchers.eq(student), Matchers.eq(SecurityUtil.UserContext.STAFF_CONTEXT), Matchers.eq(isRead))).thenReturn(staffContextRights); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.eq(isSelf), Matchers.eq(student), Matchers.eq(SecurityUtil.UserContext.TEACHER_CONTEXT), Matchers.eq(isRead))).thenReturn(teacherContextRights); ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class); Field contextValidator = BasicService.class.getDeclaredField("contextValidator"); contextValidator.setAccessible(true); contextValidator.set(service, mockContextValidator); Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>(); studentContext.put(student.getEntityId(), SecurityUtil.UserContext.STAFF_CONTEXT); Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext); Collection<GrantedAuthority> rights = service.getEntityContextAuthorities(student, isSelf, isRead); Assert.assertEquals(staffContextRights, rights); securityContextInjector.setEducatorContext(); rights = service.getEntityContextAuthorities(student, isSelf, isRead); Assert.assertEquals(teacherContextRights, rights); }
BasicService implements EntityService, AccessibilityCheck { protected Collection<Entity> getResponseEntities(NeutralQuery neutralQuery, boolean isSelf) throws AccessDeniedException { LOG.debug(">>>BasicService.getResponseEntities()"); Collection<Entity> responseEntities = new ArrayList<Entity>(); Map<String, UserContext> entityContexts = new HashMap<String, UserContext>(); final int limit = neutralQuery.getLimit(); final int offset = neutralQuery.getOffset(); final int responseLimit = ((0 < limit) && (limit < getCountLimit())) ? limit : (int) getCountLimit(); long accessibleCount = 0; int currentOffset = 0; int totalCount = 0; Collection<Entity> batchedEntities; do { batchedEntities = getBatchedEntities(neutralQuery, getBatchSize(), currentOffset); totalCount += batchedEntities.size(); Map<String, UserContext> batchedEntityContexts = new HashMap<String, UserContext>(); if (SecurityUtil.getUserContext() == UserContext.DUAL_CONTEXT) { batchedEntityContexts = getEntityContextMap(batchedEntities, true); } Iterator<Entity> batchedEntitiesIt = batchedEntities.iterator(); while ((accessibleCount < getCountLimit()) && batchedEntitiesIt.hasNext()) { Entity entity = batchedEntitiesIt.next(); try { validateEntity(entity, isSelf, neutralQuery, batchedEntityContexts); accessibleCount++; if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { responseEntities.add(entity); entityContexts.put(entity.getEntityId(), getEntityContext(entity.getEntityId(), batchedEntityContexts)); } } catch (AccessDeniedException aex) { if (totalCount == 1) { throw aex; } else if ((accessibleCount > offset) && (responseEntities.size() < responseLimit)) { LOG.error(aex.getMessage()); } } } currentOffset += getBatchSize(); } while ((accessibleCount < getCountLimit()) && (batchedEntities.size() == getBatchSize())); neutralQuery.setLimit(limit); neutralQuery.setOffset(offset); if ((totalCount > 0) && (accessibleCount == 0)) { validateQuery(neutralQuery, isSelf); throw new APIAccessDeniedException("Access to resource denied."); } setEntityContexts(entityContexts); setAccessibleEntitiesCount(collectionName, accessibleCount); return responseEntities; } BasicService(String collectionName, List<Treatment> treatments, Repository<Entity> repo); @Override long count(NeutralQuery neutralQuery); @Override long countBasedOnContextualRoles(NeutralQuery neutralQuery); @Override List<String> create(List<EntityBody> content); @Override List<String> createBasedOnContextualRoles(List<EntityBody> content); @Override Iterable<String> listIds(final NeutralQuery neutralQuery); @Override String create(EntityBody content); @Override String createBasedOnContextualRoles(EntityBody content); @Override boolean accessibilityCheck(String id); @Override void delete(String id); @Override void deleteBasedOnContextualRoles(String id); @Override boolean update(String id, EntityBody content, boolean applySecurityContext); @Override boolean patch(String id, EntityBody content, boolean applySecurityContext); @Override EntityBody get(String id); @Override EntityBody get(String id, NeutralQuery neutralQuery); @Override Iterable<EntityBody> get(Iterable<String> ids); @Override Iterable<EntityBody> get(Iterable<String> ids, final NeutralQuery neutralQuery); @Override Iterable<EntityBody> list(NeutralQuery neutralQuery); @Override Iterable<EntityBody> listBasedOnContextualRoles(NeutralQuery neutralQuery); @Override boolean exists(String id); @Override EntityBody getCustom(String id); @Override void deleteCustom(String id); @Override void createOrUpdateCustom(String id, EntityBody customEntity); void setDefn(EntityDefinition defn); @Override EntityDefinition getEntityDefinition(); long getCountLimit(); int getBatchSize(); @Override CalculatedData<String> getCalculatedValues(String id); @Override CalculatedData<Map<String, Integer>> getAggregates(String id); @Override boolean collectionExists(String collection); }
@SuppressWarnings("unchecked") @Test public void testGetResponseEntities() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { securityContextInjector.setDualContext(); SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT); List<Entity> entities = new ArrayList<Entity>(); Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>(); for (int i=0; i<30; i++) { String id = "student" + i; entities.add(new MongoEntity("student", id, new HashMap<String,Object>(), new HashMap<String,Object>())); studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities); Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L); ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class); Field contextValidator = BasicService.class.getDeclaredField("contextValidator"); contextValidator.setAccessible(true); contextValidator.set(service, mockContextValidator); Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class), Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean())).thenReturn(studentContext); RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class); Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator"); rightAccessValidator.setAccessible(true); rightAccessValidator.set(service, mockAccessValidator); Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class), Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean())).thenReturn(new HashSet<GrantedAuthority>()); Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(), Mockito.anyCollection()); Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()), Mockito.anyString(), Mockito.anyCollection()); NeutralQuery query = new NeutralQuery(); query.setLimit(ApiQuery.API_QUERY_DEFAULT_LIMIT); Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class, boolean.class); method.setAccessible(true); RequestUtil.setCurrentRequestId(); Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult1 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23"); assertEntityIdsEqual(expectedResult1.iterator(), accessibleEntities.iterator()); long count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); RequestUtil.setCurrentRequestId(); accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult2 = Arrays.asList("student2", "student4", "student5", "student6", "student13", "student16", "student17", "student18", "student22", "student23"); assertEntityIdsEqual(expectedResult2.iterator(), accessibleEntities.iterator()); count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); query.setOffset(7); RequestUtil.setCurrentRequestId(); accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult3 = Arrays.asList("student18", "student22", "student23"); assertEntityIdsEqual(expectedResult3.iterator(), accessibleEntities.iterator()); count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); query.setOffset(7); RequestUtil.setCurrentRequestId(); accessibleEntities = (Collection<Entity>) method.invoke(service, query, false); Iterable<String> expectedResult4 = Arrays.asList("student18", "student22", "student23"); assertEntityIdsEqual(expectedResult4.iterator(), accessibleEntities.iterator()); count = service.getAccessibleEntitiesCount("student"); Assert.assertEquals(10, count); }
Selector2MapOfMaps implements SelectionConverter { public Map<String, Object> convert(String selectorString) throws SelectorParseException { Map<String, Object> converted = new HashMap<String, Object>(); Matcher matcher = SELECTOR_PATTERN.matcher(selectorString); if (matcher.find()) { int groups = matcher.groupCount(); for (int i = 0; i < groups; i++) { String data = matcher.group(i + 1); while (!data.isEmpty()) { int indexOfComma = data.indexOf(","); int indexOfParen = data.indexOf("("); if (indexOfComma == -1 && indexOfParen == -1) { parseKeyAndAddValueToMap(data, converted); data = ""; } else if (indexOfComma == -1) { String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1); addKeyValueToMap(key, convert(value), converted); data = ""; } else if (indexOfParen == -1) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else if (indexOfComma < indexOfParen) { String value = data.substring(0, indexOfComma); parseKeyAndAddValueToMap(value, converted); data = data.substring(indexOfComma + 1); } else { int endOfSubMap = getMatchingClosingParenIndex(data, indexOfParen); String key = data.substring(0, indexOfParen - 1); String value = data.substring(indexOfParen - 1, endOfSubMap + 1); addKeyValueToMap(key, convert(value), converted); data = data.substring(endOfSubMap + 1); if (data.startsWith(",")) { data = data.substring(1); } } } } } else { throw new SelectorParseException("Invalid selector syntax"); } return converted; } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
@Test(expected = SelectorParseException.class) public void testDollarSignThrowsExceptionWhenNotExpected() { this.selectionConverter.convert(":($)"); } @Test(expected = SelectorParseException.class) public void testNestedDollarSignThrowsExceptionWhenNotExpected() { this.selectionConverter.convert(":(foo:($))"); } @Test public void testDollarSignDoesNotThrowExceptionWhenExpected() { SelectionConverter mySelectionConverter = new Selector2MapOfMaps(false); Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("$", true); Map<String, Object> convertResult = mySelectionConverter.convert(":($)"); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); } @Test public void testBasicWildcard() throws SelectorParseException { Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("*", true); Map<String, Object> convertResult = this.selectionConverter.convert(":( * )".replaceAll(" ", "")); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); } @Test public void testBasicString() throws SelectorParseException { Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("name", true); expectedResult.put("sectionAssociations", true); Map<String, Object> convertResult = this.selectionConverter.convert(":( name, sectionAssociations )".replaceAll(" ", "")); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); } @Test public void testTwiceNestedString() throws SelectorParseException { Map<String, Object> convertResult = this.selectionConverter.convert(":( name, sectionAssociations : ( studentId , sectionId : ( * ) ) )".replaceAll(" ", "")); Map<String, Object> sectionIdMap = new HashMap<String, Object>(); sectionIdMap.put("*", true); Map<String, Object> sectionAssociationsMap = new HashMap<String, Object>(); sectionAssociationsMap.put("studentId", true); sectionAssociationsMap.put("sectionId", sectionIdMap); Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("name", true); expectedResult.put("sectionAssociations", sectionAssociationsMap); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); } @Test public void testExcludingFeaturesFromWildcardSelection() throws SelectorParseException { Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("*", true); expectedResult.put("sequenceOfCourse", false); Map<String, Object> convertResult = this.selectionConverter.convert(":( *, sequenceOfCourse:false )".replaceAll(" ", "")); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); } @Test public void veryNestedTest() throws SelectorParseException { String selectorString = ":(foo:(bar),foo2:(bar2:true),foo3:(bar3:false),foo4:(bar4:(*,foobar5:false)))"; Map<String, Object> fooMap = new HashMap<String, Object>(); fooMap.put("bar", true); Map<String, Object> foo2Map = new HashMap<String, Object>(); foo2Map.put("bar2", true); Map<String, Object> foo3Map = new HashMap<String, Object>(); foo3Map.put("bar3", false); Map<String, Object> foo4Map = new HashMap<String, Object>(); Map<String, Object> bar4Map = new HashMap<String, Object>(); bar4Map.put("*", true); bar4Map.put("foobar5", false); foo4Map.put("bar4", bar4Map); Map<String, Object> expectedResult = new HashMap<String, Object>(); expectedResult.put("foo", fooMap); expectedResult.put("foo2", foo2Map); expectedResult.put("foo3", foo3Map); expectedResult.put("foo4", foo4Map); Map<String, Object> convertResult = this.selectionConverter.convert(selectorString); assertTrue(convertResult != null); assertTrue(convertResult.equals(expectedResult)); } @Test(expected = SelectorParseException.class) public void testInvalidSyntax() throws SelectorParseException { this.selectionConverter.convert(":("); } @Test(expected = SelectorParseException.class) public void testEmptyStrings() throws SelectorParseException { this.selectionConverter.convert(":(,,)"); } @Test(expected = SelectorParseException.class) public void testUnbalancedParens3() throws SelectorParseException { String selectorString = ":(name,sectionAssociations)"; String unbalancedString = selectorString + ")"; this.selectionConverter.convert(unbalancedString); } @Test(expected = SelectorParseException.class) public void testEmptyStringForKey() throws SelectorParseException { String selectorString = ":(:(test))"; this.selectionConverter.convert(selectorString); } @Test(expected = SelectorParseException.class) public void testNonTrueFalseValueParsing() throws SelectorParseException { String selectorString = ":(someField:tru)"; this.selectionConverter.convert(selectorString); }
Selector2MapOfMaps implements SelectionConverter { protected static int getMatchingClosingParenIndex(String string, int openParenIndex) throws SelectorParseException { int balance = 0; for (int i = openParenIndex; i < string.length(); i++) { switch(string.charAt(i)) { case '(' : balance++; break; case ')' : balance--; if (balance == 0) { return i; } else if (balance < 0) { throw new SelectorParseException("Invalid parentheses"); } } } throw new SelectorParseException("Unbalanced parentheses"); } Selector2MapOfMaps(); Selector2MapOfMaps(boolean errorOnDollarSign); Map<String, Object> convert(String selectorString); static final String SELECTOR_REGEX_STRING; static final Pattern SELECTOR_PATTERN; }
@Test(expected = SelectorParseException.class) public void testUnbalancedParens() throws SelectorParseException { Selector2MapOfMaps.getMatchingClosingParenIndex("((", 0); } @Test(expected = SelectorParseException.class) public void testUnbalancedParens2() throws SelectorParseException { Selector2MapOfMaps.getMatchingClosingParenIndex(")", 0); }
DefaultUsersService { public List<Dataset> getAvailableDatasets() { return datasets; } @PostConstruct void postConstruct(); List<Dataset> getAvailableDatasets(); List<DefaultUser> getUsers(String dataset); DefaultUser getUser(String dataset, String userId); }
@Test public void testGetAvailableDatasets() { service.setDatasetList("one,List One,two,List Two"); service.initDatasets(); List<Dataset> result = service.getAvailableDatasets(); assertEquals(2, result.size()); assertEquals("List One",result.get(0).getDisplayName()); assertEquals("one",result.get(0).getKey()); assertEquals("List Two",result.get(1).getDisplayName()); assertEquals("two",result.get(1).getKey()); }
UriInfoToApiQueryConverter { public ApiQuery convert(ApiQuery apiQuery, URI requestURI) { if (requestURI == null) { return apiQuery; } return convert(apiQuery, requestURI.getQuery()); } UriInfoToApiQueryConverter(); ApiQuery convert(ApiQuery apiQuery, URI requestURI); ApiQuery convert(ApiQuery apiQuery, UriInfo uriInfo); ApiQuery convert(ApiQuery apiQuery, String queryString); ApiQuery convert(UriInfo uriInfo); }
@Test public void testNonNullForNull() { assertTrue(QUERY_CONVERTER.convert(null) != null); } @Test (expected = QueryParseException.class) public void testPreventionOfNegativeLimit() throws URISyntaxException { String queryString = "limit=-1"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); QUERY_CONVERTER.convert(uriInfo); } @Test(expected = QueryParseException.class) public void testPreventionOfNegativeOffset() throws URISyntaxException { String queryString = "offset=-1"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); QUERY_CONVERTER.convert(uriInfo); } @Test(expected = QueryParseException.class) public void testSelectorShouldFail() throws URISyntaxException { String queryString = "selector=:(students)"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); QUERY_CONVERTER.convert(uriInfo); } @Test(expected = QueryParseException.class) public void testInvalidSelector() { try { String queryString = "selector=true"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); } @Test(expected = QueryParseException.class) public void testInvalidOffset() { try { String queryString = "offset=four"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); } @Test(expected = QueryParseException.class) public void testInvalidLimit() { try { String queryString = "limit=four"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); } @Test(expected = QueryParseException.class) public void testQueryStringMissingKey() { try { String queryString = "=4"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); } @Test(expected = QueryParseException.class) public void testQueryStringMissingOperator() { try { String queryString = "key4"; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); } @Test(expected = QueryParseException.class) public void testQueryStringMissingValue() { try { String queryString = "key="; URI requestUri = new URI(URI_STRING + "?" + queryString); when(uriInfo.getRequestUri()).thenReturn(requestUri); } catch (URISyntaxException urise) { assertTrue(false); } QUERY_CONVERTER.convert(uriInfo); }
DefaultUsersService { public DefaultUser getUser(String dataset, String userId) { for (DefaultUser user : getUsers(dataset)) { if (user.getUserId().equals(userId)) { return user; } } return null; } @PostConstruct void postConstruct(); List<Dataset> getAvailableDatasets(); List<DefaultUser> getUsers(String dataset); DefaultUser getUser(String dataset, String userId); }
@Test public void testGetUser() { service.setDatasetList("TestDataset,The Test Dataset"); service.initDatasets(); service.initUserLists(); DefaultUser user = service.getUser("TestDataset", "linda.kim"); assertEquals("linda.kim", user.getUserId()); }
ApiQuery extends NeutralQuery { @Override public String toString() { StringBuilder stringBuffer = new StringBuilder("offset=" + getOffset() + "&limit=" + getLimit()); if (getIncludeFields() != null) { stringBuffer.append("&includeFields=" + StringUtils.join(getIncludeFields(), ",")); } if (getExcludeFields() != null) { stringBuffer.append("&excludeFields=" + StringUtils.join(getExcludeFields(), ",")); } if (getSortBy() != null) { stringBuffer.append("&sortBy=" + getSortBy()); } if (getSortOrder() != null) { stringBuffer.append("&sortOrder=" + getSortOrder()); } if (this.selector != null) { stringBuffer.append("&selector=" + this.toSelectorString(this.selector)); } for (NeutralCriteria neutralCriteria : getCriteria()) { stringBuffer.append("&" + neutralCriteria.getKey() + neutralCriteria.getOperator() + neutralCriteria.getValue()); } return stringBuffer.toString(); } ApiQuery(UriInfo uriInfo); ApiQuery(String entityType, URI requestURI); ApiQuery(URI requestURI); ApiQuery(); @Override String toString(); Map<String, Object> getSelector(); void setSelector(Map<String, Object> selector); String getEntityType(); static final int API_QUERY_DEFAULT_LIMIT; static final Map<String, Object> DEFAULT_SELECTOR; }
@Test public void testToString() throws URISyntaxException { List<String> equivalentStrings = new ArrayList<String>(); equivalentStrings.add("offset=0&limit=50"); equivalentStrings.add("offset=0&limit=50"); equivalentStrings.add("offset=0&limit=50"); equivalentStrings.add("offset=0&limit=50"); URI requestUri = new URI(URI_STRING); when(uriInfo.getRequestUri()).thenReturn(requestUri); ApiQuery apiQuery = new ApiQuery(uriInfo); assertTrue(equivalentStrings.contains(apiQuery.toString())); }
CustomEntityValidator { public List<ValidationError> validate(EntityBody entityBody) { List<ValidationError> errorList = new ArrayList<ValidationError>(); if (!entityBody.isEmpty()) { validate(entityBody, errorList); } return errorList; } List<ValidationError> validate(EntityBody entityBody); }
@Test public void testEmptyEntity() { EntityBody emptyCustomEntity = new EntityBody(); List<ValidationError> validationErrors = customEntityValidator.validate(emptyCustomEntity); Assert.assertTrue("There should be no validation errors", validationErrors.isEmpty()); } @Test public void testValidFieldName() { String validCustomEntityId = "validCustomEntity1"; EntityBody validCustomEntity = new EntityBody(); validCustomEntity.put("ID", validCustomEntityId); validCustomEntity.put("goodFieldName", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(validCustomEntity); Assert.assertTrue("There should be no validation errors", validationErrors.isEmpty()); } @SuppressWarnings("serial") @Test public void testMultipleNestedValidFieldNames() { final String validCustomEntityId = "validCustomEntity2"; EntityBody validCustomEntity = new EntityBody() { { put("ID", validCustomEntityId); put("goodFieldName1", "goodFieldValue"); put("goodFieldName2", new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); put("goodSubFieldName2", "goodFieldValue"); put("goodSubFieldName3", new LinkedList<HashMap<String, Object>>() { { add(new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); } }); add(new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); put("goodSubFieldName2", new HashMap[] { new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); } }, new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); put("goodSubFieldName2", "goodFieldValue"); } } }); } }); } }); } }); } }; List<ValidationError> validationErrors = customEntityValidator.validate(validCustomEntity); Assert.assertTrue("There should be no validation errors", validationErrors.isEmpty()); } @Test public void testInvalidFieldNameConsistingOfNullChar() { String invalidCustomEntityId = "invalidCustomEntity1"; EntityBody invalidCustomEntity = new EntityBody(); invalidCustomEntity.put("ID", invalidCustomEntityId); invalidCustomEntity.put("\u0000", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "\u0000", "\u0000", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); } @Test public void testInvalidFieldNameConsistingOfNullString() { String invalidCustomEntityId = "invalidCustomEntity2"; EntityBody invalidCustomEntity = new EntityBody(); invalidCustomEntity.put("ID", invalidCustomEntityId); invalidCustomEntity.put("\\x00", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "\\x00", "\\x00", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); } @Test public void testInvalidFieldNameContainingNullChar() { String invalidCustomEntityId = "invalidCustomEntity3"; EntityBody invalidCustomEntity = new EntityBody(); invalidCustomEntity.put("ID", invalidCustomEntityId); invalidCustomEntity.put("bad\u0000FieldName", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\u0000FieldName", "bad\u0000FieldName", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); } @Test public void testInvalidFieldNameContainingNullString() { String invalidCustomEntityId = "invalidCustomEntity4"; EntityBody invalidCustomEntity = new EntityBody(); invalidCustomEntity.put("ID", invalidCustomEntityId); invalidCustomEntity.put("bad\\x00FieldName", "goodFieldValue"); List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\\x00FieldName", "bad\\x00FieldName", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); } @SuppressWarnings("serial") @Test public void testInvalidNestedFieldNameInMap() { final String invalidCustomEntityId = "invalidCustomEntity5"; EntityBody invalidCustomEntity = new EntityBody() { { put("ID", invalidCustomEntityId); put("nestedFieldName", new HashMap<String, Object>() { { put("goodFieldName", "goodFieldValue"); put("bad\u0011FieldName", "goodFieldValue"); } }); } }; List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 1 validation error", 1, validationErrors.size()); ValidationError ve = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\u0011FieldName", "bad\u0011FieldName", null); Assert.assertEquals("Mismatched validation error", ve.toString(), validationErrors.get(0).toString()); } @SuppressWarnings("serial") @Test public void testMultipleNestedInvalidFieldNames() { final String invalidCustomEntityId = "invalidCustomEntity6"; EntityBody invalidCustomEntity = new EntityBody() { { put("ID", invalidCustomEntityId); put("FSCommand = DEL", "goodFieldValue"); put("nestedField", new HashMap<String, Object>() { { put("goodFieldName1", "goodFieldValue"); put("bad\u0000FieldName2", "goodFieldValue"); put("goodFieldName2", new LinkedList<HashMap<String, Object>>() { { add(new HashMap<String, Object>() { { put("goodSubFieldName1", "goodFieldValue"); } }); add(new HashMap<String, Object>() { { put("goodSubFieldName2", "goodFieldValue"); put("bad\\x00FieldName3", new HashMap[] { new HashMap<String, Object>() { { put("goodSubFieldName", "goodFieldValue"); } }, new HashMap<String, Object>() { { put("goodSubFieldName3", "goodFieldValue"); put("bad\u007FFieldName4", "goodFieldValue"); } } }); } }); } }); } }); } }; List<ValidationError> validationErrors = customEntityValidator.validate(invalidCustomEntity); Assert.assertEquals("Should be 4 validation errors", 4, validationErrors.size()); ValidationError ve1 = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "FSCommand = DEL", "FSCommand = DEL", null); ValidationError ve2 = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\u0000FieldName2", "bad\u0000FieldName2", null); ValidationError ve3 = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\\x00FieldName3", "bad\\x00FieldName3", null); ValidationError ve4 = new ValidationError(ValidationError.ErrorType.INVALID_FIELD_NAME, "bad\u007FFieldName4", "bad\u007FFieldName4", null); assertValidationErrorIsInList(validationErrors, ve1); assertValidationErrorIsInList(validationErrors, ve2); assertValidationErrorIsInList(validationErrors, ve3); assertValidationErrorIsInList(validationErrors, ve4); }
Login { @RequestMapping(value = "/logout") public ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession) { httpSession.removeAttribute(USER_SESSION_KEY); if(encodedSamlRequest!=null){ ModelAndView mav = form(encodedSamlRequest, realm, developer, httpSession); mav.addObject("msg", "You are now logged out"); return mav; }else{ return new ModelAndView("loggedOut"); } } @RequestMapping(value = "/logout") ModelAndView logout(@RequestParam(value="SAMLRequest", required=false) String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession); @RequestMapping(value = "/", method = RequestMethod.GET) ModelAndView form(@RequestParam("SAMLRequest") String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession); @RequestMapping(value= "/admin", method = RequestMethod.POST) ModelAndView admin(@RequestParam("SAMLRequest") String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, HttpSession httpSession); @RequestMapping(value = "/login", method = RequestMethod.POST) ModelAndView login( @RequestParam("user_id") String userId, @RequestParam("password") String password, @RequestParam("SAMLRequest") String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "developer", required = false) String developer, HttpSession httpSession, HttpServletRequest request); @SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping(value = "/impersonate", method = RequestMethod.POST) ModelAndView impersonate( @RequestParam("SAMLRequest") String encodedSamlRequest, @RequestParam(value = "realm", required = false) String realm, @RequestParam(value = "impersonate_user", required = false) String impersonateUser, @RequestParam(value = "selected_roles", required = false) List<String> roles, @RequestParam(value = "customRoles", required = false) String customRoles, @RequestParam(value = "selected_type", required = false) String userType, @RequestParam(value = "datasets", required = false) String dataset, @RequestParam(value = "userList", required = false) String datasetUser, @RequestParam(value = "manualConfig", required = false) boolean manualConfig, HttpSession httpSession, HttpServletRequest request); }
@Test public void testLogoutNoSaml() { ModelAndView mav = loginController.logout(null, null, null, httpSession); Mockito.verify(httpSession, Mockito.times(1)).removeAttribute("user_session_key"); assertEquals("loggedOut", mav.getViewName()); } @Test public void testLogoutWithSaml() { ModelAndView mav = loginController.logout("SAMLRequest", "realm", null, httpSession); assertEquals("You are now logged out", mav.getModel().get("msg")); assertEquals("login", mav.getViewName()); Mockito.verify(httpSession, Mockito.times(1)).removeAttribute("user_session_key"); }
SuperAdminService { public Set<String> getAllowedEdOrgs(String tenant, String edOrg) { return getAllowedEdOrgs(tenant, edOrg, null, false); } Set<String> getAllowedEdOrgs(String tenant, String edOrg); Set<String> getAllowedEdOrgs(final String tenant, final String edOrg, final Collection<String> interestedTypes, boolean strict); static final String STATE_EDUCATION_AGENCY; static final String LOCAL_EDUCATION_AGENCY; }
@Test public void testGetAllowedEdOrgs() { Mockito.when(secUtil.getTenantId()).thenReturn("TENANT"); Entity user = Mockito.mock(Entity.class); HashMap<String, Object> body = new HashMap<String, Object>(); body.put("stateOrganizationId", "ID"); body.put("organizationCategories", Arrays.asList("State Education Agency")); Mockito.when(user.getBody()).thenReturn(body); Mockito.when(repo.findAll(Mockito.eq(EntityNames.EDUCATION_ORGANIZATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(user)); Set<String> edOrgs = service.getAllowedEdOrgs(null, null); Assert.assertEquals(new HashSet<String>(Arrays.asList("ID")), edOrgs); Entity edOrg = Mockito.mock(Entity.class); Mockito.when(edOrg.getEntityId()).thenReturn("EDORGID"); Mockito.when(repo.findOne(Mockito.eq(EntityNames.EDUCATION_ORGANIZATION), Mockito.any(NeutralQuery.class))) .thenReturn(edOrg); edOrgs = service.getAllowedEdOrgs("TENANT", null); }
RightAccessValidator { public Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead){ Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); SLIPrincipal principal = SecurityUtil.getSLIPrincipal(); if (SecurityUtil.isStaffUser()) { if (entity == null) { LOG.trace("No authority for null"); } else { if ((entity.getMetaData() != null && SecurityUtil.principalId().equals(entity.getMetaData().get("createdBy")) && "true".equals(entity.getMetaData().get("isOrphaned"))) || (EntityNames.isPublic(entity.getType()) && !edOrgOwnershipArbiter.isEntityOwnedByEdOrg(entity.getType())) ) { auths.addAll(principal.getAllContextRights(isSelf)); } else if(EntityNames.isPublic(entity.getType()) && principal.getAllContextRights(isSelf).contains(Right.READ_PUBLIC) && isRead) { auths.add(Right.READ_PUBLIC); } else { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(principal.getEdOrgContextRights(), entity, context, isRead)); } if (isSelf) { auths.addAll(entityEdOrgRightBuilder.buildEntityEdOrgRights(principal.getEdOrgSelfRights(), entity, isRead)); } } } else { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); auths.addAll(auth.getAuthorities()); if (isSelf) { auths.addAll(principal.getSelfRights()); } } return auths; } void checkAccess(boolean isRead, boolean isSelf, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, String entityId, EntityBody content, String entityType, String collectionName, Repository<Entity> repo, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths); void checkAccess(boolean isRead, EntityBody entityBody, String entityType, Collection<GrantedAuthority> auths, Entity entity); void checkFieldAccess(NeutralQuery query, Entity entity, String entityType, Collection<GrantedAuthority> auths); void checkFieldAccess(NeutralQuery query, String entityType, Collection<GrantedAuthority> auths); Collection<GrantedAuthority> getContextualAuthorities(boolean isSelf, Entity entity, SecurityUtil.UserContext context, boolean isRead); Set<Right> getNeededRights(String fieldPath, String entityType); boolean intersection(Collection<GrantedAuthority> authorities, Set<Right> neededRights); void checkSecurity(boolean isRead, String entityId, String entityType, String collectionName, Repository<Entity> repo); boolean isEntityAllowed(String entityId, String collectionName, String toType, Repository<Entity> repo); }
@Test public void testGetContextualAuthoritiesStaffOrphan() { String principalId = "SuperTeacher1"; Entity princEntity = new MongoEntity(null, principalId, new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(princEntity); principal.setUserType(EntityNames.STAFF); EdOrgContextRightsCache edOrgContextRights = createEdOrgContextRights(); principal.setEdOrgContextRights(edOrgContextRights); securityContextInjector.setOauthSecurityContext(principal, false); Map<String,Object> metaData = new HashMap<String,Object>(); metaData.put("createdBy", principalId); metaData.put("isOrphaned", "true"); Entity entity = new MongoEntity("student", null, new HashMap<String,Object>(), metaData); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, entity, SecurityUtil.UserContext.STAFF_CONTEXT,false); Assert.assertEquals("Expected all rights", ALL_AUTHS, auths); } @SuppressWarnings("unchecked") @Test public void testGetContextualAuthoritiesStaffMatchingEdOrgs() { Entity princEntity = new MongoEntity(null, "SuperTeacher2", new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(princEntity); principal.setUserType(EntityNames.STAFF); EdOrgContextRightsCache edOrgContextRights = createEdOrgContextRights(); principal.setEdOrgContextRights(edOrgContextRights); securityContextInjector.setOauthSecurityContext(principal, false); Entity student = createEntity(EntityNames.STUDENT, STUDENT_ID, new HashMap<String, Object>()); Mockito.when(entityEdOrgRightBuilder.buildEntityEdOrgContextRights(edOrgContextRights, student, SecurityUtil.UserContext.STAFF_CONTEXT,false)).thenReturn(ADMIN_AUTHS); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, student, SecurityUtil.UserContext.STAFF_CONTEXT, false); Assert.assertEquals("Expected administrator rights", ADMIN_AUTHS, auths); } @Test public void testGetContextualAuthoritiesStaffNoMatchingEdOrgs() { Map<String, Collection<GrantedAuthority>> edOrgRights = new HashMap<String, Collection<GrantedAuthority>>(); Entity princEntity = new MongoEntity(null, "RegularTeacher1", new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(princEntity); principal.setUserType(EntityNames.STAFF); securityContextInjector.setOauthSecurityContext(principal, false); Entity student = createEntity(EntityNames.STUDENT, STUDENT_ID, new HashMap<String, Object>()); Mockito.when(entityEdOrgRightBuilder.buildEntityEdOrgRights(edOrgRights, student, false)).thenReturn(NO_AUTHS); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, student, SecurityUtil.UserContext.STAFF_CONTEXT,false); Assert.assertEquals("Expected no rights", NO_AUTHS, auths); } @Test public void testGetContextualAuthoritiesNonStaff() { String token = "AQIC5wM2LY4SfczsoqTgHpfSEciO4J34Hc5ThvD0QaM2QUI.*AAJTSQACMDE.*"; Entity princEntity = new MongoEntity(null, "RegularTeacher2", new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setUserType(EntityNames.TEACHER); principal.setEntity(princEntity); PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(principal, token, EDU_AUTHS); SecurityContextHolder.getContext().setAuthentication(authenticationToken); Entity entity = new MongoEntity("student", null, new HashMap<String,Object>(), new HashMap<String,Object>()); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, entity, SecurityUtil.UserContext.TEACHER_CONTEXT,false); Assert.assertEquals("Expected educator rights", EDU_AUTHS, auths); } @Test public void testGetContextualAuthoritiesNonStaffSelf() { String token = "AQIC5wM2LY4SfczsoqTgHpfSEciO4J34Hc5ThvD0QaM2QUI.*AAJTSQACMDE.*"; Entity princEntity = new MongoEntity(null, "RegularTeacher3", new HashMap<String,Object>(), new HashMap<String,Object>()); SLIPrincipal principal = new SLIPrincipal(); principal.setEntity(princEntity); principal.setUserType(EntityNames.TEACHER); principal.setSelfRights(ADMIN_AUTHS); PreAuthenticatedAuthenticationToken authenticationToken = new PreAuthenticatedAuthenticationToken(principal, token, EDU_AUTHS); SecurityContextHolder.getContext().setAuthentication(authenticationToken); Entity entity = new MongoEntity("teacher", null, new HashMap<String,Object>(), new HashMap<String,Object>()); Collection<GrantedAuthority> auths = service.getContextualAuthorities(true, entity, SecurityUtil.UserContext.TEACHER_CONTEXT,false); Assert.assertEquals("Expected all rights", ALL_AUTHS, auths); } @Test public void testGetContextualAuthoritiesNullEntity() { securityContextInjector.setEducatorContext(); Collection<GrantedAuthority> auths = service.getContextualAuthorities(false, null, SecurityUtil.UserContext.TEACHER_CONTEXT,false); Assert.assertEquals("Expected no rights", NO_AUTHS, auths); }
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgRights.keySet(), entity, isRead); } for (String edorg : edorgs) { authorities.addAll(edOrgRights.get(edorg)); } return authorities; } Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead); Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead); void setEdOrgOwnershipArbiter(EdOrgOwnershipArbiter edOrgOwnershipArbiter); }
@SuppressWarnings("unchecked") @Test public void testBuildEntityEdOrgRights() { Set<String> edOrgs = new HashSet<String>(); edOrgs.add("edOrg1"); edOrgs.add("edOrg2"); edOrgs.add("edOrg3"); edOrgs.add("edOrg4"); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("student"); Mockito.when(edOrgOwnershipArbiter.determineHierarchicalEdorgs(Matchers.anyList(), Matchers.anyString())).thenReturn(edOrgs); Collection<GrantedAuthority> grantedAuthorities = entityEdOrgRightBuilder.buildEntityEdOrgRights(edOrgRights, entity, false); Assert.assertEquals(5, grantedAuthorities.size()); Assert.assertTrue(grantedAuthorities.contains(READ_PUBLIC)); Assert.assertTrue(grantedAuthorities.contains(READ_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(READ_RESTRICTED)); Assert.assertTrue(grantedAuthorities.contains(WRITE_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(WRITE_RESTRICTED)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_READ)); Assert.assertFalse(grantedAuthorities.contains(WRITE_PUBLIC)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_WRITE)); }
EntityEdOrgRightBuilder { public Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead) { Collection<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); Set<String> edorgs = edOrgOwnershipArbiter.determineHierarchicalEdorgs(Arrays.asList(entity), entity.getType()); edorgs.retainAll(edOrgContextRights.keySet()); if (edorgs.isEmpty()) { edorgs = getEdOrgsForStudent(edOrgContextRights.keySet(), entity, isRead); } for (String edorg : edorgs) { switch (context) { case DUAL_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; case STAFF_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.STAFF_CONTEXT.name())); break; case TEACHER_CONTEXT: authorities.addAll(edOrgContextRights.get(edorg).get(Right.TEACHER_CONTEXT.name())); break; } if(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name()) != null) { authorities.addAll(edOrgContextRights.get(edorg).get(Right.APP_AUTHORIZE.name())); } } return authorities; } Collection<GrantedAuthority> buildEntityEdOrgRights(final Map<String, Collection<GrantedAuthority>> edOrgRights, final Entity entity, boolean isRead); Collection<GrantedAuthority> buildEntityEdOrgContextRights(final EdOrgContextRightsCache edOrgContextRights, final Entity entity, final SecurityUtil.UserContext context, boolean isRead); void setEdOrgOwnershipArbiter(EdOrgOwnershipArbiter edOrgOwnershipArbiter); }
@SuppressWarnings("unchecked") @Test public void testBuildEntityEdOrgDualContextRights() { Set<String> edOrgs = new HashSet<String>(); edOrgs.add("edOrg1"); edOrgs.add("edOrg2"); edOrgs.add("edOrg3"); edOrgs.add("edOrg4"); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("student"); Mockito.when(edOrgOwnershipArbiter.determineHierarchicalEdorgs(Matchers.anyList(), Matchers.anyString())).thenReturn(edOrgs); Collection<GrantedAuthority> grantedAuthorities = entityEdOrgRightBuilder.buildEntityEdOrgContextRights(edOrgContextRights, entity, SecurityUtil.UserContext.DUAL_CONTEXT, false); Assert.assertEquals(6, grantedAuthorities.size()); Assert.assertTrue(grantedAuthorities.contains(READ_PUBLIC)); Assert.assertTrue(grantedAuthorities.contains(READ_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(READ_RESTRICTED)); Assert.assertTrue(grantedAuthorities.contains(WRITE_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(STAFF_CONTEXT)); Assert.assertTrue(grantedAuthorities.contains(TEACHER_CONTEXT)); Assert.assertFalse(grantedAuthorities.contains(WRITE_RESTRICTED)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_READ)); Assert.assertFalse(grantedAuthorities.contains(WRITE_PUBLIC)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_WRITE)); } @SuppressWarnings("unchecked") @Test public void testBuildEntityEdOrgSingleContextRights() { Set<String> edOrgs = new HashSet<String>(); edOrgs.add("edOrg1"); edOrgs.add("edOrg2"); edOrgs.add("edOrg3"); edOrgs.add("edOrg4"); Entity entity = Mockito.mock(Entity.class); Mockito.when(entity.getType()).thenReturn("student"); Mockito.when(edOrgOwnershipArbiter.determineHierarchicalEdorgs(Matchers.anyList(), Matchers.anyString())).thenReturn(edOrgs); Collection<GrantedAuthority> grantedAuthorities = entityEdOrgRightBuilder.buildEntityEdOrgContextRights(edOrgContextRights, entity, SecurityUtil.UserContext.TEACHER_CONTEXT, false); Assert.assertEquals(4, grantedAuthorities.size()); Assert.assertTrue(grantedAuthorities.contains(READ_PUBLIC)); Assert.assertTrue(grantedAuthorities.contains(READ_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(WRITE_GENERAL)); Assert.assertTrue(grantedAuthorities.contains(TEACHER_CONTEXT)); Assert.assertFalse(grantedAuthorities.contains(READ_RESTRICTED)); Assert.assertFalse(grantedAuthorities.contains(WRITE_RESTRICTED)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_READ)); Assert.assertFalse(grantedAuthorities.contains(WRITE_PUBLIC)); Assert.assertFalse(grantedAuthorities.contains(AGGREGATE_WRITE)); Assert.assertFalse(grantedAuthorities.contains(STAFF_CONTEXT)); }
EntityRightsFilter { @SuppressWarnings("unchecked") protected void filterFields(EntityBody entityBody, Collection<GrantedAuthority> auths, String prefix, String entityType) { if (!auths.contains(Right.FULL_ACCESS)) { List<String> toRemove = new LinkedList<String>(); for (Iterator<Map.Entry<String, Object>> it = entityBody.entrySet().iterator(); it.hasNext();) { String fieldName = it.next().getKey(); Set<Right> neededRights = rightAccessValidator.getNeededRights(prefix + fieldName, entityType); if (!neededRights.isEmpty() && !rightAccessValidator.intersection(auths, neededRights)) { it.remove(); } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
@Test public void testFilterFields() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity student = createStudentEntity(EntityNames.STUDENT, STUDENT_ID); EntityBody sb = new EntityBody(student.getBody()); entityRightsFilter.filterFields(sb, auths, "", EntityNames.STUDENT); Assert.assertEquals(1, sb.size()); Assert.assertEquals(STUDENT_UNIQUE_STATE_ID, sb.get(ParameterConstants.STUDENT_UNIQUE_STATE_ID)); }
EntityRightsFilter { protected void complexFilter(EntityBody entityBody, Collection<GrantedAuthority> auths, String entityType) { if (!auths.contains(Right.READ_RESTRICTED) && (entityType.equals(EntityNames.STAFF) || entityType.equals(EntityNames.TEACHER))) { final String work = "Work"; final String telephoneNumberType = "telephoneNumberType"; final String emailAddressType = "emailAddressType"; final String telephone = "telephone"; final String electronicMail = "electronicMail"; @SuppressWarnings("unchecked") List<Map<String, Object>> telephones = (List<Map<String, Object>>) entityBody.get(telephone); if (telephones != null) { for (Iterator<Map<String, Object>> it = telephones.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(telephoneNumberType))) { it.remove(); } } } @SuppressWarnings("unchecked") List<Map<String, Object>> emails = (List<Map<String, Object>>) entityBody.get(electronicMail); if (emails != null) { for (Iterator<Map<String, Object>> it = emails.iterator(); it.hasNext(); ) { if (!work.equals(it.next().get(emailAddressType))) { it.remove(); } } } } } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
@Test public void testComplexFilterReadGeneral() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); EntityBody sb = new EntityBody(staff.getBody()); entityRightsFilter.complexFilter(sb, auths, EntityNames.STAFF); List<Map<String, Object>> telepone = (List<Map<String, Object>>) sb.get(TELEPONE_FEILD); List<Map<String, Object>> emails = (List<Map<String, Object>>) sb.get(EMAIL_FIELD); Assert.assertEquals(1, telepone.size()); Assert.assertEquals(1, emails.size()); Assert.assertEquals(WORK_PHONE, telepone.get(0).get(TELEPONE_VALUE)); Assert.assertEquals(WORK_EMAIL, emails.get(0).get(EMAIL_VALUE)); } @Test public void testComplexFilterReadRestrict() { Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_RESTRICTED); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); EntityBody sb = new EntityBody(staff.getBody()); entityRightsFilter.complexFilter(sb, auths, EntityNames.STAFF); List<Map<String, Object>> telepone = (List<Map<String, Object>>) sb.get(TELEPONE_FEILD); List<Map<String, Object>> emails = (List<Map<String, Object>>) sb.get(EMAIL_FIELD); Assert.assertEquals(2, telepone.size()); Assert.assertEquals(2, emails.size()); }
EntityRightsFilter { public EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context) { Collection<GrantedAuthority> selfAuths; if (isSelf) { selfAuths = rightAccessValidator.getContextualAuthorities(isSelf, entity, context, true); } else { selfAuths = nonSelfAuths; } return makeEntityBody(entity, treamts, defn, nonSelfAuths, selfAuths); } EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, boolean isSelf, Collection<GrantedAuthority> nonSelfAuths, SecurityUtil.UserContext context); EntityBody makeEntityBody(Entity entity, List<Treatment> treamts, EntityDefinition defn, Collection<GrantedAuthority> nonSelfAuths, Collection<GrantedAuthority> selfAuths); EntityBody exposeTreatments(Entity entity, List<Treatment> treatments, EntityDefinition defn); void setRightAccessValidator(RightAccessValidator rightAccessValidator); }
@Test public void testMakeEntityBody() { Treatment treatment1 = Mockito.mock(Treatment.class); Treatment treatment2 = Mockito.mock(Treatment.class); List<Treatment> treatments = new ArrayList<Treatment>(); treatments.add(treatment1); treatments.add(treatment2); Collection<GrantedAuthority> auths = new HashSet<GrantedAuthority>(); auths.add(Right.READ_GENERAL); Entity student = createStudentEntity(EntityNames.STUDENT, STUDENT_ID); Entity staff = createStaffEntity(EntityNames.STAFF, STAFF_ID); student.getEmbeddedData().put("studentSchoolAssociation", Arrays.asList(staff)); EntityBody sb = new EntityBody(student.getBody()); EntityBody staffBody = new EntityBody(staff.getBody()); Mockito.when(treatment1.toExposed(Matchers.any(EntityBody.class), Matchers.any(EntityDefinition.class), Matchers.any(Entity.class))).thenReturn(sb, staffBody); Mockito.when(treatment2.toExposed(Matchers.any(EntityBody.class), Matchers.any(EntityDefinition.class), Matchers.any(Entity.class))).thenReturn(sb, staffBody); EntityDefinition definition = Mockito.mock(EntityDefinition.class); Mockito.when(definition.getType()).thenReturn("student"); EntityBody res = entityRightsFilter.makeEntityBody(student, treatments, definition, false, auths, SecurityUtil.UserContext.STAFF_CONTEXT); Assert.assertNotNull(res); List<EntityBody> ssa = (List<EntityBody>) res.get("studentSchoolAssociation"); Assert.assertNotNull(ssa); Assert.assertEquals(1, ssa.size()); Assert.assertEquals(STAFF_ID, ssa.get(0).get(ParameterConstants.STAFF_UNIQUE_STATE_ID)); }
EdOrgContextualRoleBuilder { private Map<String, List<String>> buildEdOrgContextualRoles(Set<Entity> seoas, Set<String> samlRoleSet) { Map<String, List<String>> edOrgRoles = new HashMap<String, List<String>>(); if (seoas != null) { for (Entity seoa : seoas) { String edOrgId = (String) seoa.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE); String role = (String) seoa.getBody().get(ParameterConstants.STAFF_EDORG_ASSOC_STAFF_CLASSIFICATION); if(isValidRole(role, samlRoleSet)) { if (edOrgRoles.get(edOrgId) == null) { edOrgRoles.put(edOrgId, new ArrayList<String>()); edOrgRoles.get(edOrgId).add(role); } else if (!edOrgRoles.get(edOrgId).contains(role)) { edOrgRoles.get(edOrgId).add(role); } } } } return edOrgRoles; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
@Test public void testBuildEdOrgContextualRoles () { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "IT Admin")); seoas.add(createSEOA("LEA1", "Educator")); seoas.add(createSEOA("LEA2", "Educator")); seoas.add(createSEOA("LEA2", "Educator")); Set<Role> edOrg1RolesSet = new HashSet<Role>(); edOrg1RolesSet.add(createRole("Educator")); edOrg1RolesSet.add(createRole("IT Admin")); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("Educator", "IT Admin"), false)).thenReturn(edOrg1RolesSet); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("IT Admin", "Educator"), false)).thenReturn(edOrg1RolesSet); Set<Role> edOrg2RolesSet = new HashSet<Role>(); edOrg2RolesSet.add(createRole("Educator")); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("Educator"), false)).thenReturn(edOrg2RolesSet); Mockito.when(edorgHelper.locateNonExpiredSEOAs(staffId)).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId,tenant, samlRoles); Assert.assertNotNull(edOrgRoles); Assert.assertEquals(2,edOrgRoles.size()); List<String> edOrg1Roles = edOrgRoles.get("LEA1"); Assert.assertNotNull(edOrg1Roles); Assert.assertEquals(2, edOrg1Roles.size()); Assert.assertTrue(edOrg1Roles.contains("IT Admin")); Assert.assertTrue(edOrg1Roles.contains("Educator")); List<String> edOrg2Roles = edOrgRoles.get("LEA2"); Assert.assertNotNull(edOrg2Roles); Assert.assertEquals(1, edOrg2Roles.size()); Assert.assertTrue(edOrg2Roles.contains("Educator")); }
EdOrgContextualRoleBuilder { public Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles) { Set<String> samlRoleSet = new HashSet<String>(roles); Set<Entity> staffEdOrgAssoc = edorgHelper.locateNonExpiredSEOAs(staffId); if (staffEdOrgAssoc.size() == 0) { LOG.error("Attempted login by a user that did not include any current valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. User is not currently associated with any school/edorg", true); } Map<String, List<String>> sliEdOrgRoleMap = buildEdOrgContextualRoles(staffEdOrgAssoc, samlRoleSet); if(sliEdOrgRoleMap.isEmpty()) { LOG.error("Attempted login by a user that did not include any valid roles in the SAML Assertion."); throw new APIAccessDeniedException("Invalid user. No valid roles specified for user.", true); } for (Map.Entry<String, List<String>> entry : sliEdOrgRoleMap.entrySet()) { sliEdOrgRoleMap.put(entry.getKey(), getRoleNameList(resolver.mapRoles(tenant, realmId, entry.getValue(), false))); } if (isInValidRoleMap(sliEdOrgRoleMap)) { LOG.error("Attempted login by a user that included no roles in the SAML Assertion that mapped to any of the SLI roles."); throw new APIAccessDeniedException( "Invalid user. No valid role mappings exist for the roles specified in the SAML Assertion.", true); } return sliEdOrgRoleMap; } Map<String, List<String>> buildValidStaffRoles(String realmId, String staffId, String tenant, List<String> roles); }
@Test (expected = AccessDeniedException.class) public void testNoCustomRoleMatch () { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "IT Admin")); seoas.add(createSEOA("LEA1", "Educator")); Set<Role> edOrg1RolesSet = new HashSet<Role>(); Mockito.when(resolver.mapRoles(tenant, realmId, Arrays.asList("Educator", "IT Admin"), false)).thenReturn(edOrg1RolesSet); Mockito.when(edorgHelper.locateNonExpiredSEOAs(staffId)).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId,tenant, samlRoles); Assert.assertNotNull(edOrgRoles); Assert.assertEquals(0,edOrgRoles.size()); } @Test (expected = AccessDeniedException.class) public void testInvalidEdOrgRoles() { Mockito.when(edorgHelper.locateNonExpiredSEOAs(Mockito.anyString())).thenReturn(new HashSet<Entity>()); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId, tenant, samlRoles); Assert.assertNotNull(edOrgRoles); Assert.assertEquals(0,edOrgRoles.size()); } @Test (expected = AccessDeniedException.class) public void noMatchingRoles() { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "Random Role1")); seoas.add(createSEOA("LEA1", "Random Role2")); seoas.add(createSEOA("LEA2", "Random Role2")); Mockito.when(edorgHelper.locateNonExpiredSEOAs(Mockito.anyString())).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId, tenant, samlRoles); Assert.assertTrue(edOrgRoles.isEmpty()); } @Test (expected = AccessDeniedException.class) public void testNoSamlRoles() { Set<Entity> seoas = new HashSet<Entity>(); seoas.add(createSEOA("LEA1", "IT Admin")); seoas.add(createSEOA("LEA1", "Educator")); seoas.add(createSEOA("LEA2", "Educator")); Mockito.when(edorgHelper.locateNonExpiredSEOAs(Mockito.anyString())).thenReturn(seoas); Map<String, List<String>> edOrgRoles = edOrgRoleBuilder.buildValidStaffRoles(realmId, staffId, tenant, new ArrayList<String>()); Assert.assertTrue(edOrgRoles.isEmpty()); }
SamlResponseComposer { public String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles) { String unsignedResponse = createUnsignedResponse(destination, issuer, requestId, userId, attributes, roles); byte[] signedResponse = signResponse(unsignedResponse); return Base64.encodeBase64String(signedResponse); } String componseResponse(String destination, String issuer, String requestId, String userId, Map<String, String> attributes, List<String> roles); }
@Test public void testComposeResponse() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, TransformerException, MarshalException, XMLSignatureException, SAXException, IOException, ParserConfigurationException { Mockito.when(sigHelper.signSamlAssertion(Mockito.any(Document.class))).thenAnswer(new Answer<Document>() { @Override public Document answer(InvocationOnMock invocation) throws Throwable { return (Document) invocation.getArguments()[0]; } }); Map<String, String> attributes = new HashMap<String, String>(); attributes.put("userName", "User Name"); attributes.put("tenant", "tenantId"); attributes.put("edorg", "NC-edorg"); attributes.put("adminRealm", "myrealm"); attributes.put("userType", "staff"); String encodedXml = composer.componseResponse("dest", "issuer", "requestId", "userId", attributes, Arrays.asList("role1", "role2")); String xml = new String(Base64.decodeBase64(encodedXml), "UTF8"); Mockito.verify(sigHelper).signSamlAssertion(Mockito.any(Document.class)); DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setNamespaceAware(true); Document doc = fact.newDocumentBuilder().parse(new InputSource(new StringReader(xml))); assertEquals("dest", doc.getDocumentElement().getAttribute("Destination")); assertEquals("requestId", doc.getDocumentElement().getAttribute("InResponseTo")); assertTrue(hasAttributeValue(doc, "userName", "User Name")); assertTrue(hasAttributeValue(doc, "userId", "userId")); assertTrue(hasAttributeValue(doc, "userType", "staff")); assertTrue(hasAttributeValue(doc, "roles", "role1")); assertTrue(hasAttributeValue(doc, "roles", "role2")); assertTrue(hasAttributeValue(doc, "tenant", "tenantId")); assertTrue(hasAttributeValue(doc, "edorg", "NC-edorg")); assertTrue(hasAttributeValue(doc, "adminRealm", "myrealm")); assertEquals("issuer", xpathOne(doc, "/samlp:Response/saml:Issuer").getTextContent()); assertTrue(xpathOne(doc, "/samlp:Response/@IssueInstant").getTextContent().matches( "\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ")); assertTrue(xpathOne(doc, "/samlp:Response/saml:Assertion/@IssueInstant").getTextContent().matches( "\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ")); assertTrue(!xpathOne(doc, "/samlp:Response/@ID").getTextContent().equals("__RESPONSE_ID__")); assertTrue(!xpathOne(doc, "/samlp:Response/saml:Assertion/@ID").getTextContent().equals("__ASSERTION_ID__")); assertTrue(!xpathOne(doc, "/samlp:Response/@Destination").getTextContent().equals("__DESTINATION__")); assertEquals("requestId", xpathOne(doc, "/samlp:Response/saml:Assertion/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/@InResponseTo").getTextContent()); assertEquals("dest", xpathOne(doc, "/samlp:Response/saml:Assertion/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/@Recipient").getTextContent()); String expDate = xpathOne(doc, "/samlp:Response/saml:Assertion/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/@NotOnOrAfter").getTextContent(); DateTime dt = DateTime.parse(expDate); assertTrue(dt.minusMinutes(9).isAfterNow()); assertTrue(dt.minusMinutes(11).isBeforeNow()); }
MutatedContainer { @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } MutatedContainer rhs = (MutatedContainer) obj; return new EqualsBuilder().append(path, rhs.path) .append(queryParameters, rhs.queryParameters) .append(headers, rhs.headers).isEquals(); } static MutatedContainer generate(String queryParameters, String pathFormat, String... pathArgs); String getPath(); void setPath(String path); String getQueryParameters(); void setQueryParameters(String queryParameters); Map<String, String> getHeaders(); void setHeaders(Map<String, String> headers); boolean isModified(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
@Test public void testEquals() { MutatedContainer m1 = new MutatedContainer(); setParams(m1, "a", "b", null); MutatedContainer m2 = new MutatedContainer(); setParams(m2, "a", "b", null); Assert.assertTrue(m1.equals(m2)); setParams(m1, "a", "b", null); setParams(m2, "c", "b", null); Assert.assertFalse(m1.equals(m2)); setParams(m1, "a", "b", null); setParams(m2, "a", "c", null); Assert.assertFalse(m1.equals(m2)); setParams(m1, "a", "b", new HashMap<String, String>()); setParams(m2, "a", "b", new HashMap<String, String>()); Assert.assertTrue(m1.equals(m2)); setParams(m1, "a", "b", new HashMap<String, String>()); setParams(m2, "a", "b", null); Assert.assertFalse(m1.equals(m2)); HashMap<String, String> h1 = new HashMap<String, String>(); h1.put("1", "1"); HashMap<String, String> h2 = new HashMap<String, String>(); h2.put("1", "2"); setParams(m1, "a", "b", h1); setParams(m2, "a", "b", h2); Assert.assertFalse(m1.equals(m2)); h1 = new HashMap<String, String>(); h1.put("1", "1"); h2 = new HashMap<String, String>(); h2.put("1", "1"); setParams(m1, "a", "b", h1); setParams(m2, "a", "b", h2); Assert.assertTrue(m1.equals(m2)); }
RootSearchMutator { public String mutatePath(String version, String resource, String queryParameters) { String mutatedPath = null; Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String curParameter = parameterResourcePair.getLeft(); String curResource = parameterResourcePair.getRight(); if (parameters.containsKey(curParameter)) { if (isValidPath(version, curResource, resource)) { mutatedPath = "/" + curResource + "/" + parameters.get(curParameter) + "/" + resource; break; } } } return mutatedPath; } String mutatePath(String version, String resource, String queryParameters); }
@Test public void testMutatePath() throws Exception { String expectedPath; String resultPath; resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "studentId=some_id"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "studentId=some_id&something=else"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.ATTENDANCES, "key1=val1&studentId=some_id&key2=val2"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "some_id" + "/" + ResourceNames.ATTENDANCES; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.REPORT_CARDS, "schoolId=school_id&studentId=id1,id2,id3&key2=val2"); expectedPath = "/" + ResourceNames.STUDENTS + "/" + "id1,id2,id3" + "/" + ResourceNames.REPORT_CARDS; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); resultPath = rootSearchMutator.mutatePath("v1.0", ResourceNames.TEACHER_SECTION_ASSOCIATIONS, "schoolId=school_id"); expectedPath = null; Assert.assertEquals("Invalid mutation:", expectedPath, resultPath); }
EndpointMutator { protected String getResourceVersion(List<PathSegment> segments, MutatedContainer mutated) { String version = segments.get(0).getPath(); if (mutated.getPath() != null && mutated.getPath().startsWith("/" + ResourceNames.SEARCH + "/") && VERSION_1_0.equals(version)) { return VERSION_1_1; } return version; } void mutateURI(Authentication auth, ContainerRequest request); }
@Test public void testGetResourceVersionForSearch() { List<PathSegment> segments = getPathSegmentList("v1/search"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/search"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/search"); assertEquals("Should match", "v1.0", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/search"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/search"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); } @Test public void testGetResourceVersion() { List<PathSegment> segments = getPathSegmentList("v1/students"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/studentSectionAssociations/1234/students"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/students"); assertEquals("Should match", "v1.0", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/students"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/students"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/students"); when(mutated.getPath()).thenReturn(null); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); } @Test public void testGetResourceVersionForPublicResources() { List<PathSegment> segments = getPathSegmentList("v1/assessments"); MutatedContainer mutated = mock(MutatedContainer.class); when(mutated.getPath()).thenReturn("/search/assessments"); assertEquals("Should match", "v1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.0/assessments"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.1/assessments"); assertEquals("Should match", "v1.1", endpointMutator.getResourceVersion(segments, mutated)); segments = getPathSegmentList("v1.3/assessments"); assertEquals("Should match", "v1.3", endpointMutator.getResourceVersion(segments, mutated)); }
EndpointMutator { public void mutateURI(Authentication auth, ContainerRequest request) { if (request.getMethod().equals(POST)) { return; } SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); String clientId = ((OAuth2Authentication) auth).getClientAuthentication().getClientId(); List<PathSegment> segments = sanitizePathSegments(request); String parameters = request.getRequestUri().getQuery(); if (segments.size() == 0) { throw new NotFoundException(); } if (usingVersionedApi(segments)) { if (!request.getProperties().containsKey(REQUESTED_PATH)) { request.getProperties().put(REQUESTED_PATH, request.getPath()); } MutatedContainer mutated = uriMutator.mutate(segments, parameters, user, clientId); if (mutated != null && mutated.isModified()) { String version = getResourceVersion(segments, mutated); if (mutated.getHeaders() != null) { InBoundHeaders headers = new InBoundHeaders(); headers.putAll(request.getRequestHeaders()); for (String key : mutated.getHeaders().keySet()) { headers.putSingle(key, mutated.getHeaders().get(key)); } request.setHeaders(headers); } if (mutated.getPath() != null) { if (mutated.getQueryParameters() != null && !mutated.getQueryParameters().isEmpty()) { LOG.info("URI Rewrite: {}?{} --> {}?{}", new Object[] { request.getPath(), parameters, mutated.getPath(), mutated.getQueryParameters() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()) .replaceQuery(mutated.getQueryParameters()).build()); } else { LOG.info("URI Rewrite: {} --> {}", new Object[] { request.getPath(), mutated.getPath() }); request.setUris(request.getBaseUri(), request.getBaseUriBuilder().path(version).path(mutated.getPath()).build()); } } } } } void mutateURI(Authentication auth, ContainerRequest request); }
@Test(expected = NotFoundException.class) public void testNoPathSegments() throws URISyntaxException { SLIPrincipal principle = mock(SLIPrincipal.class); ClientToken clientToken = mock(ClientToken.class); when(clientToken.getClientId()).thenReturn("theAppId"); OAuth2Authentication auth = mock(OAuth2Authentication.class); when(auth.getPrincipal()).thenReturn(principle); when(auth.getClientAuthentication()).thenReturn(clientToken); ContainerRequest request = mock(ContainerRequest.class); List<PathSegment> segments = Collections.emptyList(); when(request.getPathSegments()).thenReturn(segments); when(request.getMethod()).thenReturn("GET"); when(request.getRequestUri()).thenReturn(new URI("http: endpointMutator.mutateURI(auth, request); }
UriMutator { public MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId) { Entity user = principal.getEntity(); Map<String, String> parameters = MutatorUtil.getParameterMap(queryParameters); for (Pair<String, String> parameterResourcePair : PARAMETER_RESOURCE_PAIRS) { String parameter = parameterResourcePair.getLeft(); String resource = parameterResourcePair.getRight(); if (parameters.containsKey(parameter)) { EntityDefinition definition = definitionStore .lookupByResourceName(resource); if (definition != null) { NeutralQuery query = new NeutralQuery(new NeutralCriteria( parameter, NeutralCriteria.OPERATOR_EQUAL, parameters.get(parameter))); Entity e = repo.findOne(definition.getType(), query); if (e != null) { MutatedContainer newMutated = new MutatedContainer(); String path = String.format("/%s/%s", resource, e.getEntityId()); if (EntityNames.TEACHER.equals(e.getType())) { path = String.format("/teachers/%s", e.getEntityId()); } else if (EntityNames.STAFF.equals(e.getType())) { path = String.format("/staff/%s", e.getEntityId()); } newMutated.setPath(path); newMutated.setQueryParameters(queryParameters); LOG.info("Rewriting URI to {} based on natural keys", newMutated.getPath()); return newMutated; } } } } MutatedContainer generalMutation = doGeneralMutations( stringifyPathSegments(segments), queryParameters, user); if (generalMutation != null) { return generalMutation; } MutatedContainer mutated; if (segments.size() < NUM_SEGMENTS_IN_TWO_PART_REQUEST) { if (shouldSkipMutation(segments, queryParameters, principal, clientId)) { mutated = new MutatedContainer(); mutated.setPath(null); mutated.setQueryParameters(queryParameters); } else { if (segments.size() == 1) { mutated = mutateBaseUri(segments.get(0).getPath(), ResourceNames.HOME, queryParameters, user); } else { mutated = mutateBaseUri(segments.get(0).getPath(), segments.get(1).getPath(), queryParameters, user); } } } else { mutated = mutateUriBasedOnRole(segments, queryParameters, user); } return mutated; } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); static final int NUM_SEGMENTS_IN_TWO_PART_REQUEST; static final int NUM_SEGMENTS_IN_ONE_PART_REQUEST; }
@Test public void testV1Mutate() { PathSegment v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("v1"); when(principal.getEntity()).thenReturn(staff); Assert.assertEquals("Bad endpoint of /v1 is redirected to v1/home safely", createMutatedContainer("/home", "").toString(), mutator.mutate(Arrays.asList(v1), null, principal, "nonAdminAppId").toString()); when(principal.getEntity()).thenReturn(teacher); Assert.assertEquals("Bad endpoint of /v1 is redirected to v1/home safely", createMutatedContainer("/home", "").toString(), mutator.mutate(Arrays.asList(v1), null, principal, "nonAdminAppId").toString()); } @Test public void testDeterministicRewrite() { when(principal.getEntity()).thenReturn(null); Map<String, Object> body = new HashMap<String, Object>(); body.put("staffUniqueStateId", "teacher"); Entity teacher = repo.create("teacher", body, "staff"); PathSegment v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/staff"); Assert.assertEquals("Endpoint should be rewritten to /teachers/id", createMutatedContainer("/teachers/" + teacher.getEntityId(), "staffUniqueStateId=teacher"), mutator.mutate(Arrays.asList(v1), "staffUniqueStateId=teacher", principal, null)); body.put("staffUniqueStateId", "staff"); teacher = repo.create("staff", body, "staff"); v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/staff"); Assert.assertEquals("Endpoint should be rewritten to /staff/id", createMutatedContainer("/staff/" + teacher.getEntityId(), "staffUniqueStateId=staff"), mutator.mutate(Arrays.asList(v1), "staffUniqueStateId=staff", principal, null)); } @Test public void testMutateSkipForAppAuthRightAdminApp() { SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT); Map<String, Object> body = new HashMap<String, Object>(); body.put("staffUniqueStateId", "staff"); teacher = repo.create("staff", body, "staff"); PathSegment v1 = Mockito.mock(PathSegment.class); when(v1.getPath()).thenReturn("/v1"); PathSegment edorgs = Mockito.mock(PathSegment.class); when(edorgs.getPath()).thenReturn("/educationOrganizations"); when(principal.getEntity()).thenReturn(staff); Map<String, Collection<GrantedAuthority>> edOrgRights = generateSimpleEdOrgRightsMap("theEdOrg", Right.APP_AUTHORIZE); when(principal.getEdOrgRights()).thenReturn(edOrgRights); MutatedContainer mutated = mutator.mutate(Arrays.asList(v1,edorgs), null, principal, ADMIN_APP_ID); System.out.println("The path is : " + mutated.getPath() + ", qparams : " + mutated.getQueryParameters()); Assert.assertEquals("Endpoint should NOT have been rewritten to " + mutated.getPath(), createMutatedContainer(null, ""), mutated); }
SliDeltaManager { public static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats) { boolean isPrevIngested = false; String tenantId = TenantContext.getTenantId(); String sliEntityType = MapUtils.getString(n.getMetaData(), "sliEntityType"); if (sliEntityType == null) { sliEntityType = n.getRecordType(); } Map<String, String> populatedNaturalKeys = new HashMap<String, String>(); NeutralRecord neutralRecordResolved = null; neutralRecordResolved = (NeutralRecord) n.clone(); NeutralRecordEntity entity = new NeutralRecordEntity(neutralRecordResolved); didResolver.resolveInternalIds(entity, tenantId, report, reportStats); try { Map<String, List<DidNaturalKey>> naturalKeysMap = didResolver.getDidSchemaParser().getNaturalKeys(); String recordType = neutralRecordResolved.getRecordType(); List<DidNaturalKey> naturalKeys = naturalKeysMap.get(recordType); if ( null == naturalKeys ) { throw new NoNaturalKeysDefinedException("Natural keys not defined for record type '" + recordType + "'"); } populatedNaturalKeys = populateNaturalKeyValues(neutralRecordResolved, naturalKeys); NaturalKeyDescriptor nkd = new NaturalKeyDescriptor(populatedNaturalKeys, tenantId, sliEntityType, null); String recordId = dIdStrategy.generateId(nkd); String recordHashValues = neutralRecordResolved.generateRecordHash(tenantId); RecordHash record = batchJobDAO.findRecordHash(tenantId, recordId); List<Map<String, Object>> rhData = new ArrayList<Map<String, Object>>(); Map<String, Object> rhDataElement = new HashMap<String, Object>(); rhDataElement.put(RECORDHASH_ID, recordId); rhDataElement.put(RECORDHASH_HASH, recordHashValues); rhData.add(rhDataElement); n.addMetaData(RECORDHASH_DATA, rhData); isPrevIngested = !n.getActionVerb().doDelete() && (record != null && record.getHash().equals(recordHashValues)); if(record != null) { rhDataElement.put(RECORDHASH_CURRENT, record.exportToSerializableMap()); } } catch (NoNaturalKeysDefinedException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } catch (NaturalKeyValidationException e) { LOG.warn(e.getMessage()); isPrevIngested = false; } return isPrevIngested; } private SliDeltaManager(); static boolean isPreviouslyIngested(NeutralRecord n, BatchJobDAO batchJobDAO, DeterministicUUIDGeneratorStrategy dIdStrategy, DeterministicIdResolver didResolver, AbstractMessageReport report, ReportStats reportStats); static final String RECORDHASH_DATA; static final String RECORDHASH_HASH; static final String RECORDHASH_ID; static final String RECORDHASH_CURRENT; static final String NRKEYVALUEFIELDNAMES; static final String OPTIONALNRKEYVALUEFIELDNAMES; }
@Test public void testIsPreviouslyIngested() { NeutralRecord originalRecord = createBaseNeutralRecord(); NeutralRecord recordClone = (NeutralRecord) originalRecord.clone(); TenantContext.setTenantId("tenantId"); Mockito.when(mockBatchJobMongoDA.findRecordHash(any(String.class), any(String.class))).thenReturn(null); Mockito.when(mockDIdStrategy.generateId(any(NaturalKeyDescriptor.class))).thenReturn(RECORD_DID); Mockito.when(mockDidResolver.getDidSchemaParser()).thenReturn(didSchemaParser); Mockito.when(didSchemaParser.getNaturalKeys()).thenReturn(createNaturalKeyMap()); Assert.assertFalse(SliDeltaManager.isPreviouslyIngested(originalRecord, mockBatchJobMongoDA, mockDIdStrategy, mockDidResolver, errorReport, reportStats)); confirmMetaDataUpdated(originalRecord); List<Map<String, String>> fData = (List<Map<String, String>>) originalRecord.getMetaData().get("rhData"); String fTenantId = (String) originalRecord.getMetaData().get("rhTenantId"); String fHash=fData.get(0).get("rhHash"); String fRhId=fData.get(0).get("rhId"); RecordHash hash = createRecordHash(fHash); Mockito.when(mockBatchJobMongoDA.findRecordHash(any(String.class), any(String.class))).thenReturn(hash); Assert.assertTrue(SliDeltaManager.isPreviouslyIngested(recordClone, mockBatchJobMongoDA, mockDIdStrategy, mockDidResolver, errorReport, reportStats)); confirmMetaDataUpdated(recordClone); List<Map<String, String>> sData = (List<Map<String, String>>) originalRecord.getMetaData().get("rhData"); String sTenantId = (String) originalRecord.getMetaData().get("rhTenantId"); String sHash=sData.get(0).get("rhHash"); String sRhId=sData.get(0).get("rhId"); Assert.assertEquals(fRhId, sRhId); Assert.assertEquals(fHash, sHash); Assert.assertEquals(fTenantId, sTenantId); } @Test public void testIsPreviouslyIngestedModified() { NeutralRecord originalRecord = createBaseNeutralRecord(); NeutralRecord modifiedRecord = (NeutralRecord) originalRecord.clone(); modifiedRecord.getAttributes().put("commonAttrib1", "commonAttrib1_modified_value"); TenantContext.setTenantId("tenantId"); Mockito.when(mockBatchJobMongoDA.findRecordHash(any(String.class), any(String.class))).thenReturn(null); Mockito.when(mockDIdStrategy.generateId(any(NaturalKeyDescriptor.class))).thenReturn(RECORD_DID); Mockito.when(mockDidResolver.getDidSchemaParser()).thenReturn(didSchemaParser); Mockito.when(didSchemaParser.getNaturalKeys()).thenReturn(createNaturalKeyMap()); Assert.assertFalse(SliDeltaManager.isPreviouslyIngested(originalRecord, mockBatchJobMongoDA, mockDIdStrategy, mockDidResolver, errorReport, reportStats)); confirmMetaDataUpdated(originalRecord); List<Map<String, String>> fData = (List<Map<String, String>>) originalRecord.getMetaData().get("rhData"); String fTenantId = (String) originalRecord.getMetaData().get("rhTenantId"); String fHash=fData.get(0).get("rhHash"); String fRhId=fData.get(0).get("rhId"); RecordHash hash = createRecordHash(fHash); Mockito.when(mockBatchJobMongoDA.findRecordHash(any(String.class), any(String.class))).thenReturn(hash); Assert.assertFalse(SliDeltaManager.isPreviouslyIngested(modifiedRecord, mockBatchJobMongoDA, mockDIdStrategy, mockDidResolver, errorReport, reportStats)); confirmMetaDataUpdated(modifiedRecord); List<Map<String, String>> sData = (List<Map<String, String>>) modifiedRecord.getMetaData().get("rhData"); String sTenantId = (String) originalRecord.getMetaData().get("rhTenantId"); String sHash=sData.get(0).get("rhHash"); String sRhId=sData.get(0).get("rhId"); Assert.assertEquals(fRhId, sRhId); Assert.assertEquals(fTenantId, sTenantId); Assert.assertFalse(fHash.equals(sHash)); }
UriMutator { public MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user) { MutatedContainer mutated = new MutatedContainer(); mutated.setQueryParameters(queryParameters); if (mutated.getQueryParameters() == null) { mutated.setQueryParameters(""); } mutated.setPath(rootSearchMutator.mutatePath(version, resource, mutated.getQueryParameters())); if (mutated.getPath() == null && mutateToTeacher()) { return this.mutateBaseUriForTeacher(resource, mutated.getQueryParameters(), user); } else if (mutated.getPath() == null && mutateToStaff()) { return this.mutateBaseUriForStaff(resource, mutated.getQueryParameters(), user, mutated.getQueryParameters()); } else if (mutated.getPath() == null && isStudent(user) || isParent(user)) { return this.mutateStudentParentRequest( Arrays.<String> asList(version, resource), mutated.getQueryParameters(), user); } else { return mutated; } } MutatedContainer mutate(List<PathSegment> segments, String queryParameters, SLIPrincipal principal, String clientId); MutatedContainer mutateBaseUri(String version, String resource, final String queryParameters, Entity user); static final int NUM_SEGMENTS_IN_TWO_PART_REQUEST; static final int NUM_SEGMENTS_IN_ONE_PART_REQUEST; }
@Test public void testGetInferredUrisForTeacherContext() throws Exception { SecurityUtil.setUserContext(SecurityUtil.UserContext.TEACHER_CONTEXT); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.ATTENDANCES + " is incorrect.", createMutatedContainer("/sections/section123/studentSectionAssociations/students/attendances", ""), mutator.mutateBaseUri(VERSION, ResourceNames.ATTENDANCES, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.HOME + " is incorrect.", createMutatedContainer("/home", ""), mutator.mutateBaseUri(VERSION, ResourceNames.HOME, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.SECTIONS + " is incorrect.", createMutatedContainer("/teachers/teacher123/teacherSectionAssociations/sections", ""), mutator.mutateBaseUri(VERSION, ResourceNames.SECTIONS, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.STUDENT_SECTION_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/sections/section123/studentSectionAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENT_SECTION_ASSOCIATIONS, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.TEACHERS + " is incorrect.", createMutatedContainer("/schools/school123/teacherSchoolAssociations/teachers", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHERS, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/teachers/teacher123/teacherSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS, "", teacher)); Assert.assertEquals("inferred uri for teacher resource: /" + ResourceNames.TEACHER_SECTION_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/teachers/teacher123/teacherSectionAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHER_SECTION_ASSOCIATIONS, "", teacher)); } @Test public void testGetInferredUrisForStaffContext() throws Exception { SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.ATTENDANCES + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations/students/attendances", ""), mutator.mutateBaseUri(VERSION, ResourceNames.ATTENDANCES, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.COHORTS + " is incorrect.", createMutatedContainer("/staff/staff123/staffCohortAssociations/cohorts", ""), mutator.mutateBaseUri(VERSION, ResourceNames.COHORTS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.HOME + " is incorrect.", createMutatedContainer("/home", ""), mutator.mutateBaseUri(VERSION, ResourceNames.HOME, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.PROGRAMS + " is incorrect.", createMutatedContainer("/staff/staff123/staffProgramAssociations/programs", ""), mutator.mutateBaseUri(VERSION, ResourceNames.PROGRAMS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.SECTIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/sections", ""), mutator.mutateBaseUri(VERSION, ResourceNames.SECTIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF + " is incorrect.", createMutatedContainer("/educationOrganizations/edOrg123/staffEducationOrgAssignmentAssociations/staff", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_COHORT_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffCohortAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_COHORT_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffEducationOrgAssignmentAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_PROGRAM_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffProgramAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_PROGRAM_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STUDENTS + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations/students", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENTS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.TEACHERS + " is incorrect.", createMutatedContainer("/schools/edOrg123/teacherSchoolAssociations/teachers", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHERS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/teacherSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS, "", staff)); } @Test public void testGetInferredUrisForDualContext() throws Exception { SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.ATTENDANCES + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations/students/attendances", ""), mutator.mutateBaseUri(VERSION, ResourceNames.ATTENDANCES, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.COHORTS + " is incorrect.", createMutatedContainer("/staff/staff123/staffCohortAssociations/cohorts", ""), mutator.mutateBaseUri(VERSION, ResourceNames.COHORTS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.HOME + " is incorrect.", createMutatedContainer("/home", ""), mutator.mutateBaseUri(VERSION, ResourceNames.HOME, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.PROGRAMS + " is incorrect.", createMutatedContainer("/staff/staff123/staffProgramAssociations/programs", ""), mutator.mutateBaseUri(VERSION, ResourceNames.PROGRAMS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.SECTIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/sections", ""), mutator.mutateBaseUri(VERSION, ResourceNames.SECTIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF + " is incorrect.", createMutatedContainer("/educationOrganizations/edOrg123/staffEducationOrgAssignmentAssociations/staff", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_COHORT_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffCohortAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_COHORT_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffEducationOrgAssignmentAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_EDUCATION_ORGANIZATION_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STAFF_PROGRAM_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/staff/staff123/staffProgramAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STAFF_PROGRAM_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STUDENTS + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations/students", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENTS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/studentSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.TEACHERS + " is incorrect.", createMutatedContainer("/schools/edOrg123/teacherSchoolAssociations/teachers", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHERS, "", staff)); Assert.assertEquals("inferred uri for staff resource: /" + ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS + " is incorrect.", createMutatedContainer("/schools/edOrg123/teacherSchoolAssociations", ""), mutator.mutateBaseUri(VERSION, ResourceNames.TEACHER_SCHOOL_ASSOCIATIONS, "", staff)); }
MongoUserLocator implements UserLocator { @Override public SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId) { LOG.info("Locating user {}@{} of type: {}", new Object[]{externalUserId, tenantId, userType}); SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId); user.setExternalId(externalUserId); user.setTenantId(tenantId); user.setUserType(userType); TenantContext.setTenantId(tenantId); if (EntityNames.STUDENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria( ParameterConstants.STUDENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.STUDENT, neutralQuery, true)); } else if (EntityNames.PARENT.equals(userType)) { NeutralQuery neutralQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.PARENT_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); neutralQuery.setOffset(0); neutralQuery.setLimit(1); user.setEntity(repo.findOne(EntityNames.PARENT, neutralQuery, true)); } else if (isStaff(userType)) { NeutralQuery neutralQuery = new NeutralQuery(); neutralQuery.setOffset(0); neutralQuery.setLimit(1); neutralQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, externalUserId)); Iterable<Entity> staff = repo.findAll(EntityNames.STAFF, neutralQuery); if (staff != null && staff.iterator().hasNext()) { Entity entity = staff.iterator().next(); Set<String> edorgs = edorgHelper.locateDirectEdorgs(entity); if (edorgs.size() == 0) { LOG.warn("User {} is not currently associated to a school/edorg", user.getId()); throw new APIAccessDeniedException("User is not currently associated to a school/edorg", user, clientId); } user.setEntity(entity); } } if (user.getEntity() == null) { LOG.warn("Failed to locate user {} in the datastore", user.getId()); Entity entity = new MongoEntity("user", SLIPrincipal.NULL_ENTITY_ID, new HashMap<String, Object>(), new HashMap<String, Object>()); user.setEntity(entity); } else { LOG.info("Matched user: {}@{} -> {}", new Object[]{externalUserId, tenantId, user.getEntity().getEntityId()}); } return user; } @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType, String clientId); @Override SLIPrincipal locate(String tenantId, String externalUserId, String userType); void setRepo(Repository<Entity> repo); }
@Test public void testStudentType() { SLIPrincipal principal = locator.locate(tenant, "testId", "student"); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals(EntityNames.STUDENT)); } @Test public void testStaffType() { Set<String> edorgs = new HashSet<String>(); edorgs.add("testEdorg"); Mockito.when(edorgHelper.locateDirectEdorgs((Entity)Matchers.any())).thenReturn(edorgs); SLIPrincipal principal = locator.locate(tenant, "testId", "staff"); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals(EntityNames.STAFF)); principal = locator.locate(tenant, "testId", ""); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals(EntityNames.STAFF)); principal = locator.locate(tenant, "testId", null); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals(EntityNames.STAFF)); } @Test(expected = AccessDeniedException.class) public void testInvalidStaff() { Set<String> edorgs = new HashSet<String>(); Mockito.when(edorgHelper.locateDirectEdorgs((Entity)Matchers.any())).thenReturn(edorgs); SLIPrincipal principal = locator.locate(tenant, "testId", "staff"); } @Test public void testInvalidType() { SLIPrincipal principal = locator.locate(tenant, "testId", "nobody"); assertTrue(principal.getEntity() != null); assertTrue(principal.getEntity().getType().equals("user")); }
DefaultRolesToRightsResolver implements RolesToRightsResolver { @Override public Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm) { Set<Role> roles = new HashSet<Role>(); Entity realm = findRealm(realmId); if (isAdminRealm) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); LOG.debug("Mapped admin roles {} to {}.", roleNames, roles); } else if (isDeveloperRealm(realm)) { roles.addAll(roleRightAccess.findAdminRoles(roleNames)); boolean canLoginAsDeveloper = false; for (Role role : roles) { if (role.hasRight(Right.PRODUCTION_LOGIN)) { canLoginAsDeveloper = true; break; } } if (canLoginAsDeveloper) { roles = new HashSet<Role>(); roles.addAll(roleRightAccess.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.APP_DEVELOPER))); LOG.debug("With PRODUCTION_LOGIN right, converted {} to {}.", roleNames, roles); } } else { roles.addAll(roleRightAccess.findRoles(tenantId, realmId, roleNames)); LOG.debug("Mapped user roles {} to {}.", roleNames, roles); } return roles; } @Override Set<GrantedAuthority> resolveRolesIntersect(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<GrantedAuthority> resolveRolesUnion(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm, boolean getSelfRights); @Override Set<Role> mapRoles(String tenantId, String realmId, List<String> roleNames, boolean isAdminRealm); }
@Test public void sandboxAdminBecomeDeveloperInDevRealm() { Set<Role> roles = resolver.mapRoles(null, DEVELOPER_REALM_ID, sandboxRole, false); assertTrue("sandbox admin is not mapped to developer in developer realm", roles.containsAll(defaultRoles.findAdminRoles(appAndProdLoginUser))); assertTrue("sandbox admin is not only mapped to developer in developer realm", defaultRoles.findAdminRoles(appAndProdLoginUser).containsAll(roles)); } @Test public void sandboxAdminstaysSandboxAdminInAdminRealm() { Set<Role> roles = resolver.mapRoles(null, ADMIN_REALM_ID, sandboxRole, true); assertTrue("sandbox admin is changed in admin realm", roles.containsAll(defaultRoles.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.SANDBOX_ADMINISTRATOR)))); assertTrue("sandbox admin is only mapped to sandbox admin in admin realm", defaultRoles.findAdminRoles(Arrays.asList(SecureRoleRightAccessImpl.SANDBOX_ADMINISTRATOR)).containsAll(roles)); } @Test public void roleWithoutProdLoginIsChangedToEmptyGroupInDevRealm() { Set<Role> roles = resolver.mapRoles(null, DEVELOPER_REALM_ID, otherRole, false); assertTrue("other admin is not mapped to developer in developer realm", roles.isEmpty()); }
DefaultQueryMangler extends Mangler { public NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria) { LOG.debug(">>>DefaultQueryMangler.mangleQuery()"); setTheQuery(query); setSecurityCriteria(securityCriteria); boolean isList = true; boolean isQueried = false; NeutralCriteria idCriteria = null; for (NeutralCriteria criteria : query.getCriteria()) { if (criteria.getKey().equals("_id")) { idCriteria = criteria; isList = false; } } if (isList) { if (!isQueried) { adjustSecurityForPaging(); } query.addOrQuery(new NeutralQuery(securityCriteria)); return query; } else { Set<String> finalIdSet = new HashSet<String>((Collection) securityCriteria.getValue()); finalIdSet.retainAll((Collection) idCriteria.getValue()); finalIdSet = new HashSet<String>(adjustIdListForPaging(new ArrayList<String>(finalIdSet))); query.removeCriteria(idCriteria); if (finalIdSet.size() > 0) { idCriteria.setValue(new ArrayList<String>(finalIdSet)); query.addOrQuery(new NeutralQuery(idCriteria)); } return query; } } NeutralQuery mangleQuery(NeutralQuery query, NeutralCriteria securityCriteria); }
@Test public void testMangleListQuery() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); NeutralCriteria baseCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"1", "2", "3"})); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(baseCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, baseCriteria); assertTrue(finalQuery.getCriteria().size() == 0); assertTrue(finalQuery.getOrQueries().size() == 1); assertEquals(finalQuery.getOrQueries().get(0).getCriteria().get(0), baseCriteria); } @Test public void testMangleSpecificQuery() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); NeutralCriteria baseCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"1", "2", "3"})); query.addCriteria(baseCriteria); NeutralCriteria secureCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"1", "2"})); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(secureCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, secureCriteria); assertTrue(finalQuery.getCriteria().size() == 0); assertTrue(finalQuery.getOrQueries().size() == 1); assertEquals(finalQuery.getOrQueries().get(0).getCriteria().get(0), baseCriteria); } @Test public void testMangleSpecificFailedQuery() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); NeutralCriteria baseCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"1", "2", "3"})); query.addCriteria(baseCriteria); NeutralCriteria secureCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, Arrays.asList(new String[] {"4", "5"})); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(secureCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, secureCriteria); assertEquals(finalQuery.getOrQueries().size(), 0); } @Test public void testMangleListWithPaging() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); List<String> totalQuery = buildLargeQuery(100); query.setOffset(0); query.setLimit(50); NeutralCriteria baseCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, totalQuery.subList(0, 50)); NeutralCriteria secureCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, totalQuery); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(secureCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, secureCriteria); assertTrue(finalQuery.getCriteria().size() == 0); assertTrue(finalQuery.getOrQueries().size() == 1); NeutralCriteria finalCriteria = finalQuery.getOrQueries().get(0).getCriteria().get(0); assertEquals(((List) finalCriteria.getValue()).size(), 50); } @Test public void testMangleListWithPagingAndQuery() { DefaultQueryMangler mangler = new DefaultQueryMangler(); NeutralQuery query = new NeutralQuery(); List<String> totalQuery = buildLargeQuery(50); query.setOffset(0); query.setLimit(50); NeutralCriteria baseCriteria = new NeutralCriteria("body.something", NeutralCriteria.OPERATOR_EQUAL, "Waffletown"); query.addCriteria(baseCriteria); NeutralCriteria secureCriteria = new NeutralCriteria("_id", NeutralCriteria.CRITERIA_IN, totalQuery); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setCollectionName("students"); securityCriteria.setSecurityCriteria(secureCriteria); NeutralQuery finalQuery = mangler.mangleQuery(query, secureCriteria); assertTrue(finalQuery.getCriteria().size() == 1); assertTrue(finalQuery.getOrQueries().size() == 1); NeutralCriteria finalCriteria = finalQuery.getOrQueries().get(0).getCriteria().get(0); assertEquals(((List) finalCriteria.getValue()).size(), 50); }
SecurityCriteria { public NeutralQuery applySecurityCriteria(NeutralQuery query) { if (securityCriteria != null) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); SLIPrincipal user = (SLIPrincipal) auth.getPrincipal(); if (EntityNames.TEACHER.equals(user.getEntity().getType())) { List<String> ids = (List) securityCriteria.getValue(); if (ids.size() > inClauseSize) { throw new ResponseTooLargeException(); } } query.addOrQuery(new NeutralQuery(securityCriteria)); } return query; } String getCollectionName(); void setCollectionName(String collectionName); NeutralCriteria getSecurityCriteria(); void setSecurityCriteria(NeutralCriteria securityCriteria); NeutralQuery applySecurityCriteria(NeutralQuery query); void setInClauseSize(Long size); }
@Test public void testApplySecurityCriteria() { injector.setAccessAllAdminContext(); SecurityCriteria securityCriteria = new SecurityCriteria(); securityCriteria.setSecurityCriteria(new NeutralCriteria("key", "in", "value")); NeutralQuery query = new NeutralQuery(); query = securityCriteria.applySecurityCriteria(query); assertEquals("Should match", 1, query.getOrQueries().size()); }
SamlHelper { public String getArtifactUrl(String realmId, String artifact) { byte[] sourceId = retrieveSourceId(artifact); Entity realm = realmHelper.findRealmById(realmId); if (realm == null) { LOG.error("Invalid realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } Map<String, Object> idp = (Map<String, Object>) realm.getBody().get("idp"); String realmSourceId = (String) idp.get("sourceId"); if (realmSourceId == null || realmSourceId.isEmpty()) { LOG.error("SourceId is not configured properly for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } byte[] realmByteSourceId = DatatypeConverter.parseHexBinary(realmSourceId); if (!Arrays.equals(realmByteSourceId, sourceId)) { LOG.error("SourceId from Artifact does not match configured SourceId for realm: " + realmId); throw new APIAccessDeniedException("Authorization could not be verified."); } return (String) idp.get("artifactResolutionEndpoint"); } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test public void testGetArtifactUrl() { setRealm(VALID_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); } @Test(expected = APIAccessDeniedException.class) public void testGetArtifactUrlIncorrectSourceId() { setRealm(INCORRECT_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); } @Test(expected = IllegalArgumentException.class) public void testGetArtifactUrlInvalidSourceIdFormat() { setRealm(NOT_HEX_SOURCEID); String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT); Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result); }
MongoCommander { public static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate) { Set<MongoIndex> indexes = indexTxtFileParser.parse(indexFile); DB dbConn = getDB(db, mongoTemplate); return ensureIndexes(indexes, dbConn); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); static final String STR_0X38; }
@Test public void testEnsureIndexes() { String result = MongoCommander.ensureIndexes("mongoTestIndexes.txt", dbName, mockedMongoTemplate); assertNull(result); for (String collection : shardCollections) { DBObject asskeys = new BasicDBObject(); asskeys.put("creationTime", 1); DBObject options = buildOpts(dbName + "." + collection, collectionOrder.get(collection)); Mockito.verify(collectionIns.get(collection), Mockito.times(1)).createIndex(asskeys, options); } } @Test public void testEnsureSetIndexes() { String result = MongoCommander.ensureIndexes(indexes, dbName, mockedMongoTemplate); assertNull(result); for (String collection : shardCollections) { DBObject asskeys = new BasicDBObject(); asskeys.put("creationTime", 1); DBObject options = buildOpts(dbName + "." + collection, collectionOrder.get(collection)); Mockito.verify(collectionIns.get(collection), Mockito.times(1)).createIndex(asskeys, options); } }
SamlHelper { protected Assertion decryptAssertion(EncryptedAssertion encryptedAssertion, KeyStore.PrivateKeyEntry keystoreEntry) { BasicX509Credential decryptionCredential = new BasicX509Credential(); decryptionCredential.setPrivateKey(keystoreEntry.getPrivateKey()); StaticKeyInfoCredentialResolver resolver = new StaticKeyInfoCredentialResolver(decryptionCredential); ChainingEncryptedKeyResolver keyResolver = new ChainingEncryptedKeyResolver(); keyResolver.getResolverChain().add(new InlineEncryptedKeyResolver()); keyResolver.getResolverChain().add(new EncryptedElementTypeEncryptedKeyResolver()); keyResolver.getResolverChain().add(new SimpleRetrievalMethodEncryptedKeyResolver()); Decrypter decrypter = new Decrypter(null, resolver, keyResolver); decrypter.setRootInNewDocument(true); Assertion assertion = null; try { assertion = decrypter.decrypt(encryptedAssertion); } catch (DecryptionException e) { raiseSamlValidationError("Unable to decrypt SAML assertion", null); } return assertion; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test public void testInlineDecryption() { Resource inlineAssertionResource = new ClassPathResource("saml/inlineEncryptedAssertion.xml"); EncryptedAssertion encAssertion = createAssertion(inlineAssertionResource); Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry); verifyAssertion(assertion); } @Test public void testPeerDecryption() { Resource peerAssertionResource = new ClassPathResource("saml/peerEncryptedAssertion.xml"); EncryptedAssertion encAssertion = createAssertion(peerAssertionResource); Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry); verifyAssertion(assertion); }
SamlHelper { protected boolean isAssertionEncrypted(org.opensaml.saml2.core.Response samlResponse) { if (samlResponse.getEncryptedAssertions() != null && samlResponse.getEncryptedAssertions().size() != 0) { return true; } return false; } @PostConstruct void init(); Pair<String, String> createSamlAuthnRequestForRedirect(String destination, boolean forceAuthn, int idpType); org.w3c.dom.Document parseToDoc(String data); String decodeSAMLPostResponse(String encodedReponse); Signature getDigitalSignature(KeyStore.PrivateKeyEntry keystoreEntry); void validateSignature(Response samlResponse, Assertion assertion); LinkedMultiValueMap<String, String> extractAttributesFromResponse(Assertion samlAssertion); String getArtifactUrl(String realmId, String artifact); org.opensaml.saml2.core.Response convertToSAMLResponse(org.w3c.dom.Element element); Assertion getAssertion(org.opensaml.saml2.core.Response samlResponse, KeyStore.PrivateKeyEntry keystoreEntry); void validateStatus(org.opensaml.saml2.core.Response samlResponse); static final Namespace SAML_NS; static final Namespace SAMLP_NS; }
@Test public void testIsAssertionEncrypted() { Response samlResponse = Mockito.mock(Response.class); Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(null); boolean result = samlHelper.isAssertionEncrypted(samlResponse); Assert.assertFalse(result); Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(new ArrayList<EncryptedAssertion>()); result = samlHelper.isAssertionEncrypted(samlResponse); Assert.assertFalse(result); EncryptedAssertion encryptedAssertion = Mockito.mock(EncryptedAssertion.class); List<EncryptedAssertion> assertionList = new ArrayList<EncryptedAssertion>(); assertionList.add(encryptedAssertion); Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(assertionList); result = samlHelper.isAssertionEncrypted(samlResponse); Assert.assertTrue(result); }
ContextValidator implements ApplicationContextAware { public void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive) throws APIAccessDeniedException { LOG.debug(">>>ContextValidator.validateContextToEntities()"); LOG.debug(" def: " + ToStringBuilder.reflectionToString(def, ToStringStyle.DEFAULT_STYLE)); LOG.debug(" ids: {}", (ids==null) ? "null" : ids.toArray().toString() ); LOG.debug(" isTransitive" + isTransitive); IContextValidator validator = findValidator(def.getType(), isTransitive); LOG.debug(" loaded validator: " + ToStringBuilder.reflectionToString(validator, ToStringStyle.DEFAULT_STYLE)); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); LOG.debug(" getIdsQuery: " + getIdsQuery.toString()); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); LOG.debug(" entities: " + ToStringBuilder.reflectionToString(entities, ToStringStyle.DEFAULT_STYLE)); Set<String> idsToValidate = getEntityIdsToValidate(def, entities, isTransitive, ids); LOG.debug(" idsToValidate: " + idsToValidate.toString()); Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); LOG.debug(" validatedIds: " + validatedIds.toString()); if (!validatedIds.containsAll(idsToValidate)) { LOG.debug(" ...APIAccessDeniedException"); throw new APIAccessDeniedException("Cannot access entities", def.getType(), idsToValidate); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testValidateContextToEntities() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); Entity student3 = createEntity("student", 3); Entity student5 = createEntity("student", 5); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(student1, student2, student3, student5)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student2))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student3))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student5))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student2, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student3, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student5, isTransitive)).thenReturn(true); Collection<String> ids = new HashSet<String>(Arrays.asList("student1", "student2", "student3", "student5")); contextValidator.validateContextToEntities(def, ids, isTransitive); } @Test public void testValidateContextToEntitiesOrphaned() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("createdBy", "staff1"); metaData.put("isOrphaned", "true"); Mockito.when(student1.getMetaData()).thenReturn(metaData); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(student1)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Collection<String> ids = new HashSet<String>(Arrays.asList("student1")); contextValidator.validateContextToEntities(def, ids, isTransitive); Mockito.verify(ownership, Mockito.never()).canAccess(Mockito.any(Entity.class), Mockito.anyBoolean()); } @Test public void testValidateContextToEntitiesSelf() { EntityDefinition def = createEntityDef("staff"); Entity staff1 = createEntity("staff", 1); Mockito.when(repo.findAll(Mockito.matches("staff"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(staff1)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(staff1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Collection<String> ids = new HashSet<String>(Arrays.asList("staff1")); contextValidator.validateContextToEntities(def, ids, isTransitive); Mockito.verify(ownership, Mockito.never()).canAccess(Mockito.any(Entity.class), Mockito.anyBoolean()); } @Test public void testValidateContextToEntitiesCannotAccess() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(student1)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(false); Collection<String> ids = new HashSet<String>(Arrays.asList("student1")); try { contextValidator.validateContextToEntities(def, ids, isTransitive); Assert.fail(); } catch (APIAccessDeniedException ex) { Assert.assertEquals("Access to " + student1.getEntityId() + " is not authorized", ex.getMessage()); } } @Test public void testValidateContextToEntitiesNoEntitiesInDb() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(new ArrayList<Entity>()); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); String id = "student1"; Collection<String> ids = new HashSet<String>(Arrays.asList(id)); try { contextValidator.validateContextToEntities(def, ids, isTransitive); Assert.fail(); } catch (EntityNotFoundException ex) { Assert.assertEquals(id, ex.getId()); } } @Test public void testValidateContextToEntitiesNotAllValidated() { EntityDefinition def = createEntityDef("student"); Entity student0 = createEntity("student", 0); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); Mockito.when(repo.findAll(Mockito.matches("student"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(student0, student1, student2)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student0, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student2, isTransitive)).thenReturn(true); Collection<String> ids = new HashSet<String>(Arrays.asList("student0", "student1", "student2")); try { contextValidator.validateContextToEntities(def, ids, isTransitive); Assert.fail(); } catch (APIAccessDeniedException ex) { Assert.assertEquals("Cannot access entities", ex.getMessage()); } } @Test public void testValidateContextToEntitiesSelfNoValidators() { EntityDefinition def = createEntityDef("session"); Entity session1 = createEntity("session", 1); Mockito.when(repo.findAll(Mockito.matches("session"), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(session1)); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(session1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Collection<String> ids = new HashSet<String>(Arrays.asList("session1")); try { contextValidator.validateContextToEntities(def, ids, isTransitive); Assert.fail(); } catch (APIAccessDeniedException ex) { Assert.assertEquals("No validator for " + def.getType() + ", transitive=" + isTransitive, ex.getMessage()); } }
ContextValidator implements ApplicationContextAware { public Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead) throws APIAccessDeniedException { if (skipValidation(def, isRead)) { return null; } Map<String, SecurityUtil.UserContext> entityContexts = new HashMap<String, SecurityUtil.UserContext>(); List<IContextValidator> contextValidators = findContextualValidators(def.getType(), isTransitive); Collection<String> ids = getEntityIds(entities); if (!contextValidators.isEmpty()) { Set<String> idsToValidate = getEntityIdsToValidateForgiving(entities, isTransitive); for (IContextValidator validator : contextValidators) { Set<String> validatedIds = getValidatedIds(def, idsToValidate, validator); for (String id : validatedIds) { if (!entityContexts.containsKey(id)) { entityContexts.put(id, validator.getContext()); } else if ((entityContexts.get(id).equals(SecurityUtil.UserContext.STAFF_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) || (entityContexts.get(id).equals(SecurityUtil.UserContext.TEACHER_CONTEXT)) && (validator.getContext().equals(SecurityUtil.UserContext.STAFF_CONTEXT))) { entityContexts.put(id, SecurityUtil.UserContext.DUAL_CONTEXT); } } } Set<String> accessibleNonValidatedIds = new HashSet<String>(ids); accessibleNonValidatedIds.removeAll(idsToValidate); for (String id : accessibleNonValidatedIds) { entityContexts.put(id, SecurityUtil.getUserContext()); } } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } return entityContexts; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testGetValidatedEntityContexts() { EntityDefinition def = createEntityDef("student"); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.any(Entity.class))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(Mockito.any(Entity.class), Mockito.anyBoolean())).thenReturn(true); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); Entity student3 = createEntity("student", 3); Entity student4 = createEntity("student", 4); Entity student5 = createEntity("student", 5); List<Entity> students = Arrays.asList(student1, student2, student3, student4, student5); Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, students, isTransitive, true); Assert.assertEquals(5, validatedEntityContexts.size()); Assert.assertEquals(SecurityUtil.UserContext.STAFF_CONTEXT, validatedEntityContexts.get("student1")); Assert.assertEquals(SecurityUtil.UserContext.DUAL_CONTEXT, validatedEntityContexts.get("student2")); Assert.assertEquals(SecurityUtil.UserContext.STAFF_CONTEXT, validatedEntityContexts.get("student3")); Assert.assertEquals(SecurityUtil.UserContext.TEACHER_CONTEXT, validatedEntityContexts.get("student4")); Assert.assertEquals(SecurityUtil.UserContext.DUAL_CONTEXT, validatedEntityContexts.get("student5")); } @Test public void testGetValidatedEntityContextsOrphaned() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("createdBy", "staff1"); metaData.put("isOrphaned", "true"); Mockito.when(student1.getMetaData()).thenReturn(metaData); List<Entity> students = Arrays.asList(student1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, students, isTransitive, true); Assert.assertEquals(1, validatedEntityContexts.size()); Assert.assertEquals(SecurityUtil.UserContext.DUAL_CONTEXT, validatedEntityContexts.get("student1")); Mockito.verify(ownership, Mockito.never()).canAccess(Mockito.any(Entity.class), Mockito.anyBoolean()); } @SuppressWarnings("unused") @Test public void testGetValidatedEntityContextsSelf() { EntityDefinition def = createEntityDef("staff"); Entity staff1 = createEntity("staff", 1); List<Entity> staff = Arrays.asList(staff1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(staff1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, staff, isTransitive, true); Mockito.verify(ownership, Mockito.never()).canAccess(Mockito.any(Entity.class), Mockito.anyBoolean()); } @SuppressWarnings("unused") @Test public void testGetValidatedEntityContextsCannotAccess() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); List<Entity> students = Arrays.asList(student1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(false); Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, students, isTransitive, true); Assert.assertEquals(1, validatedEntityContexts.size()); } @SuppressWarnings("unused") @Test public void testGetValidatedEntityContextsNoEntitiesInList() { EntityDefinition def = createEntityDef("student"); Entity student1 = createEntity("student", 1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Collection<String> ids = new HashSet<String>(); Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, new ArrayList<Entity>(), isTransitive, true); Assert.assertTrue(validatedEntityContexts.isEmpty()); } @Test public void testGetValidatedEntityContextsNotAllValidated() { EntityDefinition def = createEntityDef("student"); Entity student0 = createEntity("student", 0); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); List<Entity> students = Arrays.asList(student0, student1, student2); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(student1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; Mockito.when(ownership.canAccess(student0, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student2, isTransitive)).thenReturn(true); Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, students, isTransitive, true); Assert.assertEquals(2, validatedEntityContexts.size()); Assert.assertEquals(SecurityUtil.UserContext.STAFF_CONTEXT, validatedEntityContexts.get("student1")); Assert.assertEquals(SecurityUtil.UserContext.DUAL_CONTEXT, validatedEntityContexts.get("student2")); } @SuppressWarnings("unused") @Test public void testGetValidatedEntityContextsNoValidators() { EntityDefinition def = createEntityDef("session"); Entity session1 = createEntity("session", 1); List<Entity> sessions = Arrays.asList(session1); Mockito.when(edOrgHelper.getDirectEdorgs(Mockito.eq(session1))).thenReturn(new HashSet<String>(Arrays.asList("edOrg1"))); boolean isTransitive = false; try { Map<String, SecurityUtil.UserContext> validatedEntityContexts = contextValidator.getValidatedEntityContexts(def, sessions, isTransitive, true); Assert.fail(); } catch (APIAccessDeniedException ex) { Assert.assertEquals("No validator for " + def.getType() + ", transitive=" + isTransitive, ex.getMessage()); } }
ContextValidator implements ApplicationContextAware { protected Set<String> getEntityIdsToValidateForgiving(Collection<Entity> entities, boolean isTransitive){ Set<String> entityIdsToValidate = new HashSet<String>(); for (Entity ent : entities) { if (isOrphanCreatedByUser(ent)) { LOG.debug("Entity is orphaned: id {} of type {}", ent.getEntityId(), ent.getType()); } else if (SecurityUtil.getSLIPrincipal().getEntity() != null && SecurityUtil.getSLIPrincipal().getEntity().getEntityId().equals(ent.getEntityId())) { LOG.debug("Entity is themselves: id {} of type {}", ent.getEntityId(), ent.getType()); } else { try{ if (ownership.canAccess(ent, isTransitive)) { entityIdsToValidate.add(ent.getEntityId()); } } catch (AccessDeniedException aex) { LOG.error(aex.getMessage()); } } } return entityIdsToValidate; } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testgetEntityIdsToValidateForgiving() { Entity student0 = createEntity("student", 0); Entity student1 = createEntity("student", 1); Entity student2 = createEntity("student", 2); List<Entity> students = Arrays.asList(student0, student1, student2); boolean isTransitive = false; Mockito.when(ownership.canAccess(student0, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student1, isTransitive)).thenReturn(true); Mockito.when(ownership.canAccess(student2, isTransitive)).thenThrow(new AccessDeniedException("")); Set<String> ids = contextValidator.getEntityIdsToValidateForgiving(students, isTransitive); Assert.assertEquals(2, ids.size()); Assert.assertTrue(ids.contains(student0.getEntityId())); Assert.assertTrue(ids.contains(student1.getEntityId())); }
ContextValidator implements ApplicationContextAware { public Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive) throws APIAccessDeniedException { IContextValidator validator = findValidator(def.getType(), isTransitive); if (validator != null) { NeutralQuery getIdsQuery = new NeutralQuery(new NeutralCriteria("_id", "in", new ArrayList<String>(ids))); Collection<Entity> entities = (Collection<Entity>) repo.findAll(def.getStoredCollectionName(), getIdsQuery); Set<String> orphans = new HashSet<String>(); for (Entity entity: entities) { if (isOrphanCreatedByUser(entity)) { orphans.add(entity.getEntityId()); } } Set<String> nonOrphanIds = new HashSet<String>(); nonOrphanIds.addAll(ids); nonOrphanIds.removeAll(orphans); Set<String> validatedIds = validator.getValid(def.getType(), nonOrphanIds); validatedIds.addAll(orphans); return validatedIds; } else { throw new APIAccessDeniedException("No validator for " + def.getType() + ", transitive=" + isTransitive, def.getType(), ids); } } @Override void setApplicationContext(ApplicationContext applicationContext); void validateContextToUri(ContainerRequest request, SLIPrincipal principal); boolean isUrlBlocked(ContainerRequest request); List<PathSegment> cleanEmptySegments(List<PathSegment> pathSegments); void validateContextToCallUri(List<PathSegment> segments); boolean checkAccessOfStudentsThroughDisciplineIncidents(List<PathSegment> segments); void validateContextToEntities(EntityDefinition def, Collection<String> ids, boolean isTransitive); Set<String> getValidIdsIncludeOrphans(EntityDefinition def, Set<String> ids, boolean isTransitive); Map<String, SecurityUtil.UserContext> getValidatedEntityContexts(EntityDefinition def, Collection<Entity> entities, boolean isTransitive, boolean isRead); IContextValidator findValidator(String toType, boolean isTransitive); static boolean isTransitive(List<PathSegment> segs); List<IContextValidator> findContextualValidators(String toType, boolean isTransitive); boolean isGlobalEntity(String type); }
@Test public void testGetValidIdsIncludeOrphans() { EntityDefinition def = createEntityDef(EntityNames.STUDENT); Entity orphanedStudent = createEntity(EntityNames.STUDENT, 14); Entity accessStudent1 = createEntity(EntityNames.STUDENT, 1); Entity accessStudent2 = createEntity(EntityNames.STUDENT, 2); Entity noAccessStudent = createEntity(EntityNames.STUDENT, 4); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("isOrphaned", "true"); metaData.put("createdBy", "staff1"); Mockito.when(orphanedStudent.getMetaData()).thenReturn(metaData); List<Entity> students = Arrays.asList(orphanedStudent, accessStudent1, accessStudent2, noAccessStudent); Set<String> studentIds = new HashSet(Arrays.asList("student14", "student1", "student2", "student4")); Mockito.when(repo.findAll(Mockito.eq(EntityNames.STUDENT), Mockito.any(NeutralQuery.class))).thenReturn(students); Set<String> results = contextValidator.getValidIdsIncludeOrphans(def, studentIds, true); Assert.assertEquals(3, results.size()); } @Test public void getDoNotIncludeOwningOrphans() { EntityDefinition def = createEntityDef(EntityNames.STUDENT); Entity orphanNotByUser = createEntity(EntityNames.STUDENT, 14); Entity accessStudent1 = createEntity(EntityNames.STUDENT, 1); Entity accessStudent2 = createEntity(EntityNames.STUDENT, 2); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("isOrphaned", "true"); metaData.put("createdBy", "staff2"); Mockito.when(orphanNotByUser.getMetaData()).thenReturn(metaData); List<Entity> students = Arrays.asList(orphanNotByUser, accessStudent1, accessStudent2); Set<String> studentIds = new HashSet(Arrays.asList("student14", "student1", "student2")); Mockito.when(repo.findAll(Mockito.eq(EntityNames.STUDENT), Mockito.any(NeutralQuery.class))).thenReturn(students); Set<String> results = contextValidator.getValidIdsIncludeOrphans(def, studentIds, true); Assert.assertEquals(2, results.size()); }
MongoCommander { public static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate) { DB dbConn = mongoTemplate.getDb().getSisterDB("admin"); List<String> shards = getShards(dbConn); if (shards.size() == 0) { return null; } String sresult = setBalancerState(dbConn, false); if (sresult != null) { return sresult; } DBObject enableShard = new BasicDBObject("enableSharding", dbName); CommandResult result = dbConn.command(enableShard); if (!result.ok()) { LOG.error("Error enabling sharding on {}: {}", dbConn, result.getErrorMessage()); return result.getErrorMessage(); } for (String coll : shardCollections) { String collection = dbName + "." + coll; DBObject shardColl = new BasicDBObject(); shardColl.put("shardCollection", collection); shardColl.put("key", new BasicDBObject(ID, 1)); result = dbConn.command(shardColl); if (!result.ok()) { LOG.error("Error enabling shard'ing on {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } sresult = moveChunks(collection, shards, dbConn); if (sresult != null) { return sresult; } } return preSplitBinCollections(dbName, mongoTemplate); } private MongoCommander(); static String ensureIndexes(String indexFile, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<String> indexes, String db, MongoTemplate mongoTemplate); static String ensureIndexes(Set<MongoIndex> indexes, DB dbConn); @SuppressWarnings("boxing") static String ensureIndexes(MongoIndex index, DB dbConn, int indexOrder); static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate); static DB getDB(String db, MongoTemplate mongoTemplate); static DB getDB(String db, DB dbConn); static final String STR_0X38; }
@Test public void testPreSplit() { List<DBObject> shards = new ArrayList<DBObject>(); shards.add(new BasicDBObject("_id", "shard0")); shards.add(new BasicDBObject("_id", "shard1")); BasicDBList listShards = new BasicDBList(); listShards.add(new BasicDBObject("shards", shards)); List<String> lShards = new ArrayList<String>(); lShards.add("shard0"); lShards.add("lShard1"); Mockito.when(db.command((DBObject) Matchers.any())).thenReturn(res); Mockito.when(res.get("shards")).thenReturn(listShards); String result = MongoCommander.preSplit(shardCollections, dbName, mockedMongoTemplate); assertNull(result); Mockito.verify(db, Mockito.times(1)).command(new BasicDBObject("enableSharding", dbName)); Mockito.verify(db, Mockito.times(2)).command(new BasicDBObject("listShards", 1)); Mockito.verify(db, Mockito.times(13)).command(Matchers.any(DBObject.class)); Mockito.verify(settings, Mockito.times(1)).update(Matchers.any(DBObject.class), Matchers.any(DBObject.class), Matchers.eq(true), Matchers.eq(false)); }
EdOrgHelper { public List<String> getDistricts(Entity user) { Set<String> directAssoc = getDirectEdorgs(user); return getDistricts(directAssoc); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testStaff1() { setContext(staff1, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); List<String> leas = helper.getDistricts(staff1); assertTrue("staff1 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("staff1 must only see one district", 1, leas.size()); } @Test public void testStaff2() { setContext(staff2, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); List<String> leas = helper.getDistricts(staff2); assertTrue("staff2 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("staff2 must only see one district", 1, leas.size()); } @Test public void testStaff3() { setContext(staff3, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); List<String> leas = helper.getDistricts(staff3); assertTrue("staff3 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("staff3 must only see one district", 1, leas.size()); } @Test public void testStaff4() { setContext(staff4, Arrays.asList(SecureRoleRightAccessImpl.IT_ADMINISTRATOR)); List<String> leas = helper.getDistricts(staff4); assertTrue("staff4 must see lea1", leas.contains(lea1.getEntityId())); assertTrue("staff4 must see lea4", leas.contains(lea4.getEntityId())); assertEquals("staff4 must only see two districts", 2, leas.size()); } @Test public void testTeacher1() { setContext(teacher1, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); List<String> leas = helper.getDistricts(teacher1); assertTrue("teacher1 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("teacher1 must only see one district", 1, leas.size()); } @Test public void testTeacher2() { setContext(teacher2, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); List<String> leas = helper.getDistricts(teacher2); assertTrue("teacher2 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("teacher2 must only see one district", 1, leas.size()); } @Test public void testTeacher3() { setContext(teacher3, Arrays.asList(SecureRoleRightAccessImpl.EDUCATOR)); List<String> leas = helper.getDistricts(teacher3); assertTrue("teacher3 must see lea1", leas.contains(lea1.getEntityId())); assertEquals("teacher3 must only see one district", 1, leas.size()); }
EdOrgHelper { public Set<Entity> locateNonExpiredSEOAs(String staffId) { Set<Entity> validAssociations = new HashSet<Entity>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staffId)); Iterable<Entity> associations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); for (Entity association : associations) { if (!dateHelper.isFieldExpired(association.getBody(), ParameterConstants.END_DATE, false)) { validAssociations.add(association); } } return validAssociations; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testTeacher3LocateSEOAs() { NeutralQuery staffQuery = new NeutralQuery(); staffQuery.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_UNIQUE_STATE_ID, NeutralCriteria.OPERATOR_EQUAL, teacher3.getEntityId())); repo.deleteAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, staffQuery); Date now = new Date(); setupSEOAs(repo, now.getTime(), teacher3, school3.getEntityId()); Set<Entity> associations = helper.locateNonExpiredSEOAs(teacher3.getEntityId()); assertTrue("teacher3 should have 3 valid associations", associations.size() == 3); }
EdOrgHelper { public List<String> getParentEdOrgs(Entity edOrgEntity) { List<String> toReturn = new ArrayList<String>(); Map<String, Entity> edOrgCache = loadEdOrgCache(); Set<String> visitedEdOrgs = new HashSet<String>(); if (edOrgEntity != null) { String myId = edOrgEntity.getEntityId(); if (myId != null) { visitedEdOrgs.add(myId); toReturn = getParentEdOrgs(edOrgEntity, edOrgCache, visitedEdOrgs, toReturn); } } return toReturn; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testParents() { RequestUtil.setCurrentRequestId(); List<String> edorgs = helper.getParentEdOrgs(school3); assertTrue(edorgs.contains(sea1.getEntityId())); assertTrue(edorgs.contains(lea1.getEntityId())); assertTrue(edorgs.contains(lea2.getEntityId())); assertTrue(edorgs.contains(lea3.getEntityId())); assertFalse(edorgs.contains(school1.getEntityId())); assertFalse(edorgs.contains(school2.getEntityId())); assertFalse(edorgs.contains(school3.getEntityId())); assertEquals(4, edorgs.size()); } @Test public void testParentsWithCycle() { RequestUtil.setCurrentRequestId(); List<String> edorgs = helper.getParentEdOrgs(leaCycle1); assertFalse("leaCycle1 should not be a child of leaCycle1", edorgs.contains(leaCycle1.getEntityId())); assertTrue("leaCycle2 should be a child of leaCycle1", edorgs.contains(leaCycle2.getEntityId())); assertTrue("leaCycle3 should be a child of leaCycle1", edorgs.contains(leaCycle3.getEntityId())); assertEquals(2, edorgs.size()); } @Test public void testParentsOfSea() { RequestUtil.setCurrentRequestId(); List<String> edorgs = helper.getParentEdOrgs(sea1); assertEquals(0, edorgs.size()); } @Test public void testHeirarchicalEdorgs() { RequestUtil.setCurrentRequestId(); List<String> edorgs = helper.getParentEdOrgs(school1); assertEquals(2, edorgs.size()); assertFalse("school1 should not see lea3", edorgs.contains(lea3.getEntityId())); assertFalse("school1 should not see lea2", edorgs.contains(lea2.getEntityId())); assertTrue("school1 should see lea1", edorgs.contains(lea1.getEntityId())); assertTrue("school1 should see sea1", edorgs.contains(sea1.getEntityId())); }
IndexJSFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Map<String, Object> indexMap = null; File resourceFile = null; FileInputStream fstream = null; BufferedReader br = null; Set<MongoIndex> indexes = new HashSet<MongoIndex>(); try { URL resourceURL = Thread.currentThread().getContextClassLoader().getResource(fileName); if (resourceURL != null) { resourceFile = new File(resourceURL.toURI()); if (resourceFile != null) { fstream = new FileInputStream(resourceFile); br = new BufferedReader(new InputStreamReader(fstream)); String collectionName = null; String keyJsonString; String currentFileLine; while ((currentFileLine = br.readLine()) != null) { boolean unique = false; Matcher indexMatcher = ensureIndexStatement(currentFileLine); if (indexMatcher != null) { collectionName = indexMatcher.group(1); keyJsonString = indexMatcher.group(2); if (indexMatcher.group(3) != null) { unique = Boolean.parseBoolean(indexMatcher.group(4)); } indexMap = parseJson(keyJsonString); DBObject keyObj = new BasicDBObject(indexMap); indexes.add(new MongoIndex(collectionName, unique, keyObj)); } } } } } catch (IOException e) { LOG.error("Error reading index file:" + e.getMessage()); } catch (URISyntaxException e) { LOG.error("Index file not found: " + e.getMessage()); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(fstream); } return indexes; } @Override Set<MongoIndex> parse(String fileName); static Map<String, Object> parseJson(String jsonString); }
@Test public void parseJSTest() { IndexJSFileParser indexJSFileParser = new IndexJSFileParser(); Set<MongoIndex> indexes = indexJSFileParser.parse(INDEX_FILE); Map<String, MongoIndex> expectedIndexes = new HashMap<String, MongoIndex>(); DBObject userSessionIndex = new BasicDBObject(); userSessionIndex.put("body.expiration", 1); userSessionIndex.put("body.hardLogout", 1); userSessionIndex.put("body.appSession.token", 1); expectedIndexes.put("usersession", new MongoIndex("userSession", false, userSessionIndex)); DBObject tenantIndex = new BasicDBObject(); tenantIndex.put("body.tenantId", 1); expectedIndexes.put("tenant", new MongoIndex("tenant", true, tenantIndex)); assertEquals(4, indexes.size()); for (MongoIndex idx : indexes) { if (idx.getCollection().equalsIgnoreCase("realm")) { fail("Invalid index was parsed"); } else if (idx.getCollection().equalsIgnoreCase("usersession")) { assertEquals(idx, expectedIndexes.get("usersession")); } else if (idx.getCollection().equalsIgnoreCase("tenant")) { assertEquals(idx, expectedIndexes.get("tenant")); assertTrue(idx.isUnique()); } } }
EdOrgHelper { public Set<String> getDirectEdorgs() { LOG.trace(">>>EdOrgHelper.getDirectEdorgs()"); return getDirectEdorgs(SecurityUtil.getSLIPrincipal().getEntity()); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testStudent1() { Set<String> edorgs = helper.getDirectEdorgs(student1); assertEquals(1, edorgs.size()); assertTrue("student1 should see school1", edorgs.contains(school1.getEntityId())); assertFalse("student1 should not see school2", edorgs.contains(school2.getEntityId())); assertFalse("student1 should not see school3", edorgs.contains(school3.getEntityId())); } @Test public void testStudent2() { Set<String> edorgs = helper.getDirectEdorgs(student2); assertEquals(1, edorgs.size()); assertFalse("student2 should not see school1", edorgs.contains(school1.getEntityId())); assertTrue("student2 should see school2", edorgs.contains(school2.getEntityId())); assertFalse("student2 should not see school3", edorgs.contains(school3.getEntityId())); } @Test public void testStudent3() { Set<String> edorgs = helper.getDirectEdorgs(student3); assertEquals(1, edorgs.size()); assertFalse("student3 should not see school1", edorgs.contains(school1.getEntityId())); assertFalse("student3 should not see school2", edorgs.contains(school2.getEntityId())); assertTrue("student3 should see school3", edorgs.contains(school3.getEntityId())); }
EdOrgHelper { public List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity) { Set<String> result; if (edOrgEntity == null) { return null; } result = getDirectChildLEAsOfEdOrg(edOrgEntity.getEntityId()); if (result == null || result.isEmpty()) { return null; } return new ArrayList<String>(result); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testGetChildLeaOfEdorgs() { List<String> edorgs = helper.getDirectChildLEAsOfEdOrg(lea2); assertEquals(1, edorgs.size()); assertFalse("lea1 should not be a child of lea2", edorgs.contains(lea1.getEntityId())); assertFalse("lea2 should not be a child of lea2", edorgs.contains(lea2.getEntityId())); assertTrue("lea3 should be a child of lea2", edorgs.contains(lea3.getEntityId())); }
EdOrgHelper { public Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity) { String myId; Set<String> edOrgs = new HashSet<String>(); Set<String> result = new HashSet<String>(); if (edOrgEntity == null || edOrgEntity.getEntityId() == null) { return null; } myId = edOrgEntity.getEntityId(); edOrgs.add(myId); result = getAllChildLEAsOfEdOrg(edOrgs, new HashSet<String>()); result.remove(myId); return result; } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testGetAllChildLeaOfEdorgs() { Set<String> edorgs = helper.getAllChildLEAsOfEdOrg(sea1); assertEquals(4, edorgs.size()); assertTrue("lea1 should be a child of sea1", edorgs.contains(lea1.getEntityId())); assertTrue("lea2 should be a child of sea1", edorgs.contains(lea2.getEntityId())); assertTrue("lea3 should be a child of sea1", edorgs.contains(lea3.getEntityId())); assertTrue("lea4 should be a child of sea1", edorgs.contains(lea4.getEntityId())); } @Test public void testGetAllChildLeaOfEdorgsWithCycle() { Set<String> edorgs = helper.getAllChildLEAsOfEdOrg(leaCycle1); assertEquals(2, edorgs.size()); assertFalse("leaCycle1 should not be a child of leaCycle1", edorgs.contains(leaCycle1.getEntityId())); assertTrue("leaCycle2 should be a child of leaCycle1", edorgs.contains(leaCycle2.getEntityId())); assertTrue("leaCycle3 should be a child of leaCycle1", edorgs.contains(leaCycle3.getEntityId())); }
EdOrgHelper { public Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds) { return getChildEdOrgsName(parentEdOrgIds, false); } @PostConstruct void init(); List<String> getDistricts(Entity user); List<String> getDistricts(Set<String> edOrgs); List<String> getDirectChildLEAsOfEdOrg(Entity edOrgEntity); Set<String> getAllChildLEAsOfEdOrg(Entity edOrgEntity); List<String> getParentEdOrgs(Entity edOrgEntity); Entity byId(String edOrgId); boolean isSEA(Entity entity); String getSEAOfEdOrg(Entity entity); List<String> getDirectSchools(Entity principal); List<String> getDirectSchoolsLineage(Entity principal, boolean getLineage); Set<String> getChildEdOrgs(Collection<String> edOrgs); Set<String> getChildEdOrgs(String edOrg); Set<String> getChildEdOrgs(final Set<String> visitedEdOrgs, Collection<String> edOrgs); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds); Set<String> getChildEdOrgsName(Collection<String> parentEdOrgIds, boolean includeParents); Collection<String> getUserEdOrgs(Entity principal); Set<String> getStaffEdOrgsAndChildren(); Set<String> getEdorgDescendents(Set<String> edOrgLineage); Set<String> getDelegatedEdorgDescendents(); boolean isFieldExpired(Map<String, Object> body, String fieldName, boolean useGracePeriod); @SuppressWarnings("unchecked") boolean isLEA(Entity entity); @SuppressWarnings("unchecked") boolean isSchool(Entity entity); Set<String> getDirectEdorgs(); Set<String> getDirectEdorgs(Entity principal); List<String> getUserEdorgs(Entity principal); Set<String> locateDirectEdorgs(Entity principal); Set<Entity> locateValidSEOAs(String staffId, boolean filterByOwnership); Set<Entity> locateNonExpiredSEOAs(String staffId); Set<String> getEdOrgStateOrganizationIds(Set<String> edOrgIds); }
@Test public void testGetChildEdOrgsNameWithoutParents() { Set<String> children = helper.getChildEdOrgsName(Arrays.asList(lea2.getEntityId(), leaCycle1.getEntityId())); assertTrue("expected to see school2 in the list of children", children.contains(school2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see lea3 in the list of children", children.contains(lea3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see school3 in the list of children", children.contains(school3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle2 in the list of children", children.contains(leaCycle2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle3 in the list of children", children.contains(leaCycle3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertEquals(5, children.size()); } @Test public void testGetChildEdOrgsNameWithParents() { Set<String> children = helper.getChildEdOrgsName(Arrays.asList(lea2.getEntityId(), leaCycle1.getEntityId()), true); assertTrue("expected to see lea2 in the list of children", children.contains(lea2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle1 in the list of children", children.contains(leaCycle1.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see school2 in the list of children", children.contains(school2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see lea3 in the list of children", children.contains(lea3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see school3 in the list of children", children.contains(school3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle2 in the list of children", children.contains(leaCycle2.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertTrue("expected to see leaCycle3 in the list of children", children.contains(leaCycle3.getBody().get(ParameterConstants.STATE_ORGANIZATION_ID))); assertEquals(7, children.size()); }
IndexTxtFileParser implements IndexParser<String> { @Override public Set<MongoIndex> parse(String fileName) { Set<String> indexSet = loadIndexes(fileName); return new IndexSliFormatParser().parse(indexSet); } @Override Set<MongoIndex> parse(String fileName); static Set<String> loadIndexes(String indexFile); }
@Test public void parseTxtTest() { IndexTxtFileParser indexTxtFileParser = new IndexTxtFileParser(); Set<MongoIndex> indexes = indexTxtFileParser.parse(INDEX_TXT_FILE); assertEquals(2, indexes.size()); Map<String, MongoIndex> expectedIndex = new HashMap<String, MongoIndex>(); DBObject adminDelegationIndex = new BasicDBObject(); adminDelegationIndex.put("body.localEdOrgId", 1); expectedIndex.put("adminDelegation", new MongoIndex("adminDelegation", false, adminDelegationIndex, false)); DBObject applicationAuthorizationIndex = new BasicDBObject(); applicationAuthorizationIndex.put("body.appIds", 1); expectedIndex.put("applicationAuthorization", new MongoIndex("applicationAuthorization", true, applicationAuthorizationIndex, false)); for (MongoIndex index : indexes) { String collection = index.getCollection(); if (collection.equalsIgnoreCase("learningObjective")) { fail("Invalid index was parsed"); } else if (collection.equalsIgnoreCase("adminDelegation")) { assertEquals(index, expectedIndex.get("adminDelegation")); } else if (collection.equalsIgnoreCase("applicationAuthorization")) { assertEquals(index, expectedIndex.get("applicationAuthorization")); assertTrue(index.isUnique()); } } }
RealmHelper { public boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm) { if (isSandboxEnabled) { return true; } List<String> preferredRealms = getPreferredLoginRealmIds(userEntity); if (preferredRealms.size() > 0) { return preferredRealms.contains(realm.getEntityId()); } Set<String> userEdorgs = edorgHelper.locateDirectEdorgs(userEntity); for (String id : userEdorgs) { Entity edorgEntity = repo.findById("educationOrganization", id); if (isValidForLogin(edorgEntity, realm)) { LOG.debug("User is allowed to login to realm: {} through edorg: {}", realm.getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); return true; } else { LOG.debug("User cannot login to realm: {} through edorg: {}", realm .getBody().get("name"), edorgEntity.getBody().get("nameOfInstitution")); } } return false; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test public void testLoginRealmIdsForSEA() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea = buildEdOrg("LEA", sea, false); Entity seaStaff = buildStaff("SEA Staff", sea); Entity seaRealm = buildRealm(sea); Entity leaRealm = buildRealm(lea); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, seaRealm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(seaStaff, leaRealm)); } @Test public void testLoginRealmIdsForLEA() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea = buildEdOrg("LEA", sea, false); Entity leaStaff = buildStaff("LEA Staff", lea); Entity seaRealm = buildRealm(sea); Entity leaRealm = buildRealm(lea); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(leaStaff, seaRealm)); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(leaStaff, leaRealm)); } @Test public void testSeaWithNoDirectRealm() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea1 = buildEdOrg("LEA1", sea, false); Entity lea2 = buildEdOrg("LEA2", lea1, false); Entity lea1Realm = buildRealm(lea1); Entity lea2Realm = buildRealm(lea2); Entity seaStaff = buildStaff("SEA Staff", sea); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, lea1Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(seaStaff, lea2Realm)); } @Test public void testLeaWithNoDirectRealm() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea1 = buildEdOrg("LEA1", sea, false); Entity lea2 = buildEdOrg("LEA2", lea1, false); Entity lea3 = buildEdOrg("LEA3", lea2, false); Entity lea1Realm = buildRealm(lea1); Entity lea3Realm = buildRealm(lea3); Entity seaRealm = buildRealm(sea); Entity leaStaff = buildStaff("LEA Staff", lea2); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(leaStaff, lea1Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(leaStaff, lea3Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(leaStaff, seaRealm)); } @Test public void testSeaWithNoDirectRealmAndTwoAssociations() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea1 = buildEdOrg("LEA1", sea, false); Entity lea2 = buildEdOrg("LEA2", lea1, false); Entity lea3 = buildEdOrg("LEA3", lea2, false); Entity lea1Realm = buildRealm(lea1); Entity lea3Realm = buildRealm(lea3); Entity seaStaff = buildStaff("SEA Staff", sea, lea2); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, lea1Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(seaStaff, lea3Realm)); } @Test public void testSeaWithNoDirectRealmAndTwoRealmsOnSameTier() { Entity sea = buildEdOrg("SEA1", null, true); Entity lea1 = buildEdOrg("LEA1", sea, false); Entity lea2 = buildEdOrg("LEA2", sea, false); Entity lea3 = buildEdOrg("LEA3", lea1, false); Entity lea1Realm = buildRealm(lea1); Entity lea2Realm = buildRealm(lea2); Entity lea3Realm = buildRealm(lea3); Entity seaStaff = buildStaff("SEA Staff", sea); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, lea1Realm)); RequestUtil.setCurrentRequestId(); assertTrue(helper.isUserAllowedLoginToRealm(seaStaff, lea2Realm)); RequestUtil.setCurrentRequestId(); assertFalse(helper.isUserAllowedLoginToRealm(seaStaff, lea3Realm)); }
RealmHelper { public Set<String> getAssociatedRealmIds() { HashSet<String> toReturn = new HashSet<String>(); if (isSandboxEnabled) { toReturn.add(getSandboxRealmId()); } else { NeutralQuery realmQuery = new NeutralQuery(); String edOrg = SecurityUtil.getEdOrg(); LOG.debug("Looking up realms for edorg {}.", edOrg); realmQuery.addCriteria(new NeutralCriteria("edOrg", NeutralCriteria.OPERATOR_EQUAL, edOrg)); realmQuery .addCriteria(new NeutralCriteria("tenantId", NeutralCriteria.OPERATOR_EQUAL, SecurityUtil .getTenantId())); Iterable<String> realmIds = repo.findAllIds("realm", realmQuery); for (String id : realmIds) { toReturn.add(id); } } return toReturn; } String getSandboxRealmId(); String getAdminRealmId(); String getEdOrgIdFromRealm(String realmId); Entity getRealmFromSession(String sessionId); List<String> getPreferredLoginRealmIds(Entity userEntity); Iterable<Entity> getRealms(Entity edOrg); boolean isUserAllowedLoginToRealm(Entity userEntity, Entity realm); Set<String> getAssociatedRealmIds(); Entity findRealmById(String id); static final String USER_SESSION; }
@Test public void testGetAssociatedRealmIsTenantSpecific() { Entity sea = buildEdOrg("SEA1", null, injector.TENANT_ID, true); Entity lea1 = buildEdOrg("LEA1", sea, injector.TENANT_ID, false); Entity lea2 = buildEdOrg("LEA1", null, "Two", false); Entity lea2Realm = buildRealm(lea2, "Two"); Entity lea1Realm = buildRealm(lea1, injector.TENANT_ID); Entity staff = buildStaff("LEA One", lea1); injector.setCustomContext("LEA", "LEA One", lea1Realm.getEntityId(), Arrays.asList("Realm Administrator"), staff, (String) lea1Realm.getBody().get("edOrg")); Set<String> realmIds = helper.getAssociatedRealmIds(); assertTrue(realmIds != null); assertTrue(realmIds.contains(lea1Realm.getEntityId())); }
WriteValidator { public void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal) { targetEdOrgIds = new HashSet<String>(); if (isWriteValidationEnabled && !isValidForEdOrgWrite(entityBody, uriInfo, principal)) { throw new APIAccessDeniedException("Invalid reference. No association to referenced entity.", targetEdOrgIds); } } void validateWriteRequest(EntityBody entityBody, UriInfo uriInfo, SLIPrincipal principal); void setRepo(PagingRepositoryDelegate<Entity> repo); }
@Test @ExpectedException(value = AccessDeniedException.class) public void testDenyWritingOutsideOfEdOrgHierarchyCreate() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, UN_ASSOCIATED_ED_ORG); when(uriInfo.getPathSegments()).thenReturn(postPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); } @Test public void testValidWritingInEdOrgHierarchyCreate() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, ED_ORG_B); when(uriInfo.getPathSegments()).thenReturn(postPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); } @Test @ExpectedException(value = AccessDeniedException.class) public void testDenyUpdateWhenNoEdOrgMatchToExistingEntity() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, ED_ORG_A); existingSection.getBody().put(ParameterConstants.SCHOOL_ID, UN_ASSOCIATED_ED_ORG); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); } @Test @ExpectedException(value = AccessDeniedException.class) public void testDenyUpdateWhenNoEdOrgMatchToNewEntity() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, UN_ASSOCIATED_ED_ORG); existingSection.getBody().put(ParameterConstants.SCHOOL_ID, ED_ORG_B); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); } @Test public void testValidUpdate() { EntityBody entityBody = new EntityBody(); entityBody.put(ParameterConstants.SCHOOL_ID, ED_ORG_A); existingSection.getBody().put(ParameterConstants.SCHOOL_ID, ED_ORG_B); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); } @Test public void testValidUpdateWithNoEdorgId() { EntityBody entityBody = new EntityBody(); entityBody.put("key", "value"); existingSection.getBody().put(ParameterConstants.SCHOOL_ID, ED_ORG_B); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(entityBody, uriInfo, principal); } @Test public void testValidDelete() { existingSection.getBody().put(ParameterConstants.SCHOOL_ID, ED_ORG_B); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(null, uriInfo, principal); } @Test @ExpectedException(value = AccessDeniedException.class) public void testInvalidDelete() { existingSection.getBody().put(ParameterConstants.SCHOOL_ID, UN_ASSOCIATED_ED_ORG); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(null, uriInfo, principal); } @Test public void testEntityNotFound() { when(repo.findById(EntityNames.SECTION, SECTION_ID)).thenReturn(null); when(uriInfo.getPathSegments()).thenReturn(putPath); writeValidator.validateWriteRequest(null, uriInfo, principal); } @Test public void testComplex() { existingSection.getBody().put(ParameterConstants.SCHOOL_ID, ED_ORG_B); String GRADEBOOK_ID = "gradebook-id"; Entity gradebookEntity = new MongoEntity(EntityNames.GRADEBOOK_ENTRY, GRADEBOOK_ID, new HashMap<String, Object>(), null); gradebookEntity.getBody().put(ParameterConstants.SECTION_ID, SECTION_ID); when(repo.findById(EntityNames.GRADEBOOK_ENTRY, GRADEBOOK_ID)).thenReturn(gradebookEntity); final List<PathSegment> path = createPathSegmentsFromStrings(PathConstants.V1, ResourceNames.GRADEBOOK_ENTRIES, GRADEBOOK_ID); when(uriInfo.getPathSegments()).thenReturn(path); writeValidator.validateWriteRequest(null, uriInfo, principal); { existingSection.getBody().put(ParameterConstants.SCHOOL_ID, UN_ASSOCIATED_ED_ORG); boolean threw = false; try { writeValidator.validateWriteRequest(null, uriInfo, principal); } catch (AccessDeniedException e) { threw = true; } Assert.assertTrue("should fail validation and throw error", threw); } }
PurgeProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Stage stage = Stage.createAndStartStage(BATCH_JOB_STAGE, BATCH_JOB_STAGE_DESC); String batchJobId = getBatchJobId(exchange); if (batchJobId != null) { reportStats = new SimpleReportStats(); NewBatchJob newJob = null; try { newJob = batchJobDAO.findBatchJobById(batchJobId); TenantContext.setTenantId(newJob.getTenantId()); String tenantId = newJob.getTenantId(); if (tenantId == null) { handleNoTenantId(batchJobId); } else { purgeForTenant(exchange, newJob, tenantId); } } catch (Exception exception) { handleProcessingExceptions(exchange, batchJobId, exception); } finally { if (newJob != null) { BatchJobUtils.stopStageAndAddToJob(stage, newJob); batchJobDAO.saveBatchJob(newJob); } } } else { missingBatchJobIdError(exchange); } } @Override void process(Exchange exchange); MongoTemplate getMongoTemplate(); void setMongoTemplate(MongoTemplate mongoTemplate); BatchJobDAO getBatchJobDAO(); AbstractMessageReport getMessageReport(); boolean isSandboxEnabled(); void setBatchJobDAO(BatchJobDAO batchJobDAO); void setMessageReport(AbstractMessageReport messageReport); void setSandboxEnabled(boolean sandboxEnabled); void setPurgeBatchSize(int purgeBatchSize); void setDeltaJournal(DeltaJournal deltaJournal); void setDeltasEnabled(boolean deltasEnabled); static final BatchJobStageType BATCH_JOB_STAGE; }
@Test public void testPurgingSystemCollections() throws Exception { RangedWorkNote workNote = RangedWorkNote.createSimpleWorkNote(BATCHJOBID); Exchange ex = Mockito.mock(Exchange.class); Message message = Mockito.mock(Message.class); Mockito.when(ex.getIn()).thenReturn(message); Mockito.when(message.getBody(RangedWorkNote.class)).thenReturn(workNote); NewBatchJob job = new NewBatchJob(); job.setProperty("tenantId", "SLI"); Mockito.when(mockBatchJobDAO.findBatchJobById(BATCHJOBID)).thenReturn(job); Set<String> collectionNames = new HashSet<String>(); collectionNames.add("system.js"); collectionNames.add("system.indexes"); Mockito.when(mongoTemplate.getCollectionNames()).thenReturn(collectionNames); purgeProcessor.process(ex); Mockito.verify(mongoTemplate, Mockito.never()).remove(Mockito.any(Query.class), Mockito.eq("system.js")); }
EdOrgOwnershipArbiter extends OwnershipArbiter { public Set<String> determineEdorgs(Iterable<Entity> entities, String entityType) { Set<String> edorgs = new HashSet<String>(); for (Entity entity : findOwner(entities, entityType, false)) { edorgs.add(entity.getEntityId()); } return edorgs; } @SuppressWarnings("unused") @PostConstruct void init(); Set<String> determineEdorgs(Iterable<Entity> entities, String entityType); Set<String> determineHierarchicalEdorgs(Iterable<Entity> entities, String entityType); boolean isEntityOwnedByEdOrg(String entityType); }
@Test public void testEdOrgReferenceEntities() { securityContextInjector.setEducatorContext(); Entity edorg = createEntity(EntityNames.SCHOOL, "edorg1", new HashMap<String, Object>()); Mockito.when(repo.findAll(Mockito.eq(EntityNames.EDUCATION_ORGANIZATION), argThat(new BaseMatcher<NeutralQuery>() { @Override public boolean matches(Object item) { NeutralQuery matching = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.OPERATOR_EQUAL, "edorg1")); NeutralQuery other = (NeutralQuery) item; return matching.getCriteria().equals(other.getCriteria()); } @Override public void describeTo(Description description) { } }))).thenReturn(Arrays.asList(edorg)); Map<String, Object> attendanceBody = new HashMap<String, Object>(); attendanceBody.put(ParameterConstants.SCHOOL_ID, "edorg1"); Entity attendance = createEntity(EntityNames.ATTENDANCE, "attendance1", attendanceBody); Set<String> edorgIds = arbiter.determineEdorgs(Arrays.asList(attendance), EntityNames.ATTENDANCE); Assert.assertEquals(1, edorgIds.size()); Assert.assertTrue(edorgIds.contains("edorg1")); } @Test public void testEdOrgFromAssociation() { securityContextInjector.setEducatorContext(); Entity edorg1 = createEntity(EntityNames.SCHOOL, "edorg1", new HashMap<String, Object>()); Entity edorg2 = createEntity(EntityNames.SCHOOL, "edorg2", new HashMap<String, Object>()); Entity edorg3 = createEntity(EntityNames.SCHOOL, "edorg3", new HashMap<String, Object>()); Mockito.when(repo.findAll(Mockito.eq(EntityNames.EDUCATION_ORGANIZATION), argThat(new BaseMatcher<NeutralQuery>() { @SuppressWarnings("unchecked") @Override public boolean matches(Object item) { NeutralQuery matching1 = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.OPERATOR_EQUAL, "edorg1")); NeutralQuery matching2 = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.OPERATOR_EQUAL, "edorg2")); NeutralQuery matching3 = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.OPERATOR_EQUAL, "edorg3")); NeutralQuery other = (NeutralQuery) item; return matching1.getCriteria().equals(other.getCriteria()) || matching2.getCriteria().equals(other.getCriteria()) || matching3.getCriteria().equals(other.getCriteria()); } @Override public void describeTo(Description description) { } }))).thenReturn(Arrays.asList(edorg1), Arrays.asList(edorg2), Arrays.asList(edorg3)); Entity student1 = createEntity(EntityNames.STUDENT, "student1", new HashMap<String, Object>()); Map<String, Object> ssa1Body = new HashMap<String, Object>(); ssa1Body.put(ParameterConstants.SCHOOL_ID, "edorg1"); ssa1Body.put(ParameterConstants.STUDENT_ID, "student1"); Entity ssa1 = createEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, "ssa1", ssa1Body); Map<String, Object> ssa2Body = new HashMap<String, Object>(); ssa2Body.put(ParameterConstants.SCHOOL_ID, "edorg2"); ssa2Body.put(ParameterConstants.STUDENT_ID, "student1"); Entity ssa2 = createEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, "ssa2", ssa2Body); Map<String, Object> ssa3Body = new HashMap<String, Object>(); ssa3Body.put(ParameterConstants.SCHOOL_ID, "edorg3"); ssa3Body.put(ParameterConstants.STUDENT_ID, "student1"); Entity ssa3 = createEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, "ssa3", ssa3Body); Mockito.when(repo.findAll(Mockito.eq(EntityNames.STUDENT_SCHOOL_ASSOCIATION), argThat(new BaseMatcher<NeutralQuery>() { @Override public boolean matches(Object item) { NeutralQuery matching = new NeutralQuery(new NeutralCriteria(ParameterConstants.STUDENT_ID, NeutralCriteria.OPERATOR_EQUAL, "student1")); NeutralQuery other = (NeutralQuery) item; return matching.getCriteria().equals(other.getCriteria()); } @Override public void describeTo(Description description) { } }))).thenReturn(Arrays.asList(ssa1, ssa2, ssa3)); Set<String> edorgIds = arbiter.determineEdorgs(Arrays.asList(student1), EntityNames.STUDENT); Assert.assertEquals(3, edorgIds.size()); Assert.assertTrue(edorgIds.contains("edorg1")); Assert.assertTrue(edorgIds.contains("edorg2")); Assert.assertTrue(edorgIds.contains("edorg3")); } @Test public void testEdOrgThroughStaff() { securityContextInjector.setStaffContext(); Entity edorg1 = createEntity(EntityNames.SCHOOL, "edorg1", new HashMap<String, Object>()); Entity edorg2 = createEntity(EntityNames.SCHOOL, "edorg2", new HashMap<String, Object>()); Mockito.when(repo.findAll(Mockito.eq(EntityNames.EDUCATION_ORGANIZATION), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(edorg1), Arrays.asList(edorg2)); Map<String, Object> sca1Body = new HashMap<String, Object>(); sca1Body.put(ParameterConstants.STAFF_ID, "staff1"); final Entity sca1 = createEntity(EntityNames.STAFF_COHORT_ASSOCIATION, "sca1", sca1Body); final Entity staff1 = createEntity(EntityNames.STAFF, "staff1", new HashMap<String, Object>()); Mockito.when(repo.findAll(Mockito.eq(EntityNames.STAFF), argThat(new BaseMatcher<NeutralQuery>() { @Override public boolean matches(Object item) { NeutralQuery matching = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.OPERATOR_EQUAL, sca1.getBody().get(ParameterConstants.STAFF_ID))); NeutralQuery other = (NeutralQuery) item; return matching.getCriteria().equals(other.getCriteria()); } @Override public void describeTo(Description description) { } }))).thenReturn(Arrays.asList(staff1)); Map<String, Object> seoa1Body = new HashMap<String, Object>(); seoa1Body.put(ParameterConstants.STAFF_REFERENCE, "staff1"); seoa1Body.put(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE, "edorg1"); Entity seoa1 = createEntity(EntityNames.STAFF_ED_ORG_ASSOCIATION, "seoa1", seoa1Body); Map<String, Object> seoa2Body = new HashMap<String, Object>(); seoa2Body.put(ParameterConstants.STAFF_REFERENCE, "staff1"); seoa2Body.put(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE, "edorg2"); Entity seoa2 = createEntity(EntityNames.STAFF_ED_ORG_ASSOCIATION, "seoa2", seoa2Body); Mockito.when(repo.findAll(Mockito.eq(EntityNames.STAFF_ED_ORG_ASSOCIATION), argThat(new BaseMatcher<NeutralQuery>() { @Override public boolean matches(Object item) { NeutralQuery matching = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, staff1.getEntityId())); NeutralQuery other = (NeutralQuery) item; return matching.getCriteria().equals(other.getCriteria()); } @Override public void describeTo(Description description) { } }))).thenReturn(Arrays.asList(seoa1, seoa2)); Set<String> edorgIds = arbiter.determineEdorgs(Arrays.asList(sca1), EntityNames.STAFF_COHORT_ASSOCIATION); Assert.assertEquals(2, edorgIds.size()); Assert.assertTrue(edorgIds.contains("edorg1")); Assert.assertTrue(edorgIds.contains("edorg2")); } @Test (expected = AccessDeniedException.class) public void testInvalidReference() { securityContextInjector.setEducatorContext(); Map<String, Object> body = new HashMap<String, Object>(); body.put(ParameterConstants.SECTION_ID, "section1"); final Entity gradebookEntry = createEntity(EntityNames.GRADEBOOK_ENTRY, "gradebookEntry", body); Mockito.when(repo.findAll(Mockito.eq(EntityNames.SECTION), argThat(new BaseMatcher<NeutralQuery>() { @Override public boolean matches(Object item) { NeutralQuery matching = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.OPERATOR_EQUAL, gradebookEntry.getBody().get(ParameterConstants.SECTION_ID))); NeutralQuery other = (NeutralQuery) item; return matching.getCriteria().equals(other.getCriteria()); } @Override public void describeTo(Description description) { } }))).thenReturn(new ArrayList<Entity>()); Set<String> edorgIds = arbiter.determineEdorgs(Arrays.asList(gradebookEntry), EntityNames.GRADEBOOK_ENTRY); Assert.assertNull(edorgIds); }
ZipFileProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { WorkNote workNote = exchange.getIn().getBody(WorkNote.class); String batchJobId = workNote.getBatchJobId(); if (batchJobId == null) { handleNoBatchJobIdInExchange(exchange); } else { processZipFile(exchange, batchJobId); } } @Override void process(Exchange exchange); ZipFileHandler getHandler(); void setHandler(ZipFileHandler handler); static final BatchJobStageType BATCH_JOB_STAGE; }
@Test public void testHappyZipFileProcessor() throws Exception { Exchange preObject = new DefaultExchange(new DefaultCamelContext()); String batchJobId = NewBatchJob.createId("ValidZip.zip"); Mockito.when(workNote.getBatchJobId()).thenReturn(batchJobId); preObject.getIn().setBody(workNote); Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(batchJobId))).thenReturn(mockedJob); File zipFile = IngestionTest.getFile("zip/ValidZip.zip"); ResourceEntry entry = new ResourceEntry(); entry.setResourceName(zipFile.getAbsolutePath()); Mockito.when(mockedJob.getZipResourceEntry()).thenReturn(entry); createResourceEntryAndAddToJob(zipFile, mockedJob); mockedJob.setSourceId("zip"); preObject.getIn().setHeader("BatchJobId", batchJobId); zipProc.process(preObject); Assert.assertNotNull(preObject.getIn().getBody()); } @Test public void testNoControlFileZipFileProcessor() throws Exception { Exchange preObject = new DefaultExchange(new DefaultCamelContext()); String batchJobId = NewBatchJob.createId("NoControlFile.zip"); Mockito.when(workNote.getBatchJobId()).thenReturn(batchJobId); preObject.getIn().setBody(workNote); Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(batchJobId))).thenReturn(mockedJob); File zipFile = IngestionTest.getFile("zip/NoControlFile.zip"); ResourceEntry entry = new ResourceEntry(); entry.setResourceName(zipFile.getAbsolutePath()); Mockito.when(mockedJob.getZipResourceEntry()).thenReturn(entry); createResourceEntryAndAddToJob(zipFile, mockedJob); mockedJob.setSourceId("zip"); Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(batchJobId))).thenReturn(mockedJob); preObject.getIn().setHeader("BatchJobId", batchJobId); zipProc.process(preObject); Assert.assertNotNull(preObject.getIn().getBody()); Assert.assertTrue(preObject.getIn().getBody(WorkNote.class).hasErrors()); Assert.assertEquals(preObject.getIn().getHeader("IngestionMessageType") , MessageType.BATCH_REQUEST.name()); }
EdOrgOwnershipArbiter extends OwnershipArbiter { public Set<String> determineHierarchicalEdorgs(Iterable<Entity> entities, String entityType) { Set<String> hierarchicalEdorgs = new HashSet<String>(); List<Entity> edorgs = findOwner(entities, entityType, true); for (Entity edorg : edorgs) { hierarchicalEdorgs.add(edorg.getEntityId()); hierarchicalEdorgs.addAll(helper.getParentEdOrgs(edorg)); } return hierarchicalEdorgs; } @SuppressWarnings("unused") @PostConstruct void init(); Set<String> determineEdorgs(Iterable<Entity> entities, String entityType); Set<String> determineHierarchicalEdorgs(Iterable<Entity> entities, String entityType); boolean isEntityOwnedByEdOrg(String entityType); }
@Test public void testHierarchicalEdOrgs() { securityContextInjector.setStaffContext(); Entity edorg1 = createEntity(EntityNames.SCHOOL, "edorg1", new HashMap<String, Object>()); Mockito.when(repo.findAll(Mockito.eq(EntityNames.EDUCATION_ORGANIZATION), Mockito.any(NeutralQuery.class))).thenReturn( Arrays.asList(edorg1)); Mockito.when(helper.getParentEdOrgs(edorg1)).thenReturn(Arrays.asList("edorg1Parent1", "edorg1Parent2")); Map<String, Object> attendanceBody = new HashMap<String, Object>(); attendanceBody.put(ParameterConstants.SCHOOL_ID, "edorg1"); Entity attendance = createEntity(EntityNames.ATTENDANCE, "attendance1", attendanceBody); Set<String> edorgIds = arbiter.determineHierarchicalEdorgs(Arrays.asList(attendance), EntityNames.ATTENDANCE); Assert.assertEquals(3, edorgIds.size()); Assert.assertTrue(edorgIds.contains("edorg1")); Assert.assertTrue(edorgIds.contains("edorg1Parent1")); Assert.assertTrue(edorgIds.contains("edorg1Parent2")); } @Test public void testOrphanedEntity() { securityContextInjector.setStaffContext(); Entity principalEntity = Mockito.mock(Entity.class); Mockito.when(principalEntity.getEntityId()).thenReturn("doofus1_id"); SLIPrincipal principal = Mockito.mock(SLIPrincipal.class); Mockito.when(principal.getEntity()).thenReturn(principalEntity); securityContextInjector.setOauthSecurityContext(principal, false); Mockito.when(repo.findAll(Mockito.anyString(), Mockito.any(NeutralQuery.class))).thenReturn(new ArrayList<Entity>()); Map<String, Object> metaData = new HashMap<String, Object>(); metaData.put("createdBy", "doofus1_id"); metaData.put("isOrphaned", "true"); Entity student1 = new MongoEntity(EntityNames.STUDENT, "student1", new HashMap<String, Object>(), metaData); Set<String> edorgIds = arbiter.determineHierarchicalEdorgs(Arrays.asList(student1), EntityNames.STUDENT); Assert.assertTrue(edorgIds.isEmpty()); }
ParentAccessValidator extends AccessValidator { @Override protected boolean isReadAllowed(List<String> path, MultivaluedMap<String, String> queryParameters) { List<String> subPath = null; if (path.size() == 3) { subPath = Arrays.asList(path.get(2)); } else if (path.size() == 4) { subPath = Arrays.asList(path.get(2), path.get(3)); } if (subPath != null && path.get(0).equals(ResourceNames.PARENTS) && ALLOWED_DELTA_FOR_PARENT.contains(subPath)) { return true; } return studentAccessValidator.isReadAllowed(path, queryParameters); } }
@Test public void followStudents() { paths = Arrays.asList("v1", ResourceNames.STUDENT_SCHOOL_ASSOCIATIONS, "ssa123", ResourceNames.STUDENTS); when(studentValidator.isReadAllowed(Matchers.anyListOf(String.class), any(MultivaluedMapImpl.class))).thenReturn(true); assertTrue(underTest.isAllowed(request)); paths = Arrays.asList("v1", ResourceNames.TEACHERS, "teacher123", ResourceNames.TEACHER_SECTION_ASSOCIATIONS); when(studentValidator.isReadAllowed(Matchers.anyListOf(String.class), any(MultivaluedMapImpl.class))).thenReturn(false); assertFalse(underTest.isAllowed(request)); }
EntityOwnershipValidator { public boolean canAccess(Entity entity) { return canAccess(entity, true); } boolean canAccess(Entity entity); boolean canAccess(Entity entity, boolean isTransitive); }
@Test public void testAssessment() { Entity assessment = helper.generateAssessment(); Assert.assertTrue(validator.canAccess(assessment)); } @Test public void testEdorg() { Entity edorg = helper.generateEdorgWithParent(null); Assert.assertTrue(validator.canAccess(edorg)); } @Test public void testLearningObj() { Entity obj = helper.generateLearningObjective(); Assert.assertTrue(validator.canAccess(obj)); } @Test public void testLearningStd() { Entity ls = helper.generateLearningStandard(); Assert.assertTrue(validator.canAccess(ls)); } @Test public void testProgram() { Entity prog = helper.generateProgram(); Assert.assertTrue(validator.canAccess(prog)); } @Test public void testGradingPeriod() { Entity gp = helper.generateGradingPeriod(); Assert.assertTrue(validator.canAccess(gp)); } @Test public void testStudent() { Entity student = helper.generateStudent(); helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Assert.assertFalse(validator.canAccess(student)); helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); Assert.assertTrue(validator.canAccess(student)); } @Test public void testStudentSchoolAssociation() { Entity student = helper.generateStudent(); Entity ssa = helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Assert.assertFalse(validator.canAccess(ssa)); ssa = helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); Assert.assertTrue(validator.canAccess(student)); } @Test public void testStudentSectionAssoc() { Entity student = helper.generateStudent(); helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Entity section = helper.generateSection(otherEdorg.getEntityId()); Entity ssa = helper.generateSSA(student.getEntityId(), section.getEntityId(), false); Assert.assertFalse(validator.canAccess(ssa)); section = helper.generateSection(myEdOrg.getEntityId()); helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); ssa = helper.generateSSA(student.getEntityId(), section.getEntityId(), false); Assert.assertTrue(validator.canAccess(ssa)); } @Test public void testGrade() { Entity student = helper.generateStudent(); helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Entity section = helper.generateSection(otherEdorg.getEntityId()); Entity ssa = helper.generateSSA(student.getEntityId(), section.getEntityId(), false); Entity grade = helper.generateGrade(ssa.getEntityId()); Assert.assertFalse(validator.canAccess(grade)); section = helper.generateSection(myEdOrg.getEntityId()); helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); ssa = helper.generateSSA(student.getEntityId(), section.getEntityId(), false); grade = helper.generateGrade(ssa.getEntityId()); Assert.assertTrue(validator.canAccess(grade)); } @Test public void testAttendance() { Entity att = helper.generateAttendance("blah", otherEdorg.getEntityId()); Assert.assertFalse(validator.canAccess(att)); att = helper.generateAttendance("blah", myEdOrg.getEntityId()); Assert.assertTrue(validator.canAccess(att)); } @Test public void testCohort() { Entity cohort = helper.generateCohort(otherEdorg.getEntityId()); Assert.assertFalse(validator.canAccess(cohort)); cohort = helper.generateCohort(myEdOrg.getEntityId()); Assert.assertTrue(validator.canAccess(cohort)); } @Test public void testDisciplineIncident() { Entity di = helper.generateDisciplineIncident(otherEdorg.getEntityId()); Assert.assertFalse(validator.canAccess(di)); di = helper.generateDisciplineIncident(myEdOrg.getEntityId()); Assert.assertTrue(validator.canAccess(di)); } @Test public void testGraduationPlan() { Entity gp = helper.generateGraduationPlan(otherEdorg.getEntityId()); Assert.assertFalse(validator.canAccess(gp)); gp = helper.generateGraduationPlan(myEdOrg.getEntityId()); Assert.assertTrue(validator.canAccess(gp)); } @Test public void testParent() { Entity student = helper.generateStudent(); Entity ssa = helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Entity parent = helper.generateParent(); helper.generateStudentParentAssoc(student.getEntityId(), parent.getEntityId()); Assert.assertFalse(validator.canAccess(parent)); ssa = helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); Assert.assertTrue(validator.canAccess(student)); } @Test public void testStudentParentAssoc() { Entity student = helper.generateStudent(); Entity ssa = helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Entity parent = helper.generateParent(); Entity spa = helper.generateStudentParentAssoc(student.getEntityId(), parent.getEntityId()); Assert.assertFalse(validator.canAccess(spa)); ssa = helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); Assert.assertTrue(validator.canAccess(spa)); } @Test public void testSection() { Entity sec = helper.generateSection(otherEdorg.getEntityId()); Assert.assertFalse(validator.canAccess(sec)); sec = helper.generateSection(myEdOrg.getEntityId()); Assert.assertTrue(validator.canAccess(sec)); } @Test public void testStaff() { Entity staff = helper.generateStaff(); helper.generateStaffEdorg(staff.getEntityId(), otherEdorg.getEntityId(), false); Assert.assertFalse(validator.canAccess(staff)); helper.generateStaffEdorg(staff.getEntityId(), myEdOrg.getEntityId(), false); Assert.assertTrue(validator.canAccess(staff)); } @Test public void testStaffEdOrg() { Entity staff = helper.generateStaff(); Entity staffEdorg = helper.generateStaffEdorg(staff.getEntityId(), otherEdorg.getEntityId(), false); Assert.assertFalse(validator.canAccess(staffEdorg)); staffEdorg = helper.generateStaffEdorg(staff.getEntityId(), myEdOrg.getEntityId(), false); Assert.assertTrue(validator.canAccess(staffEdorg)); } @Test public void testStaffCohort() { Entity staff = helper.generateStaff(); helper.generateStaffEdorg(staff.getEntityId(), otherEdorg.getEntityId(), false); Entity staffCohort = helper.generateStaffCohort(staff.getEntityId(), "cohortId", false, true); Assert.assertFalse(validator.canAccess(staffCohort)); helper.generateStaffEdorg(staff.getEntityId(), myEdOrg.getEntityId(), false); Assert.assertTrue(validator.canAccess(staffCohort)); } @Test public void testStaffProgram() { Entity staff = helper.generateStaff(); helper.generateStaffEdorg(staff.getEntityId(), otherEdorg.getEntityId(), false); Entity staffProgram = helper.generateStaffProgram(staff.getEntityId(), "programId", false, true); Assert.assertFalse(validator.canAccess(staffProgram)); helper.generateStaffEdorg(staff.getEntityId(), myEdOrg.getEntityId(), false); Assert.assertTrue(validator.canAccess(staffProgram)); } @Test public void testStudentCohortAssoc() { Entity student = helper.generateStudent(); Entity ssa = helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Entity cohort = helper.generateCohort(otherEdorg.getEntityId()); Entity studentCohort = helper.generateStudentCohort(student.getEntityId(), cohort.getEntityId(), false); Assert.assertFalse(validator.canAccess(studentCohort)); ssa = helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); Assert.assertTrue(validator.canAccess(studentCohort)); } @Test public void testStudentCompetency() { Entity student = helper.generateStudent(); helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Entity section = helper.generateSection(otherEdorg.getEntityId()); Entity ssa = helper.generateSSA(student.getEntityId(), section.getEntityId(), false); Entity comp = helper.generateStudentCompetency(ssa.getEntityId(), "objid"); Assert.assertFalse(validator.canAccess(comp)); section = helper.generateSection(myEdOrg.getEntityId()); helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); ssa = helper.generateSSA(student.getEntityId(), section.getEntityId(), false); comp = helper.generateStudentCompetency(ssa.getEntityId(), "objid"); Assert.assertTrue(validator.canAccess(ssa)); } @Test public void testStudentCompObj() { Entity obj = helper.generateStudentCompetencyObjective(otherEdorg.getEntityId()); Assert.assertFalse(validator.canAccess(obj)); obj = helper.generateStudentCompetencyObjective(myEdOrg.getEntityId()); Assert.assertTrue(validator.canAccess(obj)); } @Test public void testStudentDiscIncAssoc() { Entity student = helper.generateStudent(); helper.generateStudentSchoolAssociation(student.getEntityId(), otherEdorg.getEntityId(), "", false); Entity discIncAssoc = helper.generateStudentDisciplineIncidentAssociation(student.getEntityId(), "dicpId"); Assert.assertFalse(validator.canAccess(discIncAssoc)); helper.generateStudentSchoolAssociation(student.getEntityId(), myEdOrg.getEntityId(), "", false); Assert.assertTrue(validator.canAccess(discIncAssoc)); } @Test public void testStudentProgramAssoc() { Entity spa = helper.generateStudentProgram("studentId", "programId", otherEdorg.getEntityId(), false); Assert.assertFalse(validator.canAccess(spa)); spa = helper.generateStudentProgram("studentId", "programId", myEdOrg.getEntityId(), false); Assert.assertTrue(validator.canAccess(spa)); } @Test public void testTeacherSectionAssoc() { Entity staff = helper.generateStaff(); helper.generateStaffEdorg(staff.getEntityId(), otherEdorg.getEntityId(), false); Entity staffSection = helper.generateTSA(staff.getEntityId(), "sectionId", false); Assert.assertFalse(validator.canAccess(staffSection)); helper.generateStaffEdorg(staff.getEntityId(), myEdOrg.getEntityId(), false); Assert.assertTrue(validator.canAccess(staffSection)); } @Test public void testTeacherSchoolAssoc() { Entity tsa = helper.generateTeacherSchool("teacherId", otherEdorg.getEntityId()); Assert.assertFalse(validator.canAccess(tsa)); tsa = helper.generateTeacherSchool("teacherId", myEdOrg.getEntityId()); Assert.assertTrue(validator.canAccess(tsa)); } @Test public void testTeacher() { Entity teacher = helper.generateTeacher(); helper.generateTeacherSchool(teacher.getEntityId(), otherEdorg.getEntityId()); Assert.assertFalse(validator.canAccess(teacher)); helper.generateTeacherSchool(teacher.getEntityId(), myEdOrg.getEntityId()); Assert.assertTrue(validator.canAccess(teacher)); }
DeltaHashPurgeProcessor extends IngestionProcessor<WorkNote, Resource> { @Override public void process(Exchange exchange, ProcessorArgs<WorkNote> args) { String tenantId = TenantContext.getTenantId(); removeRecordHash(args.job, tenantId); } @Override void process(Exchange exchange, ProcessorArgs<WorkNote> args); static final BatchJobStageType BATCH_JOB_STAGE; }
@Test public void testPurgeDeltas() throws Exception { Mockito.when(job.getProperty(AttributeType.DUPLICATE_DETECTION.getName())).thenReturn(RecordHash.RECORD_HASH_MODE_DISABLE); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); WorkNote workNote = new WorkNote("batchJobId", false); exchange.getIn().setBody(workNote); deltaHashPurgeProcessor.process(exchange); Mockito.verify(batchJobDAO, Mockito.atLeastOnce()).removeRecordHashByTenant("tenantId"); }
DeltaProcessor extends IngestionProcessor<NeutralRecordWorkNote, Resource> { @Override public void process(Exchange exchange, ProcessorArgs<NeutralRecordWorkNote> args) { List<NeutralRecord> filteredRecords = null; List<NeutralRecord> records = args.workNote.getNeutralRecords(); if (records != null && records.size() > 0) { Metrics metrics = Metrics.newInstance(records.get(0).getSourceFile()); args.stage.addMetrics(metrics); if (!isDeltaDisabled()) { filteredRecords = filterRecords(metrics, args.workNote, args.reportStats); args.workNote.setNeutralRecords(filteredRecords); exchange.getIn().setBody(args.workNote); } exchange.getIn().setHeader(IngestionRouteBuilder.INGESTION_MESSAGE_TYPE, MessageType.PERSIST_REQUEST.name()); } } @Override void process(Exchange exchange, ProcessorArgs<NeutralRecordWorkNote> args); void setdIdStrategy(DeterministicUUIDGeneratorStrategy dIdStrategy); void setdIdResolver(DeterministicIdResolver dIdResolver); void setRecordLevelDeltaEnabledEntities(Set<String> recordLevelDeltaEnabledEntities); }
@Test public void unSupportedEntitiesTest() throws Exception { Exchange exchange = new DefaultExchange(new DefaultCamelContext()); List<NeutralRecord> neutralRecords = new ArrayList<NeutralRecord>(); neutralRecords.add(createNeutralRecord("gradingPeriod")); NeutralRecordWorkNote workNote = new NeutralRecordWorkNote(neutralRecords, "batchJobId", false); exchange.getIn().setBody(workNote); deltaProcessor.process(exchange); NeutralRecordWorkNote newWorkNote = exchange.getIn().getBody(NeutralRecordWorkNote.class); List<NeutralRecord> filteredRecords = newWorkNote.getNeutralRecords(); Assert.assertNotNull(filteredRecords); Assert.assertEquals(1, filteredRecords.size()); Assert.assertEquals("gradingPeriod", filteredRecords.get(0).getRecordType()); } @Test public void testDisableDeltaMode() throws Exception { Map<String, String> batchProperties = new HashMap<String, String>(); batchProperties.put(AttributeType.DUPLICATE_DETECTION.getName(), RecordHash.RECORD_HASH_MODE_DISABLE); Mockito.when(job.getBatchProperties()).thenReturn(batchProperties); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); List<NeutralRecord> neutralRecords = new ArrayList<NeutralRecord>(); neutralRecords.add(createNeutralRecord("gradingPeriod")); neutralRecords.add(createNeutralRecord("student")); neutralRecords.add(createNeutralRecord("grade")); NeutralRecordWorkNote workNote = new NeutralRecordWorkNote(neutralRecords, "batchJobId", false); exchange.getIn().setBody(workNote); deltaProcessor.process(exchange); NeutralRecordWorkNote newWorkNote = exchange.getIn().getBody(NeutralRecordWorkNote.class); List<NeutralRecord> filteredRecords = newWorkNote.getNeutralRecords(); Assert.assertNotNull(filteredRecords); Assert.assertEquals(3, filteredRecords.size()); Assert.assertEquals("gradingPeriod", filteredRecords.get(0).getRecordType()); Assert.assertEquals("student", filteredRecords.get(1).getRecordType()); Assert.assertEquals("grade", filteredRecords.get(2).getRecordType()); } @Test public void testPrevIngested() throws Exception{ DidSchemaParser didSchemaParser = Mockito.mock(DidSchemaParser.class); Mockito.when(dIdResolver.getDidSchemaParser()).thenReturn(didSchemaParser); Map<String, List<DidNaturalKey>> naturalKeys = new HashMap<String, List<DidNaturalKey>>(); naturalKeys.put("student", new ArrayList<DidNaturalKey>()); Mockito.when(didSchemaParser.getNaturalKeys()).thenReturn(naturalKeys); Mockito.when(dIdStrategy.generateId(Mockito.any(NaturalKeyDescriptor.class))).thenReturn("recordId"); NeutralRecord nr = createNeutralRecord("student"); List<NeutralRecord> neutralRecords = new ArrayList<NeutralRecord>(); neutralRecords.add(nr); RecordHash recordHash = Mockito.mock(RecordHash.class); String recordHashValues = nr.generateRecordHash("tenantId"); Mockito.when(recordHash.getHash()).thenReturn(recordHashValues); Mockito.when(batchJobDAO.findRecordHash("tenantId", "recordId")).thenReturn(recordHash); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); NeutralRecordWorkNote workNote = new NeutralRecordWorkNote(neutralRecords, "batchJobId", false); exchange.getIn().setBody(workNote); deltaProcessor.process(exchange); NeutralRecordWorkNote newWorkNote = exchange.getIn().getBody(NeutralRecordWorkNote.class); List<NeutralRecord> filteredRecords = newWorkNote.getNeutralRecords(); Assert.assertNotNull(filteredRecords); Assert.assertEquals(0, filteredRecords.size()); } @Test public void testNotPrevIngested() throws Exception{ NeutralRecord nr = createNeutralRecord("student"); List<NeutralRecord> neutralRecords = new ArrayList<NeutralRecord>(); neutralRecords.add(nr); DidSchemaParser didSchemaParser = Mockito.mock(DidSchemaParser.class); Mockito.when(dIdResolver.getDidSchemaParser()).thenReturn(didSchemaParser); Map<String, List<DidNaturalKey>> naturalKeysMap = new HashMap<String, List<DidNaturalKey>>(); naturalKeysMap.put(nr.getRecordType(), new ArrayList<DidNaturalKey>()); Mockito.when(didSchemaParser.getNaturalKeys()).thenReturn(naturalKeysMap); Mockito.when(dIdStrategy.generateId(Mockito.any(NaturalKeyDescriptor.class))).thenReturn("recordId"); Mockito.when(batchJobDAO.findRecordHash("tenantId", "recordId")).thenReturn(null); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); NeutralRecordWorkNote workNote = new NeutralRecordWorkNote(neutralRecords, "batchJobId", false); exchange.getIn().setBody(workNote); deltaProcessor.process(exchange); NeutralRecordWorkNote newWorkNote = exchange.getIn().getBody(NeutralRecordWorkNote.class); List<NeutralRecord> filteredRecords = newWorkNote.getNeutralRecords(); Assert.assertNotNull(filteredRecords); Assert.assertEquals(1, filteredRecords.size()); Assert.assertEquals("student", filteredRecords.get(0).getRecordType()); }
TeacherToTeacherSectionAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.TEACHER_SECTION_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.TEACHER_ID, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.getSLIPrincipal().getEntity().getEntityId())); nq.addCriteria(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); Iterable<String> tsaIds = getRepo().findAllIds(EntityNames.TEACHER_SECTION_ASSOCIATION, nq); return Sets.newHashSet(tsaIds); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test(expected = IllegalArgumentException.class) public void testValidateWrongType() { val.validate(EntityNames.ASSESSMENT, new HashSet<String>(Arrays.asList("Jomolungma"))); } @Test public void testSuccessOne() { Entity tsa = this.vth.generateTSA(USER_ID, SECTION_ID, false); Set<String> ids = Collections.singleton(tsa.getEntityId()); Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); } @Test public void testSuccessMulti() { Set<String> ids = new HashSet<String>(); for (int i = 0; i < 100; i++) { ids.add(this.vth.generateTSA(USER_ID, SECTION_ID, false).getEntityId()); } Assert.assertTrue(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); } @Test public void testWrongId() { Set<String> ids = Collections.singleton("Hammerhands"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); ids = Collections.singleton("Nagas"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE,ids).equals(ids)); ids = Collections.singleton("Phantom Warriors"); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); } @Test public void testHeterogenousList() { Set<String> ids = new HashSet<String>(Arrays .asList(this.vth.generateTSA(USER_ID, SECTION_ID, false).getEntityId(), this.vth.generateTSA("Ssss'ra", "Arcanus", false).getEntityId(), this.vth.generateTSA("Kali", "Arcanus", false).getEntityId())); Assert.assertFalse(val.validate(CORRECT_ENTITY_TYPE, ids).equals(ids)); }
GlobalEntityValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isTransitive && isGlobalWrite(entityType) && !isStudentOrParent(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> entityIds); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidationStaff() throws Exception { assertTrue(validator.canValidate(EntityNames.ASSESSMENT, true)); assertFalse(validator.canValidate(EntityNames.ASSESSMENT, false)); assertTrue(validator.canValidate(EntityNames.LEARNING_OBJECTIVE, true)); assertFalse(validator.canValidate(EntityNames.LEARNING_OBJECTIVE, false)); assertTrue(validator.canValidate(EntityNames.LEARNING_STANDARD, true)); assertFalse(validator.canValidate(EntityNames.LEARNING_STANDARD, false)); assertTrue(validator.canValidate(EntityNames.COMPETENCY_LEVEL_DESCRIPTOR, true)); assertFalse(validator.canValidate(EntityNames.COMPETENCY_LEVEL_DESCRIPTOR, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, true)); } @Test public void testCanValidationTeacher() throws Exception { injector.setEducatorContext(); assertTrue(validator.canValidate(EntityNames.ASSESSMENT, true)); assertFalse(validator.canValidate(EntityNames.ASSESSMENT, false)); assertTrue(validator.canValidate(EntityNames.LEARNING_OBJECTIVE, true)); assertFalse(validator.canValidate(EntityNames.LEARNING_OBJECTIVE, false)); assertTrue(validator.canValidate(EntityNames.LEARNING_STANDARD, true)); assertFalse(validator.canValidate(EntityNames.LEARNING_STANDARD, false)); assertTrue(validator.canValidate(EntityNames.COMPETENCY_LEVEL_DESCRIPTOR, true)); assertFalse(validator.canValidate(EntityNames.COMPETENCY_LEVEL_DESCRIPTOR, false)); assertFalse(validator.canValidate(EntityNames.COHORT, true)); }
GlobalEntityValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> entityIds) throws IllegalStateException { Set<String> result = new HashSet<String>(); if(areParametersValid(GLOBAL_WRITE_RESOURCE, entityType, entityIds)) { result = entityIds; } return result; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> entityIds); @Override SecurityUtil.UserContext getContext(); }
@Test public void testValidateSingleAssessment() throws Exception { HashSet<String> assessmentIds = new HashSet<String>(); assessmentIds.add(helper.generateAssessment().getEntityId()); assertTrue(validator.validate(EntityNames.ASSESSMENT, assessmentIds).containsAll(assessmentIds)); } @Test public void testValidateMultipleAssessments() throws Exception { HashSet<String> assessmentIds = new HashSet<String>(); assessmentIds.add(helper.generateAssessment().getEntityId()); assessmentIds.add(helper.generateAssessment().getEntityId()); assessmentIds.add(helper.generateAssessment().getEntityId()); assertTrue(validator.validate(EntityNames.ASSESSMENT, assessmentIds).containsAll(assessmentIds)); } @Test public void testValidateSingleLearningObjective() throws Exception { HashSet<String> learningObjectiveIds = new HashSet<String>(); learningObjectiveIds.add(helper.generateLearningObjective().getEntityId()); assertTrue(validator.validate(EntityNames.LEARNING_OBJECTIVE, learningObjectiveIds).containsAll(learningObjectiveIds)); } @Test public void testValidateMultipleLearningObjectives() throws Exception { HashSet<String> learningObjectiveIds = new HashSet<String>(); learningObjectiveIds.add(helper.generateLearningObjective().getEntityId()); learningObjectiveIds.add(helper.generateLearningObjective().getEntityId()); learningObjectiveIds.add(helper.generateLearningObjective().getEntityId()); assertTrue(validator.validate(EntityNames.LEARNING_OBJECTIVE, learningObjectiveIds).containsAll(learningObjectiveIds)); } @Test public void testValidateSingleLearningStandard() throws Exception { HashSet<String> learningStandardIds = new HashSet<String>(); learningStandardIds.add(helper.generateLearningStandard().getEntityId()); assertTrue(validator.validate(EntityNames.LEARNING_STANDARD, learningStandardIds).containsAll(learningStandardIds)); } @Test public void testValidateMultipleLearningStandards() throws Exception { HashSet<String> learningStandardIds = new HashSet<String>(); learningStandardIds.add(helper.generateLearningStandard().getEntityId()); learningStandardIds.add(helper.generateLearningStandard().getEntityId()); learningStandardIds.add(helper.generateLearningStandard().getEntityId()); assertTrue(validator.validate(EntityNames.LEARNING_STANDARD, learningStandardIds).containsAll(learningStandardIds)); } @Test public void testValidateSingleCompetencyLevelDescriptor() throws Exception { HashSet<String> competencyLevelDescriptorIds = new HashSet<String>(); competencyLevelDescriptorIds.add(helper.generateCompetencyLevelDescriptor().getEntityId()); assertTrue(validator.validate(EntityNames.COMPETENCY_LEVEL_DESCRIPTOR, competencyLevelDescriptorIds).containsAll(competencyLevelDescriptorIds)); } @Test public void testValidateMultipleCompetencyLevelDescriptors() throws Exception { HashSet<String> competencyLevelDescriptorIds = new HashSet<String>(); competencyLevelDescriptorIds.add(helper.generateCompetencyLevelDescriptor().getEntityId()); competencyLevelDescriptorIds.add(helper.generateCompetencyLevelDescriptor().getEntityId()); competencyLevelDescriptorIds.add(helper.generateCompetencyLevelDescriptor().getEntityId()); assertTrue(validator.validate(EntityNames.COMPETENCY_LEVEL_DESCRIPTOR, competencyLevelDescriptorIds).containsAll(competencyLevelDescriptorIds)); } @Test(expected = IllegalArgumentException.class) public void testGuards() throws Exception { validator.validate(EntityNames.STUDENT, new HashSet<String>(Arrays.asList("student1", "student2"))); }
TransitiveTeacherToStaffEdOrgAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.STAFF_ED_ORG_ASSOCIATION.equals(entityType) && isTeacher() && isTransitive; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STAFF_ED_ORG_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STAFF_ED_ORG_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, true)); }
TransitiveTeacherToStaffEdOrgAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STAFF_ED_ORG_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } Map<String, Set<String>> requiredEdOrgsToSEOAs = new HashMap<String, Set<String>>(); { Iterable<Entity> requestedAssociations = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids))); for (Entity entity : requestedAssociations) { String id = (String) entity.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE); if (!requiredEdOrgsToSEOAs.containsKey(id)) { requiredEdOrgsToSEOAs.put(id, new HashSet<String>()); } requiredEdOrgsToSEOAs.get(id).add(entity.getEntityId()); } } Set<String> teachersEdOrgs = new HashSet<String>(); { NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.principalId())); Iterable<Entity> teachersAssociations = this.repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, query); for (Entity entity : teachersAssociations) { if (!dateHelper.isFieldExpired(entity.getBody(), ParameterConstants.END_DATE)) { teachersEdOrgs.add((String) entity.getBody().get(ParameterConstants.EDUCATION_ORGANIZATION_REFERENCE)); } } } return getValidIds(teachersEdOrgs, requiredEdOrgsToSEOAs); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidateNonExpiredAssociation() { helper.generateStaffEdorg(helper.STAFF_ID, helper.ED_ORG_ID, false); Entity assoc = helper.generateStaffEdorg("staff2", helper.ED_ORG_ID, false); edOrgAssociationIds.add(assoc.getEntityId()); assertTrue(validator.validate(EntityNames.STAFF_ED_ORG_ASSOCIATION, edOrgAssociationIds).equals(edOrgAssociationIds)); } @Test public void testInvalidateExpiredAssociation() { helper.generateStaffEdorg(helper.STAFF_ID, helper.ED_ORG_ID, true); Entity assoc = helper.generateStaffEdorg("staff2", helper.ED_ORG_ID, false); edOrgAssociationIds.add(assoc.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_ED_ORG_ASSOCIATION, edOrgAssociationIds).equals(edOrgAssociationIds)); }
StaffToTeacherValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean through) { return EntityNames.TEACHER.equals(entityType) && isStaff(); } @Override boolean canValidate(String entityType, boolean through); @Override Set<String> validate(String entityName, Set<String> teacherIds); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidateStaffToTeacher() throws Exception { setupCurrentUser(staff1); setupCommonTSAs(); assertTrue(validator.canValidate(EntityNames.TEACHER, true)); assertTrue(validator.canValidate(EntityNames.TEACHER, false)); }
StaffToTeacherValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityName, Set<String> teacherIds) throws IllegalStateException { if (!areParametersValid(EntityNames.TEACHER, entityName, teacherIds)) { return Collections.EMPTY_SET; } NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.CRITERIA_IN, teacherIds)); Iterable<Entity> schoolAssoc = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); Map<String, Set<String>> teacherSchoolMap = new HashMap<String, Set<String>>(); populateMapFromMongoResponse(teacherSchoolMap, schoolAssoc); Set<String> edOrgLineage = getStaffEdOrgLineage(); Set<String> validTeacherIds = new HashSet<String>(); for (String teacher : teacherSchoolMap.keySet()) { Set<String> tmpSet = new HashSet<String>(teacherSchoolMap.get(teacher)); tmpSet.retainAll(edOrgLineage); if (tmpSet.size() != 0) { validTeacherIds.add(teacher); } } return validTeacherIds; } @Override boolean canValidate(String entityType, boolean through); @Override Set<String> validate(String entityName, Set<String> teacherIds); @Override SecurityUtil.UserContext getContext(); }
@Test public void testInvalidTeacherAssociation() { setupCurrentUser(staff1); setupCommonTSAs(); Set<String> teacher = new HashSet<String>(Arrays.asList(teacher2.getEntityId())); assertTrue(validator.validate(EntityNames.TEACHER, teacher).isEmpty()); } @Test public void testValidAndInvalidTeacherAssociation() { setupCurrentUser(staff1); setupCommonTSAs(); Set<String> teachers = new HashSet<String>(Arrays.asList(teacher1.getEntityId(), teacher2.getEntityId())); assertTrue(validator.validate(EntityNames.TEACHER, teachers).equals(new HashSet<String>(Arrays.asList(teacher1.getEntityId())))); } @Test public void testValidAssociationThroughSchool() { setupCurrentUser(staff2); setupCommonTSAs(); Set<String> teachers = new HashSet<String>(Arrays.asList(teacher1.getEntityId(), teacher3.getEntityId())); assertTrue(validator.validate(EntityNames.TEACHER, teachers).equals(teachers)); } @Test public void testValidAssociationThroughLEA() { setupCurrentUser(staff1); setupCommonTSAs(); Set<String> teachers = new HashSet<String>(Arrays.asList(teacher1.getEntityId(), teacher3.getEntityId())); assertTrue(validator.validate(EntityNames.TEACHER, teachers).equals(teachers)); } @Test public void testInvalidTeacher() { setupCurrentUser(staff1); setupCommonTSAs(); Set<String> teachers = new HashSet<String>(Arrays.asList(UUID.randomUUID().toString())); assertFalse(validator.validate(EntityNames.TEACHER, teachers).equals(teachers)); } @Test public void testExpiredTeacher() { setupCurrentUser(staff1); helper.generateStaffEdorg(teacher1.getEntityId(), school1.getEntityId(), true); Set<String> teacher = new HashSet<String>(Arrays.asList(teacher1.getEntityId())); assertFalse(validator.validate(EntityNames.TEACHER, teacher).equals(teacher)); helper.generateStaffEdorg(teacher1.getEntityId(), school1.getEntityId(), false); teacher = new HashSet<String>(Arrays.asList(teacher1.getEntityId())); assertTrue(validator.validate(EntityNames.TEACHER, teacher).equals(teacher)); } @Test public void testNoTeacher() { setupCurrentUser(staff1); assertTrue(validator.validate(EntityNames.TEACHER, new HashSet<String>()).isEmpty()); }
TransitiveTeacherToStaffValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean transitive) { return transitive && EntityNames.STAFF.equals(entityType) && isTeacher(); } @Override boolean canValidate(String entityType, boolean transitive); @Override Set<String> validate(String entityName, Set<String> staffIds); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidateTeacherToStaff() throws Exception { assertTrue(validator.canValidate(EntityNames.STAFF, true)); assertFalse(validator.canValidate(EntityNames.STAFF, false)); }
TransitiveTeacherToStaffValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityName, Set<String> staffIds) throws IllegalStateException { if (!areParametersValid(EntityNames.STAFF, entityName, staffIds)) { return Collections.EMPTY_SET; } NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria("staffReference", NeutralCriteria.CRITERIA_IN, staffIds)); basicQuery.setIncludeFields(Arrays.asList("educationOrganizationReference", "staffReference")); NeutralCriteria endDateCriteria = new NeutralCriteria(ParameterConstants.END_DATE, NeutralCriteria.CRITERIA_GTE, getFilterDate(true)); basicQuery.addOrQuery(new NeutralQuery(new NeutralCriteria(ParameterConstants.END_DATE, NeutralCriteria.CRITERIA_EXISTS, false))); basicQuery.addOrQuery(new NeutralQuery(endDateCriteria)); Iterable<Entity> edOrgAssoc = repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, basicQuery); Map<String, List<String>> staffEdorgMap = new HashMap<String, List<String>>(); populateMapFromMongoResponse(staffEdorgMap, edOrgAssoc); Set<String> schools = new HashSet<String>(); schools.addAll(getDirectEdorgs()); Set<String> validStaffIds = new HashSet<String>(); for (Map.Entry entry: staffEdorgMap.entrySet()) { List<String> edorgs = (List<String>) entry.getValue(); HashSet<String> tmpSchools = new HashSet<String>(schools); tmpSchools.retainAll(edorgs); if (tmpSchools.size() != 0) { validStaffIds.add((String) entry.getKey()); } } return validStaffIds; } @Override boolean canValidate(String entityType, boolean transitive); @Override Set<String> validate(String entityName, Set<String> staffIds); @Override SecurityUtil.UserContext getContext(); }
@Test public void testInvalidTeacherStaffAssociation() { Set<String> ids = new HashSet<String>(Arrays.asList(staff1.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, ids).equals(ids)); } @Test public void testValidTeacherStaffAssociationNoEndDate() { Set<String> ids = new HashSet<String>(Arrays.asList(staff2.getEntityId())); assertTrue(validator.validate(EntityNames.STAFF, ids).equals(ids)); } @Test public void testValidTeacherStaffAssociationWithEndDate() { Set<String> ids = new HashSet<String>(Arrays.asList(staff3.getEntityId())); assertTrue(validator.validate(EntityNames.STAFF, ids).equals(ids)); } @Test public void testExpiredTeacherStaffAssociation() { Set<String> ids = new HashSet<String>(Arrays.asList(staff4.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, ids).equals(ids)); } @Test public void testStaffWithNoEdorgAssociation() { Set<String> ids = new HashSet<String>(Arrays.asList(staff2.getEntityId(), staff5.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, ids).equals(ids)); } @Test public void testMulti1() { Set<String> ids = new HashSet<String>(Arrays.asList(staff1.getEntityId(), staff2.getEntityId(), staff3.getEntityId(), staff4.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, ids).equals(ids)); } @Test public void testMulti2() { Set<String> ids = new HashSet<String>(Arrays.asList(staff1.getEntityId(), staff4.getEntityId())); assertFalse(validator.validate(EntityNames.STAFF, ids).equals(ids)); } @Test public void testMulti3() { Set<String> ids = new HashSet<String>(Arrays.asList(staff2.getEntityId(), staff3.getEntityId())); assertTrue(validator.validate(EntityNames.STAFF, ids).equals(ids)); }
StudentToStudentParentAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { Set<String> validIds = new HashSet<String>(); if (!areParametersValid(EntityNames.STUDENT_PARENT_ASSOCIATION, entityType, ids)) { return Collections.emptySet(); } Entity entity = SecurityUtil.getSLIPrincipal().getEntity(); List<Entity> elist = entity.getEmbeddedData().get("studentParentAssociation"); if (elist != null ) { for (Entity e : elist) { validIds.add(e.getEntityId()); } } validIds.retainAll(ids); return validIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
@Test public void testValidStudentParentAssociation() { Set<String> ids = new HashSet<String>(); for (Entity e : studentParentAssociationList) { String s = e.getEntityId(); ids.add(s); } boolean valid = validator.validate(EntityNames.STUDENT_PARENT_ASSOCIATION, ids).containsAll(ids); Assert.assertTrue(valid); } @Test public void testOneInvalidStudentParentAssociation() { Set<String> ids = new HashSet<String>(); for (Entity e : studentParentAssociationList) { String s = e.getEntityId(); ids.add(s); } ids.add("invalidID"); boolean valid = validator.validate(EntityNames.STUDENT_PARENT_ASSOCIATION, ids).containsAll(ids); Assert.assertTrue(!valid); } @Test public void testEmptyStudentParentAssociation() { Set<String> ids = new HashSet<String>(); ids.add("invalidID"); boolean valid = validator.validate(EntityNames.STUDENT_PARENT_ASSOCIATION, ids).containsAll(ids); Assert.assertTrue(!valid); }
JobReportingProcessor implements Processor { @Override public void process(Exchange exchange) { WorkNote workNote = exchange.getIn().getBody(WorkNote.class); if (workNote == null || workNote.getBatchJobId() == null) { missingBatchJobIdError(exchange); } else { processJobReporting(exchange, workNote); } } @Override void process(Exchange exchange); File getLogFile(NewBatchJob job); File createFile(NewBatchJob job, String fileName); void setCommandTopicUri(String commandTopicUri); void setBatchJobDAO(BatchJobDAO batchJobDAO); void setTenantDA(TenantDA tenantDA); static final BatchJobStageType BATCH_JOB_STAGE; static final String JOB_STAGE_RESOURCE_ID; static final String ORCHESTRATION_STAGES_NAME; static final String ORCHESTRATION_STAGES_DESC; static final String ERROR_FILE_TYPE; static final String WARNING_FILE_TYPE; }
@Test public void testProcess() throws Exception { List<ResourceEntry> mockedResourceEntries = createFakeResourceEntries(); List<Stage> mockedStages = createFakeStages(); Map<String, String> mockedProperties = createFakeBatchProperties(); NewBatchJob mockedJob = new NewBatchJob(BATCHJOBID, "192.168.59.11", "finished", 1, mockedProperties, mockedStages, mockedResourceEntries); mockedJob.setTopLevelSourceId(TEMP_DIR); Iterable<Error> fakeErrorIterable = createFakeErrorIterable(); RangedWorkNote workNote = RangedWorkNote.createSimpleWorkNote(BATCHJOBID); List<Stage> mockDeltaStage = new LinkedList<Stage>(); List<Metrics> mockDeltaMetrics = new LinkedList<Metrics>(); List<Stage> mockPersistenceStages = new LinkedList<Stage>(); List<Metrics> mockPersistenceMetrics = new LinkedList<Metrics>(); Metrics duplicateCountMetric = new Metrics(RESOURCEID, RECORDS_CONSIDERED, RECORDS_FAILED); HashMap<String, Long> dupMap = new HashMap<String, Long>(); dupMap.put(DUP_ENTITY, DUP_COUNT); duplicateCountMetric.setDuplicateCounts(dupMap); mockDeltaMetrics.add(duplicateCountMetric); mockDeltaStage.add(new Stage(BatchJobStageType.DELTA_PROCESSOR.getName(), "Drop records that are duplicates", "finished", new Date(), new Date(), mockDeltaMetrics)); mockPersistenceMetrics.add(new Metrics(RESOURCEID, RECORDS_CONSIDERED, RECORDS_FAILED,RECORDS_DELETED)); mockPersistenceStages.add(new Stage(BatchJobStageType.PERSISTENCE_PROCESSOR.getName(), "Persists records to the sli database", "finished", new Date(), new Date(), mockPersistenceMetrics)); Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(BATCHJOBID))).thenReturn(mockedJob); Mockito.when(mockedBatchJobDAO.getBatchJobStages(Matchers.eq(BATCHJOBID), Matchers.eq(BatchJobStageType.DELTA_PROCESSOR))).thenReturn(mockDeltaStage); Mockito.when(mockedBatchJobDAO.getBatchJobStages(Matchers.eq(BATCHJOBID), Matchers.eq(BatchJobStageType.PERSISTENCE_PROCESSOR))).thenReturn(mockPersistenceStages); Mockito.when( mockedBatchJobDAO.getBatchJobErrors(Matchers.eq(BATCHJOBID), Matchers.eq(RESOURCEID), Matchers.eq(FaultType.TYPE_ERROR), Matchers.anyInt())).thenReturn(fakeErrorIterable); Mockito.when( mockedBatchJobDAO.getBatchJobErrors(Matchers.eq(BATCHJOBID), (String) Matchers.isNull(), Matchers.eq(FaultType.TYPE_ERROR), Matchers.anyInt())).thenReturn(fakeErrorIterable); Mockito.when( mockedBatchJobDAO.getBatchJobErrors(Matchers.eq(BATCHJOBID), Matchers.eq(RESOURCEID), Matchers.eq(FaultType.TYPE_WARNING), Matchers.anyInt())).thenReturn(fakeErrorIterable); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); exchange.getIn().setBody(workNote, RangedWorkNote.class); jobReportingProcessor.setBatchJobDAO(mockedBatchJobDAO); jobReportingProcessor.setTenantDA(mockedTenantDA); jobReportingProcessor.process(exchange); FileReader fr = new FileReader(TEMP_DIR + OUTFILE); BufferedReader br = new BufferedReader(fr); assertTrue(br.readLine().contains("jobId: " + BATCHJOBID)); assertTrue(br.readLine().contains( "[file] " + RESOURCEID + " (" + FileFormat.EDFI_XML.getCode() + "/" + FileType.XML_STUDENT_PARENT_ASSOCIATION.getName() + ")")); assertTrue(br.readLine().contains("[file] " + RESOURCEID + " records considered for processing: " + RECORDS_CONSIDERED)); assertTrue(br.readLine().contains("[file] " + RESOURCEID + " records ingested successfully: " + RECORDS_PASSED)); assertTrue(br.readLine().contains("[file] " + RESOURCEID + " records deleted successfully: " + RECORDS_DELETED)); assertTrue(br.readLine().contains("[file] " + RESOURCEID + " records failed processing: " + RECORDS_FAILED)); assertTrue(br.readLine().contains("[file] " + RESOURCEID + " records not considered for processing: " + 0)); assertTrue(br.readLine().contains("[configProperty] purge: false")); assertTrue(br.readLine().contains(RESOURCEID + " " + DUP_ENTITY + " " + DUP_COUNT + " deltas!")); assertTrue(br.readLine().contains("Not all records were processed completely due to errors.")); assertTrue(br.readLine().contains("Processed " + RECORDS_CONSIDERED + " records.")); String errorFileName = getErrorFileName(); fr = new FileReader(TEMP_DIR + errorFileName); br = new BufferedReader(fr); assertTrue(br.readLine().contains("ERROR " + ERRORDETAIL)); assertTrue(br.readLine().contains("ERROR " + NULLERRORDETAIL)); fr.close(); }
GenericToGlobalClassPeriodWriteValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.CLASS_PERIOD, entityType, ids)) { return Collections.emptySet(); } Set<String> edOrgLineage = getEdorgDescendents(getDirectEdorgs()); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids, false)); query.addCriteria(new NeutralCriteria(ParameterConstants.EDUCATION_ORGANIZATION_ID, NeutralCriteria.CRITERIA_IN, edOrgLineage)); return Sets.newHashSet(getRepo().findAllIds(entityType, query)); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testFilterClassPeriodDataFromLEA() { setupStaff(staffLea, lea.getEntityId()); Set<String> expectedIds = new HashSet<String>(Arrays.asList(classPeriodLea.getEntityId(), classPeriodSchoolLea.getEntityId())); Set<String> actual = validator.validate(EntityNames.CLASS_PERIOD, classPeriodIds); Assert.assertEquals(expectedIds, actual); } @Test public void testFilterClassPeriodDataFromSchool() { setupStaff(staffSchoolLea, schoolParentLea.getEntityId()); Set<String> expectedIds = new HashSet<String>(Arrays.asList(classPeriodSchoolLea.getEntityId())); Set<String> actual = validator.validate(EntityNames.CLASS_PERIOD, classPeriodIds); Assert.assertEquals(expectedIds, actual); } @Test public void testFilterClassPeriodDataFromSchool2() { setupStaff(staffSchoolNoParent, schoolNoParent.getEntityId()); Set<String> expectedIds = new HashSet<String>(Arrays.asList(classPeriodSchoolNoParent.getEntityId())); Set<String> actual = validator.validate(EntityNames.CLASS_PERIOD, classPeriodIds); Assert.assertEquals(expectedIds, actual); }
TeacherToStudentCohortAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.STUDENT_COHORT_ASSOCIATION.equals(entityType) && isTeacher(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidate() { setupCurrentUser(teacher1); Assert.assertTrue(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, false)); Assert.assertTrue(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, true)); injector.setStaffContext(); SecurityUtil.setUserContext(SecurityUtil.UserContext.STAFF_CONTEXT); Assert.assertFalse(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, false)); Assert.assertFalse(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, true)); }
TeacherToStudentCohortAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STUDENT_COHORT_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery query = new NeutralQuery( new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); query.setIncludeFields(Arrays.asList(ParameterConstants.COHORT_ID)); Map<String, Set<String>> cohortIdToSca = new HashMap<String, Set<String>>(); Iterable<Entity> scas = getRepo().findAll(EntityNames.STUDENT_COHORT_ASSOCIATION, query); for (Entity sca : scas) { String cohortId = sca.getBody().get(ParameterConstants.COHORT_ID).toString(); if(!cohortIdToSca.containsKey(cohortId)) { cohortIdToSca.put(cohortId, new HashSet<String>()); } cohortIdToSca.get(cohortId).add(sca.getEntityId()); } String teacherId = SecurityUtil.getSLIPrincipal().getEntity().getEntityId(); NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.COHORT_ID, NeutralCriteria.CRITERIA_IN, cohortIdToSca.keySet())); nq.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, teacherId)); nq.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_RECORD_ACCESS, NeutralCriteria.OPERATOR_EQUAL, true)); Iterable<Entity> entities = getRepo().findAll(EntityNames.STAFF_COHORT_ASSOCIATION, nq); Set<String> validCohortIds = new HashSet<String>(); for (Entity entity : entities) { String expireDate = (String) entity.getBody().get(ParameterConstants.END_DATE); if (expireDate == null || isLhsBeforeRhs(getNowMinusGracePeriod(), getDateTime(expireDate))) { validCohortIds.add((String) entity.getBody().get(ParameterConstants.COHORT_ID)); } } return getValidIds(validCohortIds, cohortIdToSca); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testValidAccessTeacher1() { setupCurrentUser(teacher1); Set<String> ids = new HashSet<String>(Arrays.asList(studentCohortAssoc1.getEntityId())); Assert.assertTrue(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, ids).equals(ids)); } @Test public void testValidAccessTeacher2() { setupCurrentUser(teacher2); Set<String> ids = new HashSet<String>(Arrays.asList(studentCohortAssoc2.getEntityId())); Assert.assertTrue(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, ids).equals(ids)); } @Test public void testInvalidAccessTeacher1() { setupCurrentUser(teacher1); Set<String> ids = new HashSet<String>(Arrays.asList(studentCohortAssoc2.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(studentCohortAssoc3.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, ids).equals(ids)); } @Test public void testInvalidAccessTeacher2() { setupCurrentUser(teacher2); Set<String> ids = new HashSet<String>(Arrays.asList(studentCohortAssoc1.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(studentCohortAssoc3.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, ids).equals(ids)); } @Test public void testMulti() { setupCurrentUser(teacher2); Set<String> ids = new HashSet<String>(Arrays.asList(studentCohortAssoc2.getEntityId(), studentCohortAssoc1.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, ids).equals(ids)); }
LandingZoneProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { Stage stage = Stage.createAndStartStage(LZ_STAGE, LZ_STAGE_DESC); String batchJobId = null; ReportStats reportStats = new SimpleReportStats(); NewBatchJob currentJob = null; File lzFile = exchange.getIn().getHeader("filePath", File.class); boolean hasErrors = false; String lzDirectoryPathName = lzFile.getParent(); if (!isValidLandingZone(lzDirectoryPathName)) { hasErrors = true; LOG.error("LandingZoneProcessor: {} is not a valid landing zone.", lzDirectoryPathName); reportStats.incError(); } else { currentJob = createNewBatchJob(lzFile); createResourceEntryAndAddToJob(lzFile, currentJob); batchJobId = currentJob.getId(); String lzFileName = lzFile.getName(); if (!isZipFile(lzFileName)) { hasErrors = true; handleProcessingError(exchange, batchJobId, lzFileName, lzDirectoryPathName, reportStats); } BatchJobUtils.stopStageAndAddToJob(stage, currentJob); batchJobDAO.saveBatchJob(currentJob); } setExchangeBody(exchange, reportStats, currentJob, hasErrors); } @Override void process(Exchange exchange); static final BatchJobStageType LZ_STAGE; }
@Test public void testValidLz() throws Exception { File validLzPathFile = new File("/test/lz/inbound/TEST-LZ/testFile.zip"); String validLzPathname = validLzPathFile.getParent(); List<String> testLzPaths = new ArrayList<String>(); testLzPaths.add(validLzPathname); when(mockedTenantDA.getLzPaths()).thenReturn(testLzPaths); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); exchange.getIn().setHeader("filePath", validLzPathFile.getPath()); landingZoneProcessor.process(exchange); assertFalse("Header on exchange should indicate success", exchange.getIn().getBody(WorkNote.class).hasErrors()); } @Test public void testInvalidLz() throws Exception { File validLzPathFile = new File("/test/lz/inbound/TEST-LZ/testFile.zip"); String validLzPathname = validLzPathFile.getParent(); List<String> testLzPaths = new ArrayList<String>(); testLzPaths.add(validLzPathname); when(mockedTenantDA.getLzPaths()).thenReturn(testLzPaths); File inValidLzPathFile = new File("/test/lz/inbound/BAD-TEST-LZ/testFile.zip"); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); exchange.getIn().setHeader("filePath", inValidLzPathFile.getPath()); landingZoneProcessor.process(exchange); assertTrue("Header on exchange should indicate failure", exchange.getIn().getBody(WorkNote.class).hasErrors()); } @Test public void testNonZipFileInLz() throws Exception { File unzippedLzPathFile = new File("/test/lz/inbound/TEST-LZ/testFile.ctl"); String validLzPathname = unzippedLzPathFile.getParent(); List<String> testLzPaths = new ArrayList<String>(); testLzPaths.add(validLzPathname); when(mockedTenantDA.getLzPaths()).thenReturn(testLzPaths); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); exchange.getIn().setHeader("filePath", unzippedLzPathFile.getPath()); landingZoneProcessor.process(exchange); assertTrue("Header on exchange should indicate failure", exchange.getIn().getBody(WorkNote.class).hasErrors()); }
StudentDenyAllValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isStudentOrParent() && (STUDENT_DENIED_ENTITIES.contains(entityType) || (isTransitive && EntityNames.isPublic(entityType)) || (!isTransitive && NON_TRANSITIVE_DENY_ALL .contains(entityType))); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.DISCIPLINE_ACTION, true)); assertTrue(validator.canValidate(EntityNames.DISCIPLINE_ACTION, false)); assertTrue(validator.canValidate(EntityNames.DISCIPLINE_INCIDENT, true)); assertTrue(validator.canValidate(EntityNames.DISCIPLINE_INCIDENT, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_GRADEBOOK_ENTRY, false)); assertTrue(validator.canValidate(EntityNames.PROGRAM, true)); assertFalse(validator.canValidate(EntityNames.PROGRAM, false)); }
StudentDenyAllValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { return Collections.emptySet(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
@Test public void testValidate() { Assert.assertEquals(Collections.emptySet(), validator.validate(null, null)); Assert.assertEquals(Collections.emptySet(), validator.validate(new String(), new HashSet<String>())); }
TeacherToStudentProgramAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.STUDENT_PROGRAM_ASSOCIATION.equals(entityType) && isTeacher(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidate() { Assert.assertTrue(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, false)); Assert.assertTrue(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, true)); }
TeacherToStudentProgramAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STUDENT_PROGRAM_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery query = new NeutralQuery( new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); query.setIncludeFields(Arrays.asList(ParameterConstants.PROGRAM_ID)); Map<String, Set<String>> programIdsToSPA = new HashMap<String, Set<String>>(); Iterable<Entity> spas = getRepo().findAll(EntityNames.STUDENT_PROGRAM_ASSOCIATION, query); for (Entity spa : spas) { String programId = (String) spa.getBody().get(ParameterConstants.PROGRAM_ID); if (!programIdsToSPA.containsKey(programId)) { programIdsToSPA.put(programId, new HashSet<String>()); } programIdsToSPA.get(programId).add(spa.getEntityId()); } String teacherId = SecurityUtil.getSLIPrincipal().getEntity().getEntityId(); NeutralQuery nq = new NeutralQuery(new NeutralCriteria(ParameterConstants.PROGRAM_ID, NeutralCriteria.CRITERIA_IN, programIdsToSPA.keySet())); nq.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, teacherId)); nq.addCriteria(new NeutralCriteria(ParameterConstants.STUDENT_RECORD_ACCESS, NeutralCriteria.OPERATOR_EQUAL, true)); Iterable<Entity> entities = getRepo().findAll(EntityNames.STAFF_PROGRAM_ASSOCIATION, nq); Set<String> validProgramIds = new HashSet<String>(); for (Entity entity : entities) { String expireDate = (String) entity.getBody().get(ParameterConstants.END_DATE); if (expireDate == null || isLhsBeforeRhs(getNowMinusGracePeriod(), getDateTime(expireDate))) { validProgramIds.add((String) entity.getBody().get(ParameterConstants.PROGRAM_ID)); } } return getValidIds(validProgramIds, programIdsToSPA); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testValidAccessTeacher() { Set<String> ids = new HashSet<String>(Arrays.asList(studentProgramAssoc1.getEntityId())); Assert.assertTrue(validator.validate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, ids).equals(ids)); } @Test public void testInvalidAccessTeacher1() { Set<String> ids = new HashSet<String>(Arrays.asList(studentProgramAssoc2.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(studentProgramAssoc3.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(studentProgramAssoc4.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, ids).equals(ids)); ids = new HashSet<String>(Arrays.asList(studentProgramAssoc5.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, ids).equals(ids)); ids = new HashSet<String>( Arrays.asList(studentProgramAssoc1.getEntityId(), studentProgramAssoc3.getEntityId())); Assert.assertFalse(validator.validate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, ids).equals(ids)); }
TeacherToDisciplineIncidentValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isTeacher() && EntityNames.DISCIPLINE_INCIDENT.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.DISCIPLINE_INCIDENT, true)); assertTrue(validator.canValidate(EntityNames.DISCIPLINE_INCIDENT, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); }
TeacherToDisciplineIncidentValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.DISCIPLINE_INCIDENT, entityType, ids)) { return Collections.EMPTY_SET; } Set<String> discIncidentIds = new HashSet<String>(ids); String myself = SecurityUtil.getSLIPrincipal().getEntity().getEntityId(); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, discIncidentIds)); query.addCriteria(new NeutralCriteria(ParameterConstants.STAFF_ID, NeutralCriteria.OPERATOR_EQUAL, myself)); Iterable<Entity> incidents = getRepo().findAll(EntityNames.DISCIPLINE_INCIDENT, query); for (Entity ent : incidents) { discIncidentIds.remove(ent.getEntityId()); } if (discIncidentIds.size() == 0) { return ids; } query = new NeutralQuery(new NeutralCriteria(ParameterConstants.DISCIPLINE_INCIDENT_ID, NeutralCriteria.CRITERIA_IN, discIncidentIds)); query.setIncludeFields(Arrays.asList(ParameterConstants.STUDENT_ID, ParameterConstants.DISCIPLINE_INCIDENT_ID)); Iterable<Entity> assocs = getRepo().findAll(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, query); Map<String, Set<String>> discIncToStudents = new HashMap<String, Set<String>>(); for (Entity assoc : assocs) { String studentId = (String) assoc.getBody().get(ParameterConstants.STUDENT_ID); String discIncId = (String) assoc.getBody().get(ParameterConstants.DISCIPLINE_INCIDENT_ID); Set<String> studentList = discIncToStudents.get(discIncId); if (studentList == null) { studentList = new HashSet<String>(); discIncToStudents.put(discIncId, studentList); } studentList.add(studentId); } Set<String> validIncidents = new HashSet<String>(ids); validIncidents.removeAll(discIncidentIds); for (String discIncId : discIncToStudents.keySet()) { Set<String> validStudent = studentValidator.validate(EntityNames.STUDENT, discIncToStudents.get(discIncId)); if (validStudent.size() > 0) { validIncidents.add(discIncId); } } return validIncidents; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testValidIncident() { Set<String> ids = list(disciplineIncident1.getEntityId()); assertTrue(validator.validate(EntityNames.DISCIPLINE_INCIDENT, ids).equals(ids)); ids = list(disciplineIncident2.getEntityId()); assertTrue(validator.validate(EntityNames.DISCIPLINE_INCIDENT, ids).equals(ids)); ids = list(disciplineIncident1.getEntityId(), disciplineIncident2.getEntityId()); assertTrue(validator.validate(EntityNames.DISCIPLINE_INCIDENT, ids).equals(ids)); ids = list(disciplineIncident4.getEntityId()); assertTrue(validator.validate(EntityNames.DISCIPLINE_INCIDENT, ids).equals(ids)); } @Test public void testInvalidIncident() { Set<String> ids = list(disciplineIncident3.getEntityId()); assertFalse(validator.validate(EntityNames.DISCIPLINE_INCIDENT, ids).equals(ids)); ids = list(disciplineIncident3.getEntityId(), disciplineIncident1.getEntityId()); assertFalse(validator.validate(EntityNames.DISCIPLINE_INCIDENT, ids).equals(ids)); }
StaffToSubStudentEntityValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean through) { return isStaff() && isSubEntityOfStudent(entityType); } @Override boolean canValidate(String entityType, boolean through); @SuppressWarnings("unchecked") @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidateStaffToReportCard() { assertTrue(validator.canValidate(EntityNames.REPORT_CARD, false)); } @Test public void testCanValidateStaffToAttendance() throws Exception { assertTrue(validator.canValidate(EntityNames.ATTENDANCE, false)); } @Test public void testCanValidateStaffToDisciplineAction() throws Exception { assertTrue(validator.canValidate(EntityNames.DISCIPLINE_ACTION, false)); } @Test public void testCanValidateStaffToStudentAcademicRecord() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_ACADEMIC_RECORD, false)); } @Test public void testCanValidateStaffToStudentAssessment() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_ASSESSMENT, false)); } @Test public void testCanValidateStaffToStudentDisciplineIncident() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_DISCIPLINE_INCIDENT_ASSOCIATION, false)); } @Test public void testCanValidateStaffToStudentGradebookEntry() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_GRADEBOOK_ENTRY, false)); } @Test public void testCanValidateStaffToStudentParentAssociation() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_PARENT_ASSOCIATION, false)); } @Test public void testCanValidateStaffToStudentSchoolAssociation() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, false)); } @Test public void testCanValidateStaffToStudentSectionAssociation() throws Exception { assertTrue(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, false)); } @Test public void testCanNotValidateOtherEntities() throws Exception { assertFalse(validator.canValidate(EntityNames.STUDENT, false)); }
StaffToSubStudentEntityValidator extends AbstractContextValidator { @SuppressWarnings("unchecked") @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(SUB_ENTITIES_OF_STUDENT, entityType, ids)) { return Collections.EMPTY_SET; } Map<String, Set<String>> students = new HashMap<String, Set<String>>(); NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, new ArrayList<String>(ids))); Iterable<Entity> entities = getRepo().findAll(entityType, query); if (entities != null) { for (Entity entity : entities) { Map<String, Object> body = entity.getBody(); Object studentInfo = body.get(ParameterConstants.STUDENT_ID); if (studentInfo instanceof Collection) { students = putStudents((Collection<String>) studentInfo, entity.getEntityId(), students); } else if (studentInfo instanceof String) { students = putStudents(Arrays.asList((String) studentInfo), entity.getEntityId(), students); } } } Set<String> validStudents = validator.validate(EntityNames.STUDENT, students.keySet()); return getValidIds(validStudents, students); } @Override boolean canValidate(String entityType, boolean through); @SuppressWarnings("unchecked") @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanGetAccessToReportCard() { Set<String> studentIds = new HashSet<String>(); Set<String> reportCards = new HashSet<String>(); Map<String, Object> reportCard1 = buildReportCard("student123"); Entity reportCardEntity = new MongoEntity("reportCard", reportCard1); reportCards.add(reportCardEntity.getEntityId()); studentIds.add("student123"); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.REPORT_CARD), Mockito.any(NeutralQuery.class))).thenReturn(Arrays.asList(reportCardEntity)); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); assertTrue(validator.validate(EntityNames.REPORT_CARD, reportCards).equals(reportCards)); } @Test public void testCanGetAccessToAttendance() throws Exception { Set<String> studentIds = new HashSet<String>(); Set<String> attendances = new HashSet<String>(); Map<String, Object> attendance1 = buildAttendanceForStudent("student123", "school123"); Entity attendanceEntity1 = new MongoEntity("attendance", attendance1); attendances.add(attendanceEntity1.getEntityId()); studentIds.add("student123"); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.ATTENDANCE), Mockito.any(NeutralQuery.class))).thenReturn( Arrays.asList(attendanceEntity1)); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); assertTrue(validator.validate(EntityNames.ATTENDANCE, attendances).equals(attendances)); } @Test public void testCanNotGetAccessToAttendance() throws Exception { Set<String> attendances = new HashSet<String>(); Map<String, Object> attendance1 = buildAttendanceForStudent("student123", "school123"); Entity attendanceEntity1 = new MongoEntity("attendance", attendance1); attendances.add(attendanceEntity1.getEntityId()); studentIds.add("student123"); Mockito.when(mockRepo.findAll(Mockito.eq(EntityNames.ATTENDANCE), Mockito.any(NeutralQuery.class))).thenReturn( Arrays.asList(attendanceEntity1)); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(Collections.EMPTY_SET); assertFalse(validator.validate(EntityNames.ATTENDANCE, attendances).equals(attendances)); } @Test public void testCanGetAccessToCurrentStudentSchoolAssociation() throws Exception { Map<String, Object> goodStudentSchoolAssociation = buildStudentSchoolAssociation("student123", "school123", new DateTime().plusHours(1)); Entity association = new MongoEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, goodStudentSchoolAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); studentIds.add("student123"); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); assertTrue(validator.validate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, associations).equals(associations)); } @Test public void testCanGetAccessToStudentSchoolAssociationWithoutExitWithdrawDate() throws Exception { Map<String, Object> goodStudentSchoolAssociation = buildStudentSchoolAssociation("student123", "school123"); Entity association = new MongoEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, goodStudentSchoolAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); studentIds.add("student123"); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); assertTrue(validator.validate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, associations).equals(associations)); } @Test public void testDeniedAccessToExpiredStudentSchoolAssociation() throws Exception { Map<String, Object> badStudentSchoolAssociation = buildStudentSchoolAssociation("student123", "school123", new DateTime().minusDays(1)); Entity association = new MongoEntity(EntityNames.STUDENT_SCHOOL_ASSOCIATION, badStudentSchoolAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SCHOOL_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); assertTrue(validator.validate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, associations).isEmpty()); } @Test public void testCanGetAccessToCurrentStudentSectionAssociation() throws Exception { Map<String, Object> goodStudentSectionAssociation = buildStudentSectionAssociation("student123", "section123", new DateTime().plusDays(1)); Entity association = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, goodStudentSectionAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); studentIds.add("student123"); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); assertTrue(validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, associations).equals(associations)); } @Test public void testCanGetAccessToStudentSectionAssociationWithoutEndDate() throws Exception { Map<String, Object> goodStudentSectionAssociation = buildStudentSectionAssociation("student123", "section123"); Entity association = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, goodStudentSectionAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); studentIds.add("student123"); Mockito.when(staffToStudentValidator.validate(EntityNames.STUDENT, studentIds)).thenReturn(studentIds); assertTrue(validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, associations).equals(associations)); } @Test public void testDeniedAccessToExpiredStudentSectionAssociation() throws Exception { Map<String, Object> badStudentSectionAssociation = buildStudentSchoolAssociation("student123", "section123", new DateTime().minusDays(1)); Entity association = new MongoEntity(EntityNames.STUDENT_SECTION_ASSOCIATION, badStudentSectionAssociation); Mockito.when( mockRepo.findAll(Mockito.eq(EntityNames.STUDENT_SECTION_ASSOCIATION), Mockito.any(NeutralQuery.class))) .thenReturn(Arrays.asList(association)); Set<String> associations = new HashSet<String>(); associations.add(association.getEntityId()); assertTrue(validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, associations).isEmpty()); }
StudentToStudentCompetencyValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isStudentOrParent() && EntityNames.STUDENT_COMPETENCY.equals(entityType); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STUDENT_COMPETENCY, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_COMPETENCY, false)); assertFalse(validator.canValidate(EntityNames.GRADEBOOK_ENTRY, true)); assertFalse(validator.canValidate(EntityNames.PROGRAM, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_COMPETENCY_OBJECTIVE, true)); }
ControlFileProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { processUsingNewBatchJob(exchange); MongoTrackingAspect.aspectOf().reset(); } @Override void process(Exchange exchange); static final BatchJobStageType BATCH_JOB_STAGE; }
@Test public void shouldAcceptExchangeObjectReadExchangeControlFileAndSetExchangeBatchJob() throws Exception { Exchange preObject = new DefaultExchange(new DefaultCamelContext()); WorkNote workNote = Mockito.mock(WorkNote.class); String batchJobId = NewBatchJob.createId("InterchangeStudentCsv.ctl"); NewBatchJob mockedJob = Mockito.mock(NewBatchJob.class); Mockito.when(mockedJob.getBatchProperties()).thenReturn(new HashMap <String, String>()); Mockito.when(workNote.getBatchJobId()).thenReturn(batchJobId); Mockito.when(mockedBatchJobDAO.findBatchJobById(Matchers.eq(batchJobId))).thenReturn(mockedJob); preObject.getIn().setBody(workNote); processor.process(preObject); boolean hasErrors = (Boolean) preObject.getIn().getHeader("hasErrors"); assertNotNull("header [hasErrors] not set", hasErrors); }
StudentToStudentCompetencyValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STUDENT_COMPETENCY, entityType, ids)) { return Collections.emptySet(); } Map<String, Set<String>> ssaToSC = getIdsContainedInFieldOnEntities(entityType, new ArrayList<String>( ids), ParameterConstants.STUDENT_SECTION_ASSOCIATION_ID); if (ssaToSC.isEmpty()) { return Collections.emptySet(); } Map<String, Set<String>> studentIdsToSSA = getIdsContainedInFieldOnEntities(EntityNames.STUDENT_SECTION_ASSOCIATION, new ArrayList<String>(ssaToSC.keySet()), ParameterConstants.STUDENT_ID); if (studentIdsToSSA.isEmpty()) { return Collections.emptySet(); } Set<String> studentIds = studentIdsToSSA.keySet(); studentIds.retainAll(getDirectStudentIds()); Set<String> validSSAIds = getValidIds(studentIds, studentIdsToSSA); Set<String> validSCIds = getValidIds(validSSAIds, ssaToSC); return validSCIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
@Test public void testSingleValidate() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(competency1.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_COMPETENCY, idsToValidate).containsAll(idsToValidate)); } @Test public void testNegativeHeterogeneousValidate() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(competency1.getEntityId(),competency2.getEntityId())); assertFalse(validator.validate(EntityNames.STUDENT_COMPETENCY, idsToValidate).containsAll(idsToValidate)); }
TeacherToStaffEdOrgAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return EntityNames.STAFF_ED_ORG_ASSOCIATION.equals(entityType) && isTeacher() && !isTransitive; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STAFF_ED_ORG_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STAFF_ED_ORG_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, false)); assertFalse(validator.canValidate(EntityNames.ATTENDANCE, true)); }
TeacherToStaffEdOrgAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STAFF_ED_ORG_ASSOCIATION, entityType, ids)) { return Collections.EMPTY_SET; } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.STAFF_REFERENCE, NeutralCriteria.OPERATOR_EQUAL, SecurityUtil.principalId())); Iterable<Entity> entities = this.repo.findAll(EntityNames.STAFF_ED_ORG_ASSOCIATION, query); Set<String> validIds = new HashSet<String>(); for (Entity entity : entities) { if (!dateHelper.isFieldExpired(entity.getBody(), ParameterConstants.END_DATE)) { validIds.add(entity.getEntityId()); } } validIds.retainAll(ids); return validIds; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidateNonExpiredAssociation() { Set<String> edOrgAssociationIds = new HashSet<String>(); Entity assoc = helper.generateStaffEdorg(helper.STAFF_ID, helper.ED_ORG_ID, false); edOrgAssociationIds.add(assoc.getEntityId()); assertTrue(validator.validate(EntityNames.STAFF_ED_ORG_ASSOCIATION, edOrgAssociationIds).containsAll(edOrgAssociationIds)); } @Test public void testInvalidateExpiredAssociation() { Set<String> edOrgAssociationIds = new HashSet<String>(); Entity assoc = helper.generateStaffEdorg(helper.STAFF_ID, helper.ED_ORG_ID, true); edOrgAssociationIds.add(assoc.getEntityId()); assertFalse(validator.validate(EntityNames.STAFF_ED_ORG_ASSOCIATION, edOrgAssociationIds).containsAll(edOrgAssociationIds)); }
StudentToStudentSectionAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return isStudentOrParent() && EntityNames.STUDENT_SECTION_ASSOCIATION.equals(entityType) && !isTransitive; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_SCHOOL_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.PROGRAM, false)); assertFalse(validator.canValidate(EntityNames.ASSESSMENT, true)); assertFalse(validator.canValidate(EntityNames.GRADEBOOK_ENTRY, true)); assertFalse(validator.canValidate(EntityNames.COHORT, true)); assertFalse(validator.canValidate(EntityNames.STAFF_COHORT_ASSOCIATION, false)); }
StudentToStudentSectionAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(EntityNames.STUDENT_SECTION_ASSOCIATION, entityType, ids)) { return Collections.emptySet(); } NeutralQuery query = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); for(Entity ssa : getRepo().findAll(EntityNames.STUDENT_SECTION_ASSOCIATION, query)) { Map<String, Object> body = ssa.getBody(); if (!getDirectStudentIds().contains(body.get(ParameterConstants.STUDENT_ID))) { return Collections.emptySet(); } } return ids; } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); }
@Test public void testPositiveValidate() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(assoc1Current.getEntityId(), assoc1Past.getEntityId())); assertTrue(validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, idsToValidate).containsAll(idsToValidate)); } @Test public void testHeterogeneousValidate() { Set<String> idsToValidate = new HashSet<String>(Arrays.asList(assoc1Current.getEntityId(), assoc2.getEntityId())); assertFalse(validator.validate(EntityNames.STUDENT_SECTION_ASSOCIATION, idsToValidate).containsAll(idsToValidate)); }
StaffToStudentCohortProgramAssociationValidator extends AbstractContextValidator { @Override public boolean canValidate(String entityType, boolean isTransitive) { return STUDENT_ASSOCIATIONS.contains(entityType) && isStaff(); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidate() { assertTrue(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_COHORT_ASSOCIATION, true)); assertTrue(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, false)); assertTrue(validator.canValidate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.SECTION, true)); assertFalse(validator.canValidate(EntityNames.SECTION, false)); assertFalse(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, true)); assertFalse(validator.canValidate(EntityNames.STUDENT_SECTION_ASSOCIATION, false)); }
StaffToStudentCohortProgramAssociationValidator extends AbstractContextValidator { @Override public Set<String> validate(String entityType, Set<String> ids) throws IllegalStateException { if (!areParametersValid(STUDENT_ASSOCIATIONS, entityType, ids)) { return Collections.EMPTY_SET; } Map<String, Set<String>> associations = new HashMap<String, Set<String>>(); NeutralQuery basicQuery = new NeutralQuery(new NeutralCriteria(ParameterConstants.ID, NeutralCriteria.CRITERIA_IN, ids)); Iterable<Entity> assocs = getRepo().findAll(entityType, basicQuery); for (Entity assoc : assocs) { String studentId = (String) assoc.getBody().get(ParameterConstants.STUDENT_ID); if (!isFieldExpired(assoc.getBody(), ParameterConstants.END_DATE, true)) { if (!associations.containsKey(studentId)) { associations.put(studentId, new HashSet<String>()); } associations.get(studentId).add(assoc.getEntityId()); } } Set<String> validStudents = studentValidator.validate(EntityNames.STUDENT, associations.keySet()); return getValidIds(validStudents, associations); } @Override boolean canValidate(String entityType, boolean isTransitive); @Override Set<String> validate(String entityType, Set<String> ids); @Override SecurityUtil.UserContext getContext(); }
@Test public void testCanValidateValidCohortAssociation() { Mockito.when(mockStudentValidator.validate(Mockito.eq(EntityNames.STUDENT), Mockito.any(Set.class))) .thenReturn(new HashSet<String>(Arrays.asList("Boop"))); for (int i = 0; i < 10; ++i) { cohortIds.add(helper.generateStudentCohort("Boop", "" + i, false).getEntityId()); } assertTrue(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); } @Test public void testCanValidateValidProgramAssociation() { Mockito.when(mockStudentValidator.validate(Mockito.eq(EntityNames.STUDENT), Mockito.any(Set.class))) .thenReturn(new HashSet<String>(Arrays.asList("Boop"))); for (int i = 0; i < 10; ++i) { programIds.add(helper.generateStudentProgram("Boop", "" + i, false).getEntityId()); } assertTrue(validator.validate(EntityNames.STUDENT_PROGRAM_ASSOCIATION, programIds).equals(programIds)); } @Test public void testCanNotValidExpiredAssociation() { Mockito.when(mockStudentValidator.validate(Mockito.eq(EntityNames.STUDENT), Mockito.any(Set.class))) .thenReturn(new HashSet<String>(Arrays.asList("Boop"))); cohortIds.add(helper.generateStudentCohort("Boop", "Beep", true).getEntityId()); assertFalse(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); } @Test public void testCanNotValidateAssociationWithoutStudentAccess() { Mockito.when(mockStudentValidator.validate(Mockito.eq(EntityNames.STUDENT), Mockito.any(Set.class))) .thenReturn(new HashSet<String>(Arrays.asList("dummy"))); for (int i = 0; i < 10; ++i) { cohortIds.add(helper.generateStudentCohort("Boop", "" + i, false).getEntityId()); } assertFalse(validator.validate(EntityNames.STUDENT_COHORT_ASSOCIATION, cohortIds).equals(cohortIds)); }
TenantProcessor implements Processor { @Override public void process(Exchange exchange) throws Exception { try { createNewLandingZones(); exchange.getIn().setHeader(TENANT_POLL_HEADER, TENANT_POLL_SUCCESS); doPreloads(); } catch (Exception e) { exchange.getIn().setHeader(TENANT_POLL_HEADER, TENANT_POLL_FAILURE); LOG.error("Exception encountered adding tenant", e); } } @Override void process(Exchange exchange); static final String TENANT_POLL_HEADER; static final String TENANT_POLL_SUCCESS; static final String TENANT_POLL_FAILURE; }
@Test public void shouldAddNewLz() throws Exception { List<String> testLzPaths = new ArrayList<String>(); testLzPaths.add("."); when(mockedTenantDA.getLzPaths()).thenReturn(testLzPaths); Exchange exchange = new DefaultExchange(new DefaultCamelContext()); tenantProcessor.process(exchange); assertEquals("Header on exchange should indicate success", TenantProcessor.TENANT_POLL_SUCCESS, exchange .getIn().getHeader(TenantProcessor.TENANT_POLL_HEADER)); }