src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
SpringAwareRuleBookRunner extends RuleBookRunner implements ApplicationContextAware { @Override protected Object getRuleInstance(Class<?> rule) { if (_applicationContext == null) { throw new IllegalStateException("Cannot instantiate RuleBookRunner because " + "Spring application context is not available."); } try { return _applicationContext.getBean(rule); } catch (BeansException e) { return super.getRuleInstance(rule); } } SpringAwareRuleBookRunner(String rulePackage); SpringAwareRuleBookRunner(Class<? extends RuleBook> ruleBookClass, String rulePackage); SpringAwareRuleBookRunner(String rulePackage, Predicate<String> subPkgMatch); SpringAwareRuleBookRunner(
Class<? extends RuleBook> ruleBookClass, String rulePackage, Predicate<String> subPkgMatch); @Override void setApplicationContext(ApplicationContext applicationContext); }
|
@Test public void ruleRunnerShouldReturnNullRuleClassIsInvalid() { Class clazz = Class.class; Assert.assertNull(_ruleBook.getRuleInstance(clazz)); }
|
FactMap implements NameValueReferableMap<T> { @Override public void clear() { _facts.clear(); } FactMap(Map<String, NameValueReferable<T>> facts); @SafeVarargs FactMap(NameValueReferable<T>... facts); FactMap(); @Override T getOne(); @Override T getValue(String name); @Deprecated String getStrVal(String name); @Deprecated Integer getIntVal(String name); @Deprecated Double getDblVal(String name); void setValue(String name, T value); @Override Fact<T> put(NameValueReferable<T> fact); @Override Fact<T> put(String key, NameValueReferable<T> fact); @Override int size(); @Override boolean isEmpty(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @Override Fact<T> get(Object key); @Override Fact<T> remove(Object key); @Override void putAll(Map<? extends String, ? extends NameValueReferable<T>> map); @Override void clear(); @Override Set<String> keySet(); @Override Collection<NameValueReferable<T>> values(); @Override Set<Entry<String, NameValueReferable<T>>> entrySet(); @Override String toString(); }
|
@Test public void clearShouldDelegateToMap() { Map<String, Object> map = Mockito.mock(Map.class); FactMap factMap = new FactMap(map); factMap.clear(); Mockito.verify(map, Mockito.times(1)).clear(); }
|
RuleBookFactoryBean implements FactoryBean<RuleBook> { @Override public RuleBook getObject() throws Exception { if (_package != null) { if (_ruleBookType != null) { return new RuleBookRunner(_ruleBookType, _package); } return new RuleBookRunner(_package); } if (_ruleBookType != null) { return RuleBookBuilder.create(_ruleBookType).build(); } return new CoRRuleBook(); } @Deprecated RuleBookFactoryBean(Class<? extends RuleBook> ruleBookType, String pkg); RuleBookFactoryBean(Class<? extends RuleBook> ruleBookType); @Deprecated RuleBookFactoryBean(String pkg); @Override RuleBook getObject(); @Override Class<?> getObjectType(); @Override boolean isSingleton(); }
|
@Test public void ruleBookFactoryBeanShouldBeCreatedUsingOnlyPackageName() throws Exception { RuleBookFactoryBean factoryBean = new RuleBookFactoryBean("com.deliveredtechnologies.rulebook.spring"); RuleBook<String> ruleBook = (RuleBook<String>)factoryBean.getObject(); ruleBook.run(_facts); Assert.assertEquals("valueTwo", _facts.getValue("value2")); Assert.assertEquals("firstRule", ruleBook.getResult().get().getValue()); }
@Test public void ruleBookFactoryBeanShouldBeCreatedUsingOnlyClassName() throws Exception { RuleBookFactoryBean factoryBean = new RuleBookFactoryBean(CoRRuleBook.class); RuleBook<String> ruleBook = (RuleBook<String>)factoryBean.getObject(); ruleBook.addRule(RuleBuilder.create().withFactType(String.class) .given(_facts) .when(facts -> facts.getValue("value1").equals("Value")) .then(facts -> facts.setValue("value1", "Value One")) .build()); ruleBook.run(_facts); Assert.assertEquals("Value One", _facts.getValue("value1")); }
@Test public void ruleBookFactoryBeanShouldBeCreatedUsingClassAndPackageName() throws Exception { RuleBookFactoryBean factoryBean = new RuleBookFactoryBean( CoRRuleBook.class, "com.deliveredtechnologies.rulebook.spring"); RuleBook<String> ruleBook = (RuleBook<String>)factoryBean.getObject(); ruleBook.run(_facts); Assert.assertEquals("valueTwo", _facts.getValue("value2")); Assert.assertEquals("firstRule", ruleBook.getResult().get().getValue()); }
@Test public void ruleBookFactoryBeanShouldBeCreatedEvenIfBothClassAndPackageAreNull() throws Exception { RuleBookFactoryBean factoryBean = new RuleBookFactoryBean(null, null); RuleBook<String> ruleBook = (RuleBook<String>)factoryBean.getObject(); ruleBook.addRule(RuleBuilder.create().withFactType(String.class) .given(_facts) .when(facts -> facts.getValue("value1").equals("Value")) .then(facts -> facts.setValue("value1", "Value One")) .build()); ruleBook.run(_facts); Assert.assertEquals("Value One", _facts.getValue("value1")); }
|
Result implements Referable<T> { public void reset() { _lock.readLock().lock(); try { if (_defaultValue == null) { return; } } finally { _lock.readLock().unlock(); } setValue(_defaultValue); } Result(); Result(T value); void reset(); @Override T getValue(); @Override void setValue(T value); @Override String toString(); }
|
@Test public void resetWithNoDefaultValueSetDoesNotError() { Result<String> result = new Result<>(); result.reset(); }
|
Result implements Referable<T> { @Override public String toString() { _lock.readLock().lock(); try { long key = Thread.currentThread().getId(); if (_valueMap.containsKey(key)) { return _valueMap.get(key).toString(); } if (_defaultValue != null) { return _defaultValue.toString(); } return ""; } finally { _lock.readLock().unlock(); } } Result(); Result(T value); void reset(); @Override T getValue(); @Override void setValue(T value); @Override String toString(); }
|
@Test public void toStringWithNoValueReturnsToStringOnDefaultValue() { Result<String> result = new Result<>("Default"); Assert.assertEquals("Default", result.toString()); }
@Test public void toStringWithNoValueOrDefaultReturnsBlankString() { Result<String> result = new Result<>(); Assert.assertEquals("", result.toString()); }
|
AnnotationUtils { @SuppressWarnings("unchecked") public static List<Field> getAnnotatedFields(Class annotation, Class clazz) { if (clazz == Object.class) { return new ArrayList<>(); } List<Field> fields = (List<Field>)Arrays.stream(clazz.getDeclaredFields()) .filter(field -> field.getAnnotation(annotation) != null) .collect(Collectors.toList()); if (clazz.getSuperclass() != null) { fields.addAll(getAnnotatedFields(annotation, clazz.getSuperclass())); } return fields; } private AnnotationUtils(); @SuppressWarnings("unchecked") static List<Field> getAnnotatedFields(Class annotation, Class clazz); static Optional<Field> getAnnotatedField(Class annotation, Class clazz); @SuppressWarnings("unchecked") static List<Method> getAnnotatedMethods(Class annotation, Class clazz); static Optional<Method> getAnnotatedMethod(Class annotation, Class clazz); @SuppressWarnings("unchecked") static A getAnnotation(Class<A> annotation, Class<?> clazz); }
|
@Test public void getAnnotatedFieldsShouldFindAnnotatedFields() { List<Field> givenFields = getAnnotatedFields(Given.class, SampleRuleWithResult.class); List<Field> resultFields = getAnnotatedFields(Result.class, SampleRuleWithResult.class); Assert.assertEquals(11, givenFields.size()); Assert.assertEquals(1, resultFields.size()); }
@Test public void getAnnotatedFieldsShouldFindAnnotatedFieldsInParentClasses() { List<Field> givenFields = getAnnotatedFields(Given.class, SubRuleWithResult.class); List<Field> resultFields = getAnnotatedFields(Result.class, SubRuleWithResult.class); Assert.assertEquals(12, givenFields.size()); Assert.assertEquals(1, resultFields.size()); }
|
SessionAdapter implements TokenAdapter<InternalSession> { public int findIndexOfValidField(String blob) { for (Field field : AttributeCompressionStrategy.getAllValidFields(InternalSession.class)) { String search = JSONSerialisation.jsonAttributeName(field.getName()); int index = blob.indexOf(search); if (index != -1) { return index; } } return -1; } @Inject SessionAdapter(TokenIdFactory tokenIdFactory, CoreTokenConfig config,
JSONSerialisation serialisation, LDAPDataConversion dataConversion,
TokenBlobUtils blobUtils); Token toToken(InternalSession session); InternalSession fromToken(Token token); int findIndexOfValidField(String blob); String filterLatestAccessTime(Token token); }
|
@Test public void shouldLocateValidFieldInJSON() { String json = "{\"clientDomain\":null,\"creationTime\":1376307674,\"isISStored\":true,\"latestAccessTime\":1376308558,\"maxCachingTime\":3}"; assertEquals(1, adapter.findIndexOfValidField(json)); }
@Test public void shouldIndicateNoValidFieldsInJSON() { assertEquals(-1, adapter.findIndexOfValidField("")); }
|
SAMLAdapter implements TokenAdapter<SAMLToken> { public Token toToken(SAMLToken samlToken) { String tokenId = tokenIdFactory.toSAMLPrimaryTokenId(samlToken.getPrimaryKey()); Token token = new Token(tokenId, TokenType.SAML2); Calendar timestamp = dataConversion.fromEpochedSeconds(samlToken.getExpiryTime()); token.setExpiryTimestamp(timestamp); String className = samlToken.getToken().getClass().getName(); token.setAttribute(SAMLTokenField.OBJECT_CLASS.getField(), className); String secondaryKey = samlToken.getSecondaryKey(); if (secondaryKey != null) { secondaryKey = tokenIdFactory.toSAMLSecondaryTokenId(secondaryKey); token.setAttribute(SAMLTokenField.SECONDARY_KEY.getField(), secondaryKey); } String jsonBlob = serialisation.serialise(samlToken.getToken()); blobUtils.setBlobFromString(token, jsonBlob); return token; } @Inject SAMLAdapter(TokenIdFactory tokenIdFactory, JSONSerialisation serialisation,
LDAPDataConversion dataConversion, TokenBlobUtils blobUtils); Token toToken(SAMLToken samlToken); SAMLToken fromToken(Token token); }
|
@Test public void shouldNotStoreSecondaryKeyIfNull() { SAMLToken samlToken = new SAMLToken("primary", null, 12345, ""); given(tokenIdFactory.toSAMLPrimaryTokenId(anyString())).willReturn("id"); given(serialisation.serialise(anyObject())).willReturn(""); Token token = adapter.toToken(samlToken); assertThat(token.getValue(SAMLTokenField.SECONDARY_KEY.getField())).isNull(); }
|
OAuthAdapter implements TokenAdapter<JsonValue> { public Token toToken(JsonValue request) { assertObjectIsAMap(request); Set<String> idSet = (Set<String>) request.get(TokenIdFactory.ID).getObject(); String id = null; if (idSet != null && !idSet.isEmpty()){ id = tokenIdFactory.getOAuthTokenId(idSet.iterator().next()); } else { id = tokenIdFactory.getOAuthTokenId(null); } request.get(TokenIdFactory.ID).setObject(id); Token token = new Token(id, TokenType.OAUTH); Map<String,Object> values = request.asMap(); if (values != null) { for (OAuthTokenField field : OAuthTokenField.values()) { String key = field.getOAuthField(); if (values.containsKey(key)) { Object value = values.get(key); if (OAuthTokenField.ID.getOAuthField().equals(key)) { continue; } if (OAuthTokenField.EXPIRY_TIME.getOAuthField().equals(key)) { if (!Collection.class.isAssignableFrom(value.getClass())) { throw new IllegalStateException("Date must be in a collection"); } value = oAuthValues.getDateValue((Collection<String>) value); } else if (value instanceof Collection) { value = oAuthValues.getSingleValue((Collection<String>) value); } token.setAttribute(field.getField(), value); } } } Object objectToStore = request.getObject(); String serialisedObject = serialisation.serialise(objectToStore); blobUtils.setBlobFromString(token, serialisedObject); return token; } @Inject OAuthAdapter(TokenIdFactory tokenIdFactory, JSONSerialisation serialisation,
OAuthValues oAuthValues, TokenBlobUtils blobUtils); Token toToken(JsonValue request); JsonValue fromToken(Token token); static final String VALUE; }
|
@Test public void shouldSerialiseSimpleString() { OAuthAdapter adapter = generateOAuthAdapter(); Set<String> text = new HashSet<String>(); text.add("badger"); OAuthTokenField field = OAuthTokenField.PARENT; Map<String, Object> values = new HashMap<String, Object>(); values.put(field.getOAuthField(), text); JsonValue jsonValue = makeDefaultJsonValue(values); Token result = adapter.toToken(jsonValue); assert(result.getValue(field.getField()).toString().contains("badger")); }
@Test public void shouldSerialiseCollectionOfStrings() { OAuthAdapter adapter = generateOAuthAdapter(); String one = "badger"; String two = "weasel"; String three = "ferret"; OAuthTokenField field = OAuthTokenField.SCOPE; Map<String, Object> values = new HashMap<String, Object>(); values.put(field.getOAuthField(), Arrays.asList(new String[]{one, two, three})); JsonValue jsonValue = makeDefaultJsonValue(values); String result = adapter.toToken(jsonValue).getValue(field.getField()); assertTrue(result.contains(one)); assertTrue(result.contains(two)); assertTrue(result.contains(three)); }
@Test (expectedExceptions = IllegalStateException.class) public void shouldNotAllowASingleDate() { OAuthAdapter adapter = generateOAuthAdapter(); String text = "1234567890"; OAuthTokenField field = OAuthTokenField.EXPIRY_TIME; Map<String, Object> values = new HashMap<String, Object>(); values.put(field.getOAuthField(), text); JsonValue jsonValue = makeDefaultJsonValue(values); adapter.toToken(jsonValue); }
@Test public void shouldSerialiseACollectionOfTimestamps() { OAuthAdapter adapter = generateOAuthAdapter(); String timestamp = "1370425721197"; OAuthTokenField field = OAuthTokenField.EXPIRY_TIME; Map<String, Object> values = new HashMap<String, Object>(); values.put(field.getOAuthField(), Arrays.asList(new String[]{timestamp})); JsonValue jsonValue = makeDefaultJsonValue(values); Calendar result = adapter.toToken(jsonValue).getExpiryTimestamp(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("Europe/London")); c.setTimeInMillis(result.getTimeInMillis()); assertEquals(c.get(Calendar.MONTH), 5); assertEquals(c.get(Calendar.YEAR), 2013); assertEquals(c.get(Calendar.HOUR_OF_DAY), 10); assertEquals(c.get(Calendar.MINUTE), 48); }
@Test (expectedExceptions = IllegalArgumentException.class) public void shouldVerifyThatObjectIsAMap() { OAuthAdapter adapter = generateOAuthAdapter(); JsonValue mockValue = mock(JsonValue.class); given(mockValue.getObject()).willReturn("badger"); adapter.toToken(mockValue); }
|
OAuthAdapter implements TokenAdapter<JsonValue> { public JsonValue fromToken(Token token) { if (token == null){ return null; } String data = blobUtils.getBlobAsString(token); JsonValue r; try { r = new JsonValue(serialisation.deserialise(data, Map.class)); Set<String> keys = r.keys(); for (String key : keys){ List<String> x = r.get(key).asList(String.class); Set<String> set = new HashSet<String>(x); r.remove(key); r.add(key, set); } } catch (RuntimeException e) { throw new IllegalArgumentException( "The CTS usage of the JsonValue depends on the value being of " + "type Map."); } return r; } @Inject OAuthAdapter(TokenIdFactory tokenIdFactory, JSONSerialisation serialisation,
OAuthValues oAuthValues, TokenBlobUtils blobUtils); Token toToken(JsonValue request); JsonValue fromToken(Token token); static final String VALUE; }
|
@Test public void shouldDeserialiseSerialisedToken() { String[] id = {"badger"}; List<String> list = new ArrayList<String>(Arrays.asList(id)); OAuthTokenField field = OAuthTokenField.ID; JSONSerialisation serialisation = new JSONSerialisation(); OAuthAdapter adapter = generateOAuthAdapter(); Map<String, Object> values = new HashMap<String, Object>(); values.put(field.getOAuthField(), list); String serialisedObject = serialisation.serialise(values); Token token = new Token(id[0], TokenType.OAUTH); token.setBlob(serialisedObject.getBytes()); JsonValue result = adapter.fromToken(token); assertNotNull(result); assert(result.asMap().get(field.getOAuthField()).toString().contains(id[0])); }
@Test (expectedExceptions = IllegalArgumentException.class) public void shouldNotDeserialiseATokenWhichDoesntContainAMap() { JSONSerialisation serialisation = new JSONSerialisation(); OAuthAdapter adapter = generateOAuthAdapter(); Token token = new Token("", TokenType.OAUTH); token.setBlob(serialisation.serialise("badger").getBytes()); adapter.fromToken(token); }
|
CoreTokenFieldTypes { public static void validateType(CoreTokenField field, Object value) throws CoreTokenException { if (value == null) { throw new LDAPOperationFailedException(MessageFormat.format( "\n" + CoreTokenConstants.DEBUG_HEADER + "Value field cannot be null!" + "Key: {0}:{1}", CoreTokenField.class.getSimpleName(), field.name())); } try { if (isString(field)) { assertClass(value, String.class); } else if (isInteger(field)) { assertClass(value, Integer.class); } else if (isCalendar(field)) { assertClass(value, Calendar.class); } else if (isByteArray(field)) { assertClass(value, byte[].class); } else { throw new IllegalStateException("Unknown field: " + field.name()); } } catch (LDAPOperationFailedException e) { throw new LDAPOperationFailedException(MessageFormat.format( "\n" + CoreTokenConstants.DEBUG_HEADER + "Value was not the correct type:\n" + " Key: {0}:{1}\n" + "Required Class: {2}" + " Actual Class: {3}", CoreTokenField.class.getSimpleName(), field.name(), e.getMessage(), value.getClass().getName()), e); } } static void validateTypes(Map<CoreTokenField, Object> types); static void validateType(CoreTokenField field, Object value); static boolean isCalendar(CoreTokenField field); static boolean isInteger(CoreTokenField field); static boolean isString(CoreTokenField field); static boolean isByteArray(CoreTokenField field); }
|
@Test public void shouldValidateIntegerField() throws CoreTokenException { CoreTokenField key = CoreTokenField.INTEGER_ONE; Integer value = 1234; CoreTokenFieldTypes.validateType(key, value); }
@Test public void shouldValidateStringField() throws CoreTokenException { CoreTokenField key = CoreTokenField.STRING_ONE; String value = "badger"; CoreTokenFieldTypes.validateType(key, value); }
@Test public void shouldValidateDateField() throws CoreTokenException { CoreTokenField key = CoreTokenField.DATE_ONE; Calendar value = Calendar.getInstance(); CoreTokenFieldTypes.validateType(key, value); }
@Test public void shouldValidateByteField() throws CoreTokenException { CoreTokenField key = CoreTokenField.BLOB; byte[] value = new byte[]{1, 2, 3, 4}; CoreTokenFieldTypes.validateType(key, value); }
@Test (expectedExceptions = CoreTokenException.class) public void shouldValidateInvalidType() throws CoreTokenException { CoreTokenField key = CoreTokenField.BLOB; Integer value = 1234; CoreTokenFieldTypes.validateType(key, value); }
|
TokenIdFactory { public String toSessionTokenId(InternalSession session) { return toSessionTokenId(session.getID()); } @Inject TokenIdFactory(KeyConversion encoding); String toSAMLPrimaryTokenId(String requestId); String fromSAMLPrimaryTokenId(String primaryId); String toSAMLSecondaryTokenId(String secondaryKey); String fromSAMLSecondaryTokenId(String secondaryId); String toSessionTokenId(InternalSession session); String toSessionTokenId(SessionID sessionID); String getOAuthTokenId(String id); static final String ID; }
|
@Test public void shouldUseKeyConversionForSessionTokens() { SessionID session = new SessionID("badger"); factory.toSessionTokenId(session); verify(conversion).encryptKey(session); }
|
TokenIdFactory { public String getOAuthTokenId(String id) { if (id == null){ id = UUID.randomUUID().toString(); } return id; } @Inject TokenIdFactory(KeyConversion encoding); String toSAMLPrimaryTokenId(String requestId); String fromSAMLPrimaryTokenId(String primaryId); String toSAMLSecondaryTokenId(String secondaryKey); String fromSAMLSecondaryTokenId(String secondaryId); String toSessionTokenId(InternalSession session); String toSessionTokenId(SessionID sessionID); String getOAuthTokenId(String id); static final String ID; }
|
@Test public void shouldGetOAuthTokenIdWhenSet() { String key = "badger"; String result = factory.getOAuthTokenId(key); assertEquals(result, key); }
@Test public void shouldGenerateRandomIdWhenOAuthTokenIdNotSet() { String result = factory.getOAuthTokenId(null); assertNotNull(result); }
|
JSONSerialisation { public <T> String serialise(T object) { try { String value = mapper.writeValueAsString(object); return value; } catch (IOException e) { throw new IllegalStateException( MessageFormat.format( "Failed to serialise {0}:{1}", object.getClass().getSimpleName(), object), e); } } JSONSerialisation(); String serialise(T object); T deserialise(String text, Class<T> clazz); static String jsonAttributeName(String name); }
|
@Test public void basicSessionSerializationWorks() throws Exception { InternalSession is = new InternalSession(); String serialised = SERIALISATION.serialise(is); assertThat(serialised).isNotNull().isEqualTo(getJSON("/json/basic-session.json")); assertThat(is).isNotNull(); }
|
JSONSerialisation { public <T> T deserialise(String text, Class<T> clazz) { try { T value = mapper.readValue(text, clazz); return value; } catch (IOException e) { throw new IllegalStateException( MessageFormat.format( "Failed to deserailise {0}", clazz.getSimpleName()), e); } } JSONSerialisation(); String serialise(T object); T deserialise(String text, Class<T> clazz); static String jsonAttributeName(String name); }
|
@Test public void tokenRestrictionDeserialisationWithTypeWorks() throws Exception { InternalSession is = SERIALISATION.deserialise(getJSON("/json/basic-session-with-restriction.json"), InternalSession.class); assertThat(is).isNotNull(); TokenRestriction restriction = is.getRestrictionForToken(new SessionID("AQIC5wM2LY4SfcyTLz6VjQ7nkFeDcEh8K5dXkIE" + "NpXlpg28.*AAJTSQACMDIAAlMxAAIwMQACU0sAEzc5ODIzMDM5MzQyNzU2MTg1NDQ.*")); assertThat(restriction).isNotNull().isInstanceOf(DNOrIPAddressListTokenRestriction.class); assertThat(restriction.toString().equals("Fzy2GsI/O1TsXhvlVuqjqIuTG2k=")); }
@Test(dataProvider = "complex") public void internalSessionDeserialisationWorks(String path) throws Exception { InternalSession is = SERIALISATION.deserialise(getJSON(path), InternalSession.class); assertThat(is).isNotNull(); assertThat(is.getID()).isNotNull(); assertThat(Collections.list(is.getPropertyNames())).hasSize(23); }
@Test(dataProvider = "complex") public void internalSessionDeserialisationDoesNotModifyMapTypes(String path) throws Exception { InternalSession is = SERIALISATION.deserialise(getJSON(path), InternalSession.class); assertThat(is).isNotNull(); checkMapType(is, "sessionEventURLs"); checkMapType(is, "restrictedTokensBySid"); checkMapType(is, "restrictedTokensByRestriction"); }
|
JSONSerialisation { public static String jsonAttributeName(String name) { return "\"" + name + "\":"; } JSONSerialisation(); String serialise(T object); T deserialise(String text, Class<T> clazz); static String jsonAttributeName(String name); }
|
@Test public void shouldChangeAttributeName() { String name = "badger"; assertNotEquals(name, JSONSerialisation.jsonAttributeName(name)); }
|
TokenAttributeConversion { public DN generateTokenDN(Token token) { return generateTokenDN(token.getTokenId()); } @Inject TokenAttributeConversion(LDAPConfig constants, LDAPDataConversion conversion); Entry getEntry(Token token); Map<CoreTokenField, Object> mapFromEntry(Entry entry); Token tokenFromEntry(Entry entry); static Entry addObjectClass(Entry entry); static Entry stripObjectClass(Entry entry); DN generateTokenDN(Token token); DN generateTokenDN(String tokenId); }
|
@Test public void shouldProduceDNWithTokenId() { String tokenId = "badger"; LDAPConfig constants = mock(LDAPConfig.class); given(constants.getTokenStoreRootSuffix()).willReturn(DN.rootDN()); LDAPDataConversion dataConversion = new LDAPDataConversion(); TokenAttributeConversion conversion = new TokenAttributeConversion(constants, dataConversion); DN dn = conversion.generateTokenDN(tokenId); verify(constants).getTokenStoreRootSuffix(); assertTrue(dn.toString().contains(tokenId)); }
@Test public void shouldAllowPlusSignInDN() { TokenAttributeConversion conversion = generateTokenAttributeConversion(); conversion.generateTokenDN("Badger+"); }
|
TokenAttributeConversion { public static Entry stripObjectClass(Entry entry) { Attribute attribute = entry.getAttribute(CoreTokenConstants.OBJECT_CLASS); if (attribute != null) { AttributeDescription description = attribute.getAttributeDescription(); entry.removeAttribute(description); } return entry; } @Inject TokenAttributeConversion(LDAPConfig constants, LDAPDataConversion conversion); Entry getEntry(Token token); Map<CoreTokenField, Object> mapFromEntry(Entry entry); Token tokenFromEntry(Entry entry); static Entry addObjectClass(Entry entry); static Entry stripObjectClass(Entry entry); DN generateTokenDN(Token token); DN generateTokenDN(String tokenId); }
|
@Test public void shouldNotStripObjectClassIfNotPresent() { Entry entry = mock(Entry.class); given(entry.getAttribute(anyString())).willReturn(null); TokenAttributeConversion.stripObjectClass(entry); verify(entry, times(0)).removeAttribute(anyString(), any()); }
@Test public void shouldStripObjectClass() { Entry entry = mock(Entry.class); Attribute attribute = mock(Attribute.class); given(entry.getAttribute(anyString())).willReturn(attribute); AttributeDescription description = AttributeDescription.valueOf("badger"); given(attribute.getAttributeDescription()).willReturn(description); TokenAttributeConversion.stripObjectClass(entry); verify(entry).removeAttribute(description); }
|
TokenAttributeConversion { public static Entry addObjectClass(Entry entry) { Attribute attribute = entry.getAttribute(CoreTokenConstants.OBJECT_CLASS); if (attribute == null) { entry.addAttribute(CoreTokenConstants.OBJECT_CLASS, CoreTokenConstants.FR_CORE_TOKEN); } return entry; } @Inject TokenAttributeConversion(LDAPConfig constants, LDAPDataConversion conversion); Entry getEntry(Token token); Map<CoreTokenField, Object> mapFromEntry(Entry entry); Token tokenFromEntry(Entry entry); static Entry addObjectClass(Entry entry); static Entry stripObjectClass(Entry entry); DN generateTokenDN(Token token); DN generateTokenDN(String tokenId); }
|
@Test public void shouldNotAddObjectClassIfPresent() { Entry entry = mock(Entry.class); Attribute attribute = mock(Attribute.class); given(entry.getAttribute(anyString())).willReturn(attribute); TokenAttributeConversion.addObjectClass(entry); verify(entry, times(0)).addAttribute(anyString(), any()); }
@Test public void shouldAddObjectClass() { Entry entry = mock(Entry.class); given(entry.getAttribute(anyString())).willReturn(null); TokenAttributeConversion.addObjectClass(entry); verify(entry).addAttribute(anyString(), any()); }
|
TokenAttributeConversion { public Entry getEntry(Token token) { Entry entry = new LinkedHashMapEntry(generateTokenDN(token)); addObjectClass(entry); for (CoreTokenField field : token.getAttributeNames()) { String key = field.toString(); if (CoreTokenField.TOKEN_TYPE.equals(field)) { TokenType type = token.getValue(field); entry.addAttribute(key, type.name()); continue; } if (CoreTokenFieldTypes.isCalendar(field)) { Calendar calendar = token.getValue(field); String dateString = conversion.toLDAPDate(calendar); entry.addAttribute(key, dateString); } else if (CoreTokenFieldTypes.isByteArray(field)) { byte[] array = token.getValue(field); entry.addAttribute(key, ByteString.valueOf(array)); } else if (CoreTokenFieldTypes.isInteger(field)) { Integer value = token.getValue(field); entry.addAttribute(key, ByteString.valueOf(value)); } else if (CoreTokenFieldTypes.isString(field)) { String value = token.getValue(field); if (value.isEmpty()) { value = EMPTY; } entry.addAttribute(key, ByteString.valueOf(value)); } else { throw new IllegalStateException(); } } return entry; } @Inject TokenAttributeConversion(LDAPConfig constants, LDAPDataConversion conversion); Entry getEntry(Token token); Map<CoreTokenField, Object> mapFromEntry(Entry entry); Token tokenFromEntry(Entry entry); static Entry addObjectClass(Entry entry); static Entry stripObjectClass(Entry entry); DN generateTokenDN(Token token); DN generateTokenDN(String tokenId); }
|
@Test public void shouldHandleEmptyStrings() { Token token = new Token("id", TokenType.OAUTH); token.setAttribute(CoreTokenField.STRING_ONE, ""); TokenAttributeConversion conversion = generateTokenAttributeConversion(); Entry result = conversion.getEntry(token); Attribute attribute = result.getAttribute(CoreTokenField.STRING_ONE.toString()); String string = attribute.firstValue().toString(); assertFalse(string.isEmpty()); }
|
TokenAttributeConversion { public Token tokenFromEntry(Entry entry) { Map<CoreTokenField, Object> map = mapFromEntry(entry); String tokenId = (String) map.get(CoreTokenField.TOKEN_ID); TokenType type = (TokenType) map.get(CoreTokenField.TOKEN_TYPE); Token token = new Token(tokenId, type); for (Map.Entry<CoreTokenField, Object> e : map.entrySet()) { CoreTokenField key = e.getKey(); Object value = e.getValue(); if (Token.isFieldReadOnly(key)) { continue; } token.setAttribute(key, value); } return token; } @Inject TokenAttributeConversion(LDAPConfig constants, LDAPDataConversion conversion); Entry getEntry(Token token); Map<CoreTokenField, Object> mapFromEntry(Entry entry); Token tokenFromEntry(Entry entry); static Entry addObjectClass(Entry entry); static Entry stripObjectClass(Entry entry); DN generateTokenDN(Token token); DN generateTokenDN(String tokenId); }
|
@Test public void shouldUnderstandEmptyStrings() { Entry entry = new LinkedHashMapEntry(); entry.addAttribute(CoreTokenField.TOKEN_ID.toString(), "id"); entry.addAttribute(CoreTokenField.TOKEN_TYPE.toString(), TokenType.OAUTH.toString()); entry.addAttribute(CoreTokenField.STRING_ONE.toString(), TokenAttributeConversion.EMPTY); TokenAttributeConversion conversion = generateTokenAttributeConversion(); Token result = conversion.tokenFromEntry(entry); String string = result.getValue(CoreTokenField.STRING_ONE); assertTrue(string.isEmpty()); }
|
TokenBlobUtils { public void setBlobFromString(Token token, String blob) { try { token.setBlob(blob.getBytes(ENCODING)); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to encode blob to " + ENCODING, e); } } String getBlobAsString(Token token); void setBlobFromString(Token token, String blob); static final String ENCODING; }
|
@Test public void shouldUseTokenWhenStoringStringAsBlob() throws CoreTokenException { TokenBlobUtils utils = new TokenBlobUtils(); Token mockToken = mock(Token.class); utils.setBlobFromString(mockToken, "badger"); verify(mockToken).setBlob(any(byte[].class)); }
|
TokenBlobUtils { public String getBlobAsString(Token token) { try { return new String(token.getBlob(), ENCODING); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Failed to decode blob to " + ENCODING, e); } } String getBlobAsString(Token token); void setBlobFromString(Token token, String blob); static final String ENCODING; }
|
@Test public void shouldUseTokenForBlobAsString() throws CoreTokenException, UnsupportedEncodingException { TokenBlobUtils utils = new TokenBlobUtils(); Token mockToken = mock(Token.class); given(mockToken.getBlob()).willReturn("badger".getBytes(TokenBlobUtils.ENCODING)); utils.getBlobAsString(mockToken); verify(mockToken).getBlob(); }
|
TokenBlobStrategy { public void perfom(Token token) throws TokenStrategyFailedException { for (BlobStrategy strategy : strategies) { strategy.perform(token); } } @Inject TokenBlobStrategy(TokenStrategyFactory factory, CoreTokenConfig config); void perfom(Token token); void reverse(Token token); }
|
@Test public void shouldPerformAllStrategy() throws TokenStrategyFailedException { BlobStrategy first = mock(BlobStrategy.class); BlobStrategy second = mock(BlobStrategy.class); BlobStrategy third = mock(BlobStrategy.class); given(factory.getStrategies(any(CoreTokenConfig.class))) .willReturn(Arrays.asList(first, second, third)); Token mockToken = mock(Token.class); TokenBlobStrategy strategy = new TokenBlobStrategy(factory, config); strategy.perfom(mockToken); verify(first).perform(mockToken); verify(second).perform(mockToken); verify(third).perform(mockToken); }
@Test public void shouldDoNothingWithNoStrategy() throws TokenStrategyFailedException { Token mockToken = mock(Token.class); TokenBlobStrategy strategy = new TokenBlobStrategy(factory, config); strategy.perfom(mockToken); verify(mockToken, times(0)).getBlob(); }
|
TokenBlobStrategy { public void reverse(Token token) throws TokenStrategyFailedException { for (BlobStrategy strategy : reverseStrategies) { strategy.reverse(token); } } @Inject TokenBlobStrategy(TokenStrategyFactory factory, CoreTokenConfig config); void perfom(Token token); void reverse(Token token); }
|
@Test public void shouldReverseAllStrategy() throws TokenStrategyFailedException { BlobStrategy first = mock(BlobStrategy.class); BlobStrategy second = mock(BlobStrategy.class); BlobStrategy third = mock(BlobStrategy.class); given(factory.getStrategies(any(CoreTokenConfig.class))) .willReturn(Arrays.asList(first, second, third)); Token mockToken = mock(Token.class); TokenBlobStrategy strategy = new TokenBlobStrategy(factory, config); strategy.reverse(mockToken); verify(first).reverse(mockToken); verify(second).reverse(mockToken); verify(third).reverse(mockToken); }
|
CompressionStrategy implements BlobStrategy { @Override public void perform(Token token) throws TokenStrategyFailedException { bout.reset(); try { GZIPOutputStream out = new GZIPOutputStream(bout); out.write(token.getBlob(), 0, token.getBlob().length); out.flush(); out.close(); } catch (IOException e) { throw new TokenStrategyFailedException(e); } token.setBlob(bout.toByteArray()); } @Override void perform(Token token); @Override void reverse(Token token); }
|
@Test public void shouldUpdateToken() throws TokenStrategyFailedException { Token token = mock(Token.class); byte[] testData = JSON_SAMPLE.getBytes(); given(token.getBlob()).willReturn(testData); compression.perform(token); verify(token).setBlob(any(byte[].class)); }
@Test public void shouldCompressContents() throws TokenStrategyFailedException { Token token = mock(Token.class); byte[] testData = JSON_SAMPLE.getBytes(); given(token.getBlob()).willReturn(testData); compression.perform(token); ArgumentCaptor<byte[]> captor = ArgumentCaptor.forClass(byte[].class); verify(token).setBlob(captor.capture()); byte[] result = captor.getValue(); assertTrue(result.length < testData.length); }
|
EncryptionStrategy implements BlobStrategy { public void perform(Token token) throws TokenStrategyFailedException { try { encyptionAction.setBlob(token.getBlob()); byte[] encryptedBlob = AccessController.doPrivileged(encyptionAction); token.setBlob(encryptedBlob); if (debug.messageEnabled()) { debug.message(CoreTokenConstants.DEBUG_HEADER + "Encrypted Token"); } } catch (PrivilegedActionException e) { throw new TokenStrategyFailedException("Failed to encrypt JSON Blob", e); } } @Inject EncryptionStrategy(EncryptAction encyptionAction, DecryptAction decyptAction,
@Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void perform(Token token); void reverse(Token token); }
|
@Test public void shouldCallEncryptOnPerform() throws Exception { byte[] bytes = {}; EncryptAction mockEncryptAction = mock(EncryptAction.class); EncryptionStrategy strategy = new EncryptionStrategy( mockEncryptAction, mock(DecryptAction.class), mock(Debug.class)); Token mockToken = mock(Token.class); given(mockToken.getBlob()).willReturn(bytes); strategy.perform(mockToken); verify(mockEncryptAction).setBlob(eq(bytes)); verify(mockEncryptAction).run(); }
@Test (expectedExceptions = TokenStrategyFailedException.class) public void shouldThrowExceptionIfEncryptionFails() throws Exception { EncryptAction mockEncryptAction = mock(EncryptAction.class); EncryptionStrategy strategy = new EncryptionStrategy( mockEncryptAction, mock(DecryptAction.class), mock(Debug.class)); given(mockEncryptAction.run()).willThrow(new Exception()); strategy.perform(mock(Token.class)); }
|
EncryptionStrategy implements BlobStrategy { public void reverse(Token token) throws TokenStrategyFailedException { try { decyptAction.setBlob(token.getBlob()); byte[] decryptedBlob = AccessController.doPrivileged(decyptAction); token.setBlob(decryptedBlob); if (debug.messageEnabled()) { debug.message(CoreTokenConstants.DEBUG_HEADER + "Decrypted Token"); } } catch (PrivilegedActionException e) { throw new TokenStrategyFailedException("Failed to decrypt JSON Blob", e); } } @Inject EncryptionStrategy(EncryptAction encyptionAction, DecryptAction decyptAction,
@Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void perform(Token token); void reverse(Token token); }
|
@Test public void shouldCallDecryptOnReverse() throws Exception { byte[] bytes = {}; DecryptAction mockDecryptAction = mock(DecryptAction.class); EncryptionStrategy strategy = new EncryptionStrategy( mock(EncryptAction.class), mockDecryptAction, mock(Debug.class)); Token mockToken = mock(Token.class); given(mockToken.getBlob()).willReturn(bytes); strategy.reverse(mockToken); verify(mockDecryptAction).setBlob(eq(bytes)); verify(mockDecryptAction).run(); }
@Test (expectedExceptions = TokenStrategyFailedException.class) public void shouldThrowExceptionIfDecryptionFails() throws Exception { DecryptAction mockDecryptAction = mock(DecryptAction.class); EncryptionStrategy strategy = new EncryptionStrategy( mock(EncryptAction.class), mockDecryptAction, mock(Debug.class)); given(mockDecryptAction.run()).willThrow(new Exception()); strategy.reverse(mock(Token.class)); }
|
AttributeCompressionStrategy implements BlobStrategy { public static Collection<Field> getAllValidFields(Class c) { List<Field> r = new ArrayList<Field>(); for (Field f : c.getDeclaredFields()) { int modifiers = f.getModifiers(); if (Modifier.isStatic(modifiers)) continue; if (Modifier.isVolatile(modifiers)) continue; if (Modifier.isTransient(modifiers)) continue; r.add(f); } return r; } @Inject AttributeCompressionStrategy(TokenBlobUtils blobUtils); void perform(Token token); void reverse(Token token); static String getInitials(String name); static Collection<Field> getAllValidFields(Class c); }
|
@Test public void shouldNotSelectAStaticFieldFromClass() { assertEquals(0, AttributeCompressionStrategy.getAllValidFields(StaticFieldTest.class).size()); }
@Test public void shouldSelectPrivateFields() { assertEquals(1, AttributeCompressionStrategy.getAllValidFields(PrivateFieldTest.class).size()); }
|
AttributeCompressionStrategy implements BlobStrategy { public static String getInitials(String name) { if (name == null) { throw new IllegalArgumentException("Name was null"); } StringBuilder r = new StringBuilder(); boolean start = true; for (int ii = 0; ii < name.length(); ii++) { char c = name.charAt(ii); if (start) { r.append(c); start = false; continue; } if (Character.isUpperCase(c)) { r.append(c); } } return r.toString(); } @Inject AttributeCompressionStrategy(TokenBlobUtils blobUtils); void perform(Token token); void reverse(Token token); static String getInitials(String name); static Collection<Field> getAllValidFields(Class c); }
|
@Test public void shouldConvertFieldNameToInitials() { assertEquals("bW", AttributeCompressionStrategy.getInitials("badgerWoodland")); assertEquals("bWO", AttributeCompressionStrategy.getInitials("badgerWOodland")); assertEquals("bWOL", AttributeCompressionStrategy.getInitials("badgerWOodLand")); }
|
AttributeCompressionStrategy implements BlobStrategy { public void perform(Token token) throws TokenStrategyFailedException { if (!isTokenValidForCompression(token)) { return; } performUpdate(token, replacement); } @Inject AttributeCompressionStrategy(TokenBlobUtils blobUtils); void perform(Token token); void reverse(Token token); static String getInitials(String name); static Collection<Field> getAllValidFields(Class c); }
|
@Test public void shouldNotUpdateNonSessionTokens() throws TokenStrategyFailedException { Token mockToken = mock(Token.class); given(mockToken.getType()).willReturn(TokenType.OAUTH); compression.perform(mockToken); verify(mockToken, times(0)).setBlob(any(byte[].class)); }
@Test public void shouldNotUpdateWithNullTokenBlob() throws TokenStrategyFailedException { Token mockToken = mock(Token.class); given(mockToken.getType()).willReturn(TokenType.SESSION); given(mockToken.getBlob()).willReturn(null); compression.perform(mockToken); verify(mockToken, times(0)).setBlob(any(byte[].class)); }
@Test public void shouldLookForCurlyBracketsInJSONBlob() throws TokenStrategyFailedException, UnsupportedEncodingException { Token mockToken = mock(Token.class); given(mockToken.getType()).willReturn(TokenType.SESSION); given(mockToken.getBlob()).willReturn("badger".getBytes(TokenBlobUtils.ENCODING)); compression.perform(mockToken); verify(mockToken, atLeastOnce()).getBlob(); verify(mockToken, times(0)).setBlob(any(byte[].class)); }
@Test public void shouldUpdateBlobContents() throws TokenStrategyFailedException, UnsupportedEncodingException { Token mockToken = mock(Token.class); given(mockToken.getType()).willReturn(TokenType.SESSION); given(mockToken.getBlob()).willReturn("{\"sessionID\":badger}".getBytes(TokenBlobUtils.ENCODING)); compression.perform(mockToken); verify(mockToken).setBlob(any(byte[].class)); }
@Test public void shouldCompressSessionBlob() throws TokenStrategyFailedException, UnsupportedEncodingException { Token token = new Token("Badger", TokenType.SESSION); String blob = "{\"sessionID\":badger}"; token.setBlob(blob.getBytes(TokenBlobUtils.ENCODING)); compression.perform(token); int previous = blob.getBytes().length; int updated = token.getBlob().length; assertTrue(updated < previous); }
|
ExternalTokenConfig { public void update() { hostname.set(SystemProperties.get(Constants.CTS_STORE_HOSTNAME)); port.set(SystemProperties.get(Constants.CTS_STORE_PORT)); username.set(SystemProperties.get(Constants.CTS_STORE_USERNAME)); password.set(AMPasswordUtil.decrypt(SystemProperties.get(Constants.CTS_STORE_PASSWORD))); maxConnections.set(SystemProperties.get(Constants.CTS_MAX_CONNECTIONS)); sslMode.set(SystemProperties.getAsBoolean(Constants.CTS_SSL_ENABLED, false)); String heartbeatStr = SystemProperties.get(Constants.LDAP_HEARTBEAT); if (StringUtils.isNotEmpty(heartbeatStr)) { try { heartbeat.set(Integer.parseInt(heartbeatStr)); } catch (NumberFormatException e) { heartbeat.set(new Integer(-1)); } } else { heartbeat.set(new Integer(-1)); } String mode = SystemProperties.get(Constants.CTS_STORE_LOCATION); if (StringUtils.isNotEmpty(mode)) { storeMode.set(StoreMode.valueOf(mode.toUpperCase())); } else { storeMode.set(StoreMode.DEFAULT); } } @Inject ExternalTokenConfig(); StoreMode getStoreMode(); String getHostname(); String getPort(); String getUsername(); String getPassword(); String getMaxConnections(); int getHeartbeat(); boolean isSslMode(); boolean hasChanged(); void update(); }
|
@Test public void shouldUseSystemPropertiesWrapperForNotifyChanges() { PowerMockito.mockStatic(SystemProperties.class); ExternalTokenConfig config = new ExternalTokenConfig(); config.update(); PowerMockito.verifyStatic(times(7)); SystemProperties.get(anyString()); PowerMockito.verifyStatic(); SystemProperties.getAsBoolean(anyString(), anyBoolean()); }
|
CoreTokenAdapter { public void create(Token token) throws CoreTokenException { Connection connection = null; try { connection = connectionFactory.getConnection(); ldapAdapter.create(connection, token); if (debug.messageEnabled()) { debug.message(MessageFormat.format( CoreTokenConstants.DEBUG_HEADER + "Create: Created {0} Token {1}\n" + "{2}", token.getType(), token.getTokenId(), token)); } } catch (ErrorResultException e) { throw new CreateFailedException(token, e); } finally { IOUtils.closeIfNotNull(connection); } } @Inject CoreTokenAdapter(ConnectionFactory connectionFactory, QueryFactory queryFactory,
LDAPAdapter ldapAdapter, ConfigurationObserver observer,
CoreTokenConfigListener listener, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void create(Token token); Token read(String tokenId); QueryBuilder query(); QueryFilter buildFilter(); void updateOrCreate(Token token); void delete(String tokenId); }
|
@Test public void shouldCreateToken() throws CoreTokenException, ErrorResultException { Token token = new Token("badger", TokenType.SESSION); adapter.create(token); verify(mockLDAPAdapter).create(any(Connection.class), eq(token)); }
|
CoreTokenAdapter { public Token read(String tokenId) throws CoreTokenException { Connection connection = null; try { connection = connectionFactory.getConnection(); Token token = ldapAdapter.read(connection, tokenId); if (token == null) { if (debug.messageEnabled()) { debug.message(MessageFormat.format( CoreTokenConstants.DEBUG_HEADER + "Read: {0} not found.", tokenId)); } return null; } if (debug.messageEnabled()) { debug.message(MessageFormat.format( CoreTokenConstants.DEBUG_HEADER + "Read: {0} successfully.", tokenId)); } return token; } catch (ErrorResultException e) { Result result = e.getResult(); throw new LDAPOperationFailedException(result); } finally { IOUtils.closeIfNotNull(connection); } } @Inject CoreTokenAdapter(ConnectionFactory connectionFactory, QueryFactory queryFactory,
LDAPAdapter ldapAdapter, ConfigurationObserver observer,
CoreTokenConfigListener listener, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void create(Token token); Token read(String tokenId); QueryBuilder query(); QueryFilter buildFilter(); void updateOrCreate(Token token); void delete(String tokenId); }
|
@Test public void shouldReadToken() throws CoreTokenException, ErrorResultException { String tokenId = "badger"; Token token = new Token(tokenId, TokenType.SESSION); given(mockLDAPAdapter.read(any(Connection.class), eq(tokenId))).willReturn(token); Token result = adapter.read(tokenId); assertThat(result.getTokenId()).isEqualTo(tokenId); }
|
CoreTokenAdapter { public QueryBuilder query() { return queryFactory.createInstance(); } @Inject CoreTokenAdapter(ConnectionFactory connectionFactory, QueryFactory queryFactory,
LDAPAdapter ldapAdapter, ConfigurationObserver observer,
CoreTokenConfigListener listener, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void create(Token token); Token read(String tokenId); QueryBuilder query(); QueryFilter buildFilter(); void updateOrCreate(Token token); void delete(String tokenId); }
|
@Test public void shouldGenerateAnInstanceOfQueryBuilder() throws ErrorResultException { adapter.query(); verify(mockQueryFactory).createInstance(); }
|
CoreTokenAdapter { public void delete(String tokenId) throws DeleteFailedException { Connection connection = null; try { connection = connectionFactory.getConnection(); ldapAdapter.delete(connection, tokenId); if (debug.messageEnabled()) { debug.message(MessageFormat.format( CoreTokenConstants.DEBUG_HEADER + "Delete: Deleted DN {0}", tokenId)); } } catch (ErrorResultException e) { throw new DeleteFailedException(tokenId, e); } catch (LDAPOperationFailedException e) { throw new DeleteFailedException(tokenId, e); } finally { IOUtils.closeIfNotNull(connection); } } @Inject CoreTokenAdapter(ConnectionFactory connectionFactory, QueryFactory queryFactory,
LDAPAdapter ldapAdapter, ConfigurationObserver observer,
CoreTokenConfigListener listener, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void create(Token token); Token read(String tokenId); QueryBuilder query(); QueryFilter buildFilter(); void updateOrCreate(Token token); void delete(String tokenId); }
|
@Test public void shouldPerformDelete() throws LDAPOperationFailedException, ErrorResultException, DeleteFailedException { String tokenId = "badger"; adapter.delete(tokenId); verify(mockLDAPAdapter).delete(any(Connection.class), eq(tokenId)); }
|
QueryBuilder { public Collection<Entry> executeRawResults() throws CoreTokenException { Filter ldapFilter = getLDAPFilter(); SearchRequest searchRequest = Requests.newSearchRequest( constants.getTokenStoreRootSuffix(), SearchScope.WHOLE_SUBTREE, ldapFilter, requestedAttributes); searchRequest.setSizeLimit(sizeLimit); if (isPagingResults()) { searchRequest = searchRequest.addControl(SimplePagedResultsControl.newControl(true, pageSize, pagingCookie)); } Collection<Entry> entries = createResultsList(); Result result = handler.performSearch(searchRequest, entries); if (isPagingResults()) { try { SimplePagedResultsControl control = result.getControl( SimplePagedResultsControl.DECODER, new DecodeOptions()); if (control == null) { if (debug.warningEnabled()) { debug.warning("There was no paged result control in the search response, it is recommended to " + "set the CTS user's size-limit at least to " + (pageSize + 1)); } pagingCookie = getEmptyPagingCookie(); } else { pagingCookie = control.getCookie(); } } catch (DecodeException e) { throw new CoreTokenException("Failed to decode Paging Cookie", e); } } if (debug.messageEnabled()) { debug.message(MessageFormat.format( CoreTokenConstants.DEBUG_HEADER + "Query: matched {0} results\n" + "Search Request: {1}\n" + "Filter: {2}\n" + "Result: {3}", entries.size(), searchRequest, ldapFilter.toString(), result)); } return entries; } @Inject QueryBuilder(TokenAttributeConversion attributeConversion,
LDAPConfig constants, LDAPSearchHandler handler,
@Named(CoreTokenConstants.CTS_DEBUG) Debug debug); QueryBuilder limitResultsTo(int maxSize); QueryBuilder pageResultsBy(int pageSize, ByteString cookie); ByteString getPagingCookie(); boolean isPagingResults(); QueryBuilder returnTheseAttributes(CoreTokenField... fields); QueryBuilder withFilter(Filter filter); Collection<Entry> executeRawResults(); Collection<Token> execute(); @Override String toString(); static ByteString getEmptyPagingCookie(); }
|
@Test public void shouldUseHandlerToPerformSearch() throws CoreTokenException, IOException { Result mockResult = mock(Result.class); given(searchHandler.performSearch(any(SearchRequest.class), any(Collection.class))).willReturn(mockResult); builder.executeRawResults(); verify(searchHandler).performSearch(any(SearchRequest.class), any(Collection.class)); }
|
LDAPSearchHandler { public Result performSearch(SearchRequest request, Collection<Entry> entries) throws QueryFailedException { Filter filter = request.getFilter(); Connection connection = null; try { connection = connectionFactory.getConnection(); result = connection.search(request, entries); return result; } catch (ErrorResultException e) { if (!entries.isEmpty()) { if (debug.warningEnabled()) { debug.warning("Partial search result has been received due to the following error:", e); } return e.getResult(); } throw new QueryFailedException(connection, constants.getTokenStoreRootSuffix(), filter, e); } finally { IOUtils.closeIfNotNull(connection); } } @Inject LDAPSearchHandler(ConnectionFactory connectionFactory, LDAPConfig constants,
@Named(CoreTokenConstants.CTS_DEBUG) Debug debug); Result performSearch(SearchRequest request, Collection<Entry> entries); }
|
@Test public void shouldGetConnectionFromFactory() throws QueryFailedException, ErrorResultException, ErrorResultIOException { given(mockFactory.getConnection()).willReturn(mockConnection); handler.performSearch(mockRequest, mock(Collection.class)); verify(mockFactory).getConnection(); }
@Test(expectedExceptions = QueryFailedException.class) public void shouldHandleException() throws Exception { given(mockFactory.getConnection()).willThrow(ErrorResultException.class); handler.performSearch(mockRequest, new ArrayList<Entry>(0)); }
@Test public void shouldNotFailWithExceptionIfEntriesWerePresent() throws Exception { given(mockFactory.getConnection()).willReturn(mockConnection); List<Entry> entries = new ArrayList<Entry>(); entries.add(null); given(mockConnection.search(mockRequest, entries)).willThrow(ErrorResultException.class); handler.performSearch(mockRequest, new ArrayList<Entry>(0)); }
@Test public void shouldReturnResult() throws ErrorResultException, QueryFailedException { Result mockResult = mock(Result.class); given(mockConnection.search(eq(mockRequest), any(Collection.class))).willReturn(mockResult); Result result = handler.performSearch(mockRequest, mock(Collection.class)); assertThat(result).isEqualTo(mockResult); }
|
QueryPageIterator implements Iterator<Collection<Entry>> { public boolean hasNext() { if (firstCall) { return true; } return cookie.length() != QueryBuilder.getEmptyPagingCookie().length(); } QueryPageIterator(QueryBuilder builder, int pageSize); boolean hasNext(); Collection<Entry> next(); void remove(); }
|
@Test public void shouldHaveNextOnFirstCall() { assertThat(iterator.hasNext()).isTrue(); }
|
QueryPageIterator implements Iterator<Collection<Entry>> { public Collection<Entry> next() { if (firstCall) { firstCall = false; } try { return queryPage(); } catch (CoreTokenException e) { throw new IllegalStateException(e); } } QueryPageIterator(QueryBuilder builder, int pageSize); boolean hasNext(); Collection<Entry> next(); void remove(); }
|
@Test public void shouldPerfomQueryWithNextCall() throws CoreTokenException { iterator.next(); verify(mockBuilder, atLeastOnce()).executeRawResults(); }
|
LDAPAdapter { public void create(Connection connection, Token token) throws ErrorResultException, LDAPOperationFailedException { Entry entry = conversion.getEntry(token); processResult(connection.add(entry)); } @Inject LDAPAdapter(TokenAttributeConversion conversion); void create(Connection connection, Token token); Token read(Connection connection, String tokenId); boolean update(Connection connection, Token previous, Token updated); void delete(Connection connection, String tokenId); void deleteAsync(Connection connection, String tokenId, ResultHandler<Result> handler); }
|
@Test public void shouldUseConnectionForCreate() throws LDAPOperationFailedException, ErrorResultException { Token token = new Token("badger", TokenType.SESSION); Connection mockConnection = mock(Connection.class); Result successResult = mockSuccessfulResult(); given(mockConnection.add(any(Entry.class))).willReturn(successResult); TokenAttributeConversion mockConversion = mock(TokenAttributeConversion.class); given(mockConversion.getEntry(any(Token.class))).willReturn(mock(Entry.class)); LDAPAdapter adapter = new LDAPAdapter(mockConversion); adapter.create(mockConnection, token); verify(mockConnection).add(any(Entry.class)); }
|
LDAPAdapter { public Token read(Connection connection, String tokenId) throws ErrorResultException { DN dn = conversion.generateTokenDN(tokenId); try { SearchResultEntry resultEntry = connection.readEntry(dn); return conversion.tokenFromEntry(resultEntry); } catch (ErrorResultException e) { Result result = e.getResult(); if (result != null && ResultCode.NO_SUCH_OBJECT.equals(result.getResultCode())) { return null; } throw e; } } @Inject LDAPAdapter(TokenAttributeConversion conversion); void create(Connection connection, Token token); Token read(Connection connection, String tokenId); boolean update(Connection connection, Token previous, Token updated); void delete(Connection connection, String tokenId); void deleteAsync(Connection connection, String tokenId, ResultHandler<Result> handler); }
|
@Test public void shouldUseConnectionForRead() throws ErrorResultException { String tokenId = "badger"; DN testDN = DN.rootDN(); Connection mockConnection = mock(Connection.class); TokenAttributeConversion mockConversion = mock(TokenAttributeConversion.class); given(mockConversion.generateTokenDN(anyString())).willReturn(testDN); LDAPAdapter adapter = new LDAPAdapter(mockConversion); adapter.read(mockConnection, tokenId); ArgumentCaptor<DN> captor = ArgumentCaptor.forClass(DN.class); verify(mockConnection).readEntry(captor.capture()); assertEquals(testDN, captor.getValue()); }
@Test public void shouldReturnNullWhenObjectNotFound() throws ErrorResultException { String tokenId = "badger"; DN testDN = DN.rootDN(); Connection mockConnection = mock(Connection.class); ErrorResultException exception = ErrorResultException.newErrorResult(ResultCode.NO_SUCH_OBJECT); given(mockConnection.readEntry(eq(testDN))).willThrow(exception); TokenAttributeConversion mockConversion = mock(TokenAttributeConversion.class); given(mockConversion.generateTokenDN(anyString())).willReturn(testDN); LDAPAdapter adapter = new LDAPAdapter(mockConversion); Token result = adapter.read(mockConnection, tokenId); assertThat(result).isNull(); }
|
LDAPAdapter { public void delete(Connection connection, String tokenId) throws LDAPOperationFailedException, ErrorResultException { String dn = String.valueOf(conversion.generateTokenDN(tokenId)); try { processResult(connection.delete(dn)); } catch (ErrorResultException e) { Result result = e.getResult(); if (e.getResult() != null && ResultCode.NO_SUCH_OBJECT.equals(result.getResultCode())) { return; } throw e; } } @Inject LDAPAdapter(TokenAttributeConversion conversion); void create(Connection connection, Token token); Token read(Connection connection, String tokenId); boolean update(Connection connection, Token previous, Token updated); void delete(Connection connection, String tokenId); void deleteAsync(Connection connection, String tokenId, ResultHandler<Result> handler); }
|
@Test public void shouldUseConnectionForDelete() throws ErrorResultException, LDAPOperationFailedException { String tokenId = "badger"; DN testDN = DN.rootDN(); Connection mockConnection = mock(Connection.class); Result successResult = mockSuccessfulResult(); given(mockConnection.delete(anyString())).willReturn(successResult); TokenAttributeConversion mockConversion = mock(TokenAttributeConversion.class); given(mockConversion.generateTokenDN(anyString())).willReturn(testDN); LDAPAdapter adapter = new LDAPAdapter(mockConversion); adapter.delete(mockConnection, tokenId); ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); verify(mockConnection).delete(captor.capture()); assertEquals(String.valueOf(testDN), captor.getValue()); }
@Test public void shouldDoNothingIfObjectNotFoundDuringDelete() throws LDAPOperationFailedException, ErrorResultException { String tokenId = "badger"; DN testDN = DN.rootDN(); Connection mockConnection = mock(Connection.class); ErrorResultException exception = ErrorResultException.newErrorResult(ResultCode.NO_SUCH_OBJECT); given(mockConnection.delete(anyString())).willThrow(exception); TokenAttributeConversion mockConversion = mock(TokenAttributeConversion.class); given(mockConversion.generateTokenDN(anyString())).willReturn(testDN); LDAPAdapter adapter = new LDAPAdapter(mockConversion); adapter.delete(mockConnection, tokenId); }
@Test public void shouldThrowAllOtherExceptionsDuringDelete() throws LDAPOperationFailedException, ErrorResultException { String tokenId = "badger"; DN testDN = DN.rootDN(); Connection mockConnection = mock(Connection.class); ErrorResultException exception = ErrorResultException.newErrorResult(ResultCode.OTHER); given(mockConnection.delete(anyString())).willThrow(exception); TokenAttributeConversion mockConversion = mock(TokenAttributeConversion.class); given(mockConversion.generateTokenDN(anyString())).willReturn(testDN); LDAPAdapter adapter = new LDAPAdapter(mockConversion); try { adapter.delete(mockConnection, tokenId); fail(); } catch (ErrorResultException e) {} }
|
LDAPAdapter { public boolean update(Connection connection, Token previous, Token updated) throws ErrorResultException, LDAPOperationFailedException { Entry currentEntry = conversion.getEntry(updated); TokenAttributeConversion.stripObjectClass(currentEntry); Entry previousEntry = conversion.getEntry(previous); TokenAttributeConversion.stripObjectClass(previousEntry); ModifyRequest request = Entries.diffEntries(previousEntry, currentEntry); if (request.getModifications().isEmpty()) { return false; } processResult(connection.modify(request)); return true; } @Inject LDAPAdapter(TokenAttributeConversion conversion); void create(Connection connection, Token token); Token read(Connection connection, String tokenId); boolean update(Connection connection, Token previous, Token updated); void delete(Connection connection, String tokenId); void deleteAsync(Connection connection, String tokenId, ResultHandler<Result> handler); }
|
@Test public void shouldNoNothingIfNoModificaitonsOnUpdate() throws LDAPOperationFailedException, ErrorResultException { String tokenId = "badger"; Token first = new Token(tokenId, TokenType.OAUTH); Token second = new Token(tokenId, TokenType.OAUTH); Connection mockConnection = mock(Connection.class); LDAPConfig constants = new LDAPConfig(""); LDAPDataConversion dataConversion = new LDAPDataConversion(); TokenAttributeConversion conversion = new TokenAttributeConversion(constants, dataConversion); LDAPAdapter adapter = new LDAPAdapter(conversion); adapter.update(mockConnection, first, second); verify(mockConnection, never()).modify(any(ModifyRequest.class)); }
@Test public void shouldPerformUpdate() throws LDAPOperationFailedException, ErrorResultException { Token first = new Token("weasel", TokenType.OAUTH); Token second = new Token("badger", TokenType.OAUTH); Connection mockConnection = mock(Connection.class); Result successResult = mockSuccessfulResult(); given(mockConnection.modify(any(ModifyRequest.class))).willReturn(successResult); LDAPConfig constants = new LDAPConfig(""); LDAPDataConversion dataConversion = new LDAPDataConversion(); TokenAttributeConversion conversion = new TokenAttributeConversion(constants, dataConversion); LDAPAdapter adapter = new LDAPAdapter(conversion); adapter.update(mockConnection, first, second); verify(mockConnection).modify(any(ModifyRequest.class)); }
|
LDAPConfig { public void update() { tokenStoreRootSuffix.set(SystemProperties.get(Constants.CTS_ROOT_SUFFIX)); } @Inject LDAPConfig(String rootSuffix); DN getTokenStoreRootSuffix(); boolean hasChanged(); void update(); }
|
@Test public void shouldUseSystemPropertiesForNotifyChanges() { PowerMockito.mockStatic(SystemProperties.class); LDAPConfig config = new LDAPConfig(""); config.update(); PowerMockito.verifyStatic(); SystemProperties.get(anyString()); }
|
CTSConnectionFactory implements ConnectionFactory, ShutdownListener { public void close() { IOUtils.closeIfNotNull(factory); } @Inject CTSConnectionFactory(DataLayerConnectionFactory dlcf, LDAPConfig ldapConfig,
ExternalTokenConfig external, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void updateConnection(); Connection getConnection(); FutureResult<Connection> getConnectionAsync(ResultHandler<? super Connection> resultHandler); void close(); void shutdown(); }
|
@Test public void shouldCloseFactoryOnClose() { factory.close(); verify(mockDLCF).close(); }
|
CTSConnectionFactory implements ConnectionFactory, ShutdownListener { public Connection getConnection() throws ErrorResultException { try { readLock.lock(); return factory.getConnection(); } finally { readLock.unlock(); } } @Inject CTSConnectionFactory(DataLayerConnectionFactory dlcf, LDAPConfig ldapConfig,
ExternalTokenConfig external, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void updateConnection(); Connection getConnection(); FutureResult<Connection> getConnectionAsync(ResultHandler<? super Connection> resultHandler); void close(); void shutdown(); }
|
@Test public void shouldUseDLCFByDefault() throws ErrorResultException { factory.getConnection(); verify(mockDLCF).getConnection(); }
|
CTSConnectionFactory implements ConnectionFactory, ShutdownListener { public FutureResult<Connection> getConnectionAsync(ResultHandler<? super Connection> resultHandler) { try { readLock.lock(); return factory.getConnectionAsync(resultHandler); } finally { readLock.unlock(); } } @Inject CTSConnectionFactory(DataLayerConnectionFactory dlcf, LDAPConfig ldapConfig,
ExternalTokenConfig external, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void updateConnection(); Connection getConnection(); FutureResult<Connection> getConnectionAsync(ResultHandler<? super Connection> resultHandler); void close(); void shutdown(); }
|
@Test public void shouldUseFactoryForAsynConnection() { factory.getConnectionAsync(mock(ResultHandler.class)); verify(mockDLCF).getConnectionAsync(any(ResultHandler.class)); }
|
CTSConnectionFactory implements ConnectionFactory, ShutdownListener { public void updateConnection() { try { writeLock.lock(); if (ldapConfig.hasChanged() || external.hasChanged()) { reconfigureConnection(); } } finally { writeLock.unlock(); } } @Inject CTSConnectionFactory(DataLayerConnectionFactory dlcf, LDAPConfig ldapConfig,
ExternalTokenConfig external, @Named(CoreTokenConstants.CTS_DEBUG) Debug debug); void updateConnection(); Connection getConnection(); FutureResult<Connection> getConnectionAsync(ResultHandler<? super Connection> resultHandler); void close(); void shutdown(); }
|
@Test public void shouldUseLDAPUtilsForExternalConfiguration() { PowerMockito.mockStatic(LDAPUtils.class); ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); given(LDAPUtils.newFailoverConnectionPool( any(Set.class), anyString(), any(char[].class), anyInt(), anyInt(), anyString(), any(LDAPOptions.class))).willReturn(mockConnectionFactory); given(mockExternal.getStoreMode()).willReturn(ExternalTokenConfig.StoreMode.EXTERNAL); given(mockExternal.getHostname()).willReturn("badger"); given(mockExternal.getMaxConnections()).willReturn("50"); given(mockExternal.getPassword()).willReturn("weasel"); given(mockExternal.getPort()).willReturn("1234"); given(mockExternal.getUsername()).willReturn("ferret"); given(mockExternal.hasChanged()).willReturn(true); factory.updateConnection(); PowerMockito.verifyStatic(); LDAPUtils.newFailoverConnectionPool( any(Set.class), anyString(), any(char[].class), anyInt(), anyInt(), anyString(), any(LDAPOptions.class)); }
|
IndexTreeServiceImpl implements IndexTreeService, IndexChangeObserver, ShutdownListener { @Override public Set<String> searchTree(String resource, String realm) throws EntitlementException { IndexRuleTree indexRuleTree = getIndexTree(realm); if (indexRuleTree == null) { return Collections.emptySet(); } Set<String> results = indexRuleTree.searchTree(resource); if (DEBUG.messageEnabled()) { DEBUG.message(String.format("Matched index rules (resource:%s, realm:%s): %s", resource, realm, results)); } return results; } @Inject IndexTreeServiceImpl(IndexChangeManager manager, PrivilegedAction<SSOToken> adminTokenAction,
ServiceManagementDAO smDAO, DNWrapper dnMapper,
ShutdownManagerWrapper shutdownManager); @Override Set<String> searchTree(String resource, String realm); @Override void update(IndexChangeEvent event); @Override void shutdown(); }
|
@Test public void treeSearchSingleRealm() throws Exception { List<SMSDataEntry> pathIndexes = new ArrayList<SMSDataEntry>(); pathIndexes.add(new SMSDataEntry("{dn:somedn,attributeValues:{pathindex:[\"http: pathIndexes.add(new SMSDataEntry("{dn:somedn,attributeValues:{pathindex:[\"http: pathIndexes.add(new SMSDataEntry("{dn:somedn,attributeValues:{pathindex:[\"http: pathIndexes.add(new SMSDataEntry("{dn:somedn,attributeValues:{pathindex:[\"*\"]}}")); when(dnMapper.orgNameToDN(REALM)).thenReturn(REALM_DN); when(privilegedAction.run()).thenReturn(ssoToken); when(serviceManagementDAO.checkIfEntryExists(SERVICE_DN, ssoToken)).thenReturn(true); when(serviceManagementDAO.search(ssoToken, SERVICE_DN, FILTER, 0, 0, false, false, excludes)) .thenReturn(pathIndexes.iterator()); Set<String> results = treeService.searchTree("http: verify(dnMapper).orgNameToDN(REALM); verify(privilegedAction).run(); verify(serviceManagementDAO).checkIfEntryExists(SERVICE_DN, ssoToken); verify(serviceManagementDAO).search(ssoToken, SERVICE_DN, FILTER, 0, 0, false, false, excludes); Set<String> expectedResults = new HashSet<String>(); expectedResults.add("http: expectedResults.add("http: expectedResults.add("*"); assertEquals(expectedResults, results); results = treeService.searchTree("http: verifyNoMoreInteractions(dnMapper, privilegedAction, serviceManagementDAO); expectedResults = new HashSet<String>(); expectedResults.add("http: expectedResults.add("*"); assertEquals(expectedResults, results); }
@Test public void treeSearchMultipleRealms() throws Exception { List<SMSDataEntry> pathIndexes = new ArrayList<SMSDataEntry>(); pathIndexes.add(new SMSDataEntry("{dn:somedn,attributeValues:{pathindex:[\"http: pathIndexes.add(new SMSDataEntry("{dn:somedn,attributeValues:{pathindex:[\"*\"]}}")); when(dnMapper.orgNameToDN(REALM)).thenReturn(REALM_DN); when(privilegedAction.run()).thenReturn(ssoToken); when(serviceManagementDAO.checkIfEntryExists(SERVICE_DN, ssoToken)).thenReturn(true); when(serviceManagementDAO.search(ssoToken, SERVICE_DN, FILTER, 0, 0, false, false, excludes)) .thenReturn(pathIndexes.iterator()); Set<String> results = treeService.searchTree("http: verify(dnMapper).orgNameToDN(REALM); verify(privilegedAction).run(); verify(serviceManagementDAO).checkIfEntryExists(SERVICE_DN, ssoToken); verify(serviceManagementDAO).search(ssoToken, SERVICE_DN, FILTER, 0, 0, false, false, excludes); Set<String> expectedResults = new HashSet<String>(); expectedResults.add("http: expectedResults.add("*"); assertEquals(expectedResults, results); results = treeService.searchTree("http: verifyNoMoreInteractions(dnMapper, privilegedAction, serviceManagementDAO); assertEquals(expectedResults, results); pathIndexes = new ArrayList<SMSDataEntry>(); pathIndexes.add(new SMSDataEntry("{dn:somedn,attributeValues:{pathindex:[\"http: when(dnMapper.orgNameToDN(REALM2)).thenReturn(REALM_DN2); when(privilegedAction.run()).thenReturn(ssoToken); when(serviceManagementDAO.checkIfEntryExists(SERVICE_DN2, ssoToken)).thenReturn(true); when(serviceManagementDAO.search(ssoToken, SERVICE_DN2, FILTER, 0, 0, false, false, excludes)) .thenReturn(pathIndexes.iterator()); results = treeService.searchTree("http: verify(dnMapper).orgNameToDN(REALM2); verify(privilegedAction, times(2)).run(); verify(serviceManagementDAO).checkIfEntryExists(SERVICE_DN2, ssoToken); verify(serviceManagementDAO).search(ssoToken, SERVICE_DN2, FILTER, 0, 0, false, false, excludes); expectedResults = new HashSet<String>(); expectedResults.add("http: assertEquals(expectedResults, results); results = treeService.searchTree("http: verifyNoMoreInteractions(dnMapper, privilegedAction, serviceManagementDAO); assertEquals(expectedResults, results); }
@Test public void noSearchResultsReturnsEmptyList() throws Exception { List<SMSDataEntry> emptyIndexes = Collections.emptyList(); when(dnMapper.orgNameToDN(REALM)).thenReturn(REALM_DN); when(privilegedAction.run()).thenReturn(ssoToken); when(serviceManagementDAO.checkIfEntryExists(SERVICE_DN, ssoToken)).thenReturn(true); when(serviceManagementDAO.search(ssoToken, SERVICE_DN, FILTER, 0, 0, false, false, excludes)) .thenReturn(emptyIndexes.iterator()); Set<String> results = treeService.searchTree("http: verify(dnMapper).orgNameToDN(REALM); verify(privilegedAction).run(); verify(serviceManagementDAO).checkIfEntryExists(SERVICE_DN, ssoToken); verify(serviceManagementDAO).search(ssoToken, SERVICE_DN, FILTER, 0, 0, false, false, excludes); assertNotNull(results); assertTrue(results.isEmpty()); }
@Test public void missingDNReturnsEmptyList() throws Exception { when(dnMapper.orgNameToDN(REALM)).thenReturn(REALM_DN); when(privilegedAction.run()).thenReturn(ssoToken); when(serviceManagementDAO.checkIfEntryExists(SERVICE_DN, ssoToken)).thenReturn(false); Set<String> results = treeService.searchTree("http: verify(dnMapper).orgNameToDN(REALM); verify(privilegedAction).run(); verify(serviceManagementDAO).checkIfEntryExists(SERVICE_DN, ssoToken); verifyNoMoreInteractions(serviceManagementDAO); assertNotNull(results); assertTrue(results.isEmpty()); }
|
ServerGroupConfiguration { public Set<LDAPURL> getLDAPURLs() { Collection<Server> servers = group.getServersList(); Set<LDAPURL> ret = new LinkedHashSet<LDAPURL>(servers.size()); for (Server server : servers) { ret.add(LDAPURL.valueOf(server.getServerName(), server.getPort(), Server.Type.CONN_SSL.equals(server.getConnectionType()))); } return ret; } ServerGroupConfiguration(ServerGroup group, ServerInstance instance); String getBindDN(); char[] getBindPassword(); int getMaxConnections(); int getLdapHeartbeat(); Set<LDAPURL> getLDAPURLs(); }
|
@Test public void shouldReturnCorrectLDAPURLforSimpleConnections() { String hostName = "localhost"; int port = 389; Server one = mock(Server.class); given(one.getServerName()).willReturn(hostName); given(one.getPort()).willReturn(port); given(one.getConnectionType()).willReturn(Server.Type.CONN_SIMPLE); ServerInstance mockInstance = mock(ServerInstance.class); ServerGroup mockGroup = mock(ServerGroup.class); given(mockGroup.getServersList()).willReturn(Arrays.asList(one)); ServerGroupConfiguration config = new ServerGroupConfiguration(mockGroup, mockInstance); Set<LDAPURL> result = config.getLDAPURLs(); assertThat(result).hasSize(1); LDAPURL url = result.iterator().next(); assertThat(url.getHost()).isEqualTo(hostName); assertThat(url.getPort()).isEqualTo(port); assertThat(url.isSSL()).isFalse(); }
@Test public void shouldReturnCorrectLDAPURLforSSLConnections() { String hostName = "localhost"; int port = 389; Server one = mock(Server.class); given(one.getServerName()).willReturn(hostName); given(one.getPort()).willReturn(port); given(one.getConnectionType()).willReturn(Server.Type.CONN_SSL); ServerInstance mockInstance = mock(ServerInstance.class); ServerGroup mockGroup = mock(ServerGroup.class); given(mockGroup.getServersList()).willReturn(Arrays.asList(one)); ServerGroupConfiguration config = new ServerGroupConfiguration(mockGroup, mockInstance); Set<LDAPURL> result = config.getLDAPURLs(); assertThat(result).hasSize(1); LDAPURL url = result.iterator().next(); assertThat(url.getHost()).isEqualTo(hostName); assertThat(url.getPort()).isEqualTo(port); assertThat(url.isSSL()).isTrue(); }
|
ServerGroupConfiguration { public String getBindDN() { return instance.getAuthID(); } ServerGroupConfiguration(ServerGroup group, ServerInstance instance); String getBindDN(); char[] getBindPassword(); int getMaxConnections(); int getLdapHeartbeat(); Set<LDAPURL> getLDAPURLs(); }
|
@Test public void shouldReturnBindDNFromInstance() { ServerInstance mockInstance = mock(ServerInstance.class); ServerGroup mockGroup = mock(ServerGroup.class); ServerGroupConfiguration config = new ServerGroupConfiguration(mockGroup, mockInstance); config.getBindDN(); verify(mockInstance).getAuthID(); }
|
ServerGroupConfiguration { public char[] getBindPassword() { return instance.getPasswd().toCharArray(); } ServerGroupConfiguration(ServerGroup group, ServerInstance instance); String getBindDN(); char[] getBindPassword(); int getMaxConnections(); int getLdapHeartbeat(); Set<LDAPURL> getLDAPURLs(); }
|
@Test public void shouldReturnPasswordFromInstance() { ServerInstance mockInstance = mock(ServerInstance.class); ServerGroup mockGroup = mock(ServerGroup.class); ServerGroupConfiguration config = new ServerGroupConfiguration(mockGroup, mockInstance); given(mockInstance.getPasswd()).willReturn(""); config.getBindPassword(); verify(mockInstance).getPasswd(); }
|
ServerGroupConfiguration { public int getMaxConnections() { return instance.getMaxConnections(); } ServerGroupConfiguration(ServerGroup group, ServerInstance instance); String getBindDN(); char[] getBindPassword(); int getMaxConnections(); int getLdapHeartbeat(); Set<LDAPURL> getLDAPURLs(); }
|
@Test public void shouldReturnMaxConnectionsFromInstance() { ServerInstance mockInstance = mock(ServerInstance.class); ServerGroup mockGroup = mock(ServerGroup.class); ServerGroupConfiguration config = new ServerGroupConfiguration(mockGroup, mockInstance); config.getMaxConnections(); verify(mockInstance).getMaxConnections(); }
|
LoginContext { public void login() throws LoginException { loginSucceeded = false; if (subject == null) { subject = new Subject(); } try { invoke(LOGIN_METHOD); invoke(COMMIT_METHOD); loginSucceeded = true; } catch (LoginException le) { try { invoke(ABORT_METHOD); } catch (LoginException le2) { throw le; } throw le; } } LoginContext(AppConfigurationEntry[] entries,
CallbackHandler callbackHandler); LoginContext(AppConfigurationEntry[] entries, Subject subject,
CallbackHandler callbackHandler); void login(); void logout(); Subject getSubject(); }
|
@Test public void sufficientSuccess() throws LoginException { whenLoginReturnTrue(requiredDelegate, requisiteDelegate, sufficientDelegate); whenCommitReturnTrue(requiredDelegate, requisiteDelegate, sufficientDelegate); context.login(); verifyInitialize(requiredDelegate, requisiteDelegate, sufficientDelegate); verifyLogin(requiredDelegate, requisiteDelegate, sufficientDelegate); verifyCommit(requiredDelegate, requisiteDelegate, sufficientDelegate); verifyNoMoreInteractions(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); }
@Test public void sufficientFailureIgnored() throws LoginException { whenLoginReturnTrue(requiredDelegate, requisiteDelegate, optionalDelegate); whenLoginThrowInvalidPasswordException(sufficientDelegate); whenCommitReturnTrue(requiredDelegate, requisiteDelegate, optionalDelegate); whenCommitReturnFalse(sufficientDelegate); context.login(); verifyInitialize(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyLogin(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyCommit(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyNoMoreInteractions(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); }
@Test(expectedExceptions = InvalidPasswordException.class) public void requiredFailure() throws LoginException { whenLoginThrowInvalidPasswordException(requiredDelegate); whenLoginReturnTrue(requisiteDelegate, optionalDelegate); whenLoginReturnFalse(sufficientDelegate); whenAbortReturnTrue(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); try { context.login(); } finally { verifyInitialize(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyLogin(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyAbort(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyNoMoreInteractions(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); } }
@Test(expectedExceptions = InvalidPasswordException.class) public void requisiteFailure() throws LoginException { whenLoginReturnTrue(requiredDelegate); whenLoginThrowInvalidPasswordException(requisiteDelegate); whenAbortReturnTrue(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); try { context.login(); } finally { verifyInitialize(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyLogin(requiredDelegate, requisiteDelegate); verifyAbort(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyNoMoreInteractions(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); } }
@Test public void optionalFailureIgnored() throws LoginException { whenLoginReturnTrue(requiredDelegate, requisiteDelegate); whenLoginReturnFalse(sufficientDelegate); whenLoginThrowInvalidPasswordException(optionalDelegate); whenCommitReturnTrue(requiredDelegate, requisiteDelegate); whenCommitReturnFalse(sufficientDelegate, optionalDelegate); context.login(); verifyInitialize(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyLogin(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyCommit(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyNoMoreInteractions(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); }
@Test(expectedExceptions = InvalidPasswordException.class) public void optionalFailureNoted() throws LoginException { whenLoginReturnFalse(requiredDelegate, requisiteDelegate, sufficientDelegate); whenLoginThrowInvalidPasswordException(optionalDelegate); whenAbortReturnTrue(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); try { context.login(); } finally { verifyInitialize(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyLogin(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyAbort(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyNoMoreInteractions(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); } }
@Test public void optionalSuccessNoted() throws LoginException { whenLoginReturnFalse(requiredDelegate, requisiteDelegate, sufficientDelegate); whenLoginReturnTrue(optionalDelegate); whenCommitReturnFalse(requiredDelegate, requisiteDelegate, sufficientDelegate); whenCommitReturnTrue(optionalDelegate); context.login(); verifyInitialize(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyLogin(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyCommit(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); verifyNoMoreInteractions(requiredDelegate, requisiteDelegate, sufficientDelegate, optionalDelegate); }
|
ClusterStateService extends GeneralTaskRunnable { private int getNextSelected() { return lastSelected = (lastSelected + 1) % serverSelectionList.length; } protected ClusterStateService(SessionService sessionService, String localServerId,
int timeout, long period, Map<String, String> members); long getRunPeriod(); boolean addElement(Object obj); boolean removeElement(Object obj); boolean isEmpty(); void run(); @Override String toString(); static Debug sessionDebug; static final int DEFAULT_TIMEOUT; static final long DEFAULT_PERIOD; }
|
@Test(expectedExceptions={java.lang.ArithmeticException.class}) public void testGetNextSelected() throws Exception { int lastSelected = -1; lastSelected = (lastSelected + 1) % 0; assertTrue(false); }
|
QueryParameterMatcher { public boolean match(String queryString) { if (StringUtils.isEmpty(queryString)) { return false; } String[] queryParams = queryString.split("&"); for (String param : queryParams) { String[] params = param.split("="); if (params.length != 2) { throw new IllegalArgumentException("Query Param string does not contain valid query parameters"); } String key = params[0]; String val = params[1]; if (queryParam.equalsIgnoreCase(key) && value.equalsIgnoreCase(val)) { return true; } } return false; } QueryParameterMatcher(String queryParam, String value); boolean match(String queryString); }
|
@Test public void shouldMatch() { QueryParameterMatcher queryParameterMatcher = new QueryParameterMatcher("KEY", "VALUE"); boolean matches = queryParameterMatcher.match("A=1&KeY=VALuE&-fdw=23nd"); assertTrue(matches); }
@Test public void shouldNotMatchOnKey() { QueryParameterMatcher queryParameterMatcher = new QueryParameterMatcher("KEY", "VALUE"); boolean matches = queryParameterMatcher.match("A=1&KEY1=VALUE&-fdw=23nd"); assertFalse(matches); }
@Test public void shouldNotMatchOnValue() { QueryParameterMatcher queryParameterMatcher = new QueryParameterMatcher("KEY", "VALUE"); boolean matches = queryParameterMatcher.match("A=1&KEY=VALUE1&-fdw=23nd"); assertFalse(matches); }
@Test public void shouldNotMatchWhenQueryStringIsNull() { QueryParameterMatcher queryParameterMatcher = new QueryParameterMatcher("KEY", "VALUE"); boolean matches = queryParameterMatcher.match(null); assertFalse(matches); }
@Test public void shouldNotMatchWhenQueryStringIsEmpty() { QueryParameterMatcher queryParameterMatcher = new QueryParameterMatcher("KEY", "VALUE"); boolean matches = queryParameterMatcher.match(""); assertFalse(matches); }
@Test (expectedExceptions = IllegalArgumentException.class) public void shouldThrowIllegalArgumentExceptionWhenMissingEqualsInQueryParamKeyValue() { QueryParameterMatcher queryParameterMatcher = new QueryParameterMatcher("KEY", "VALUE"); queryParameterMatcher.match("KEYVALUE"); fail(); }
|
EndpointMatcher { public boolean match(HttpServletRequest request) { String path = getRequestPath(request); try { Map<String, String> details = restDispatcher.getRequestDetails(path); if (details.get("resourceId") != null) { path = details.get("resourceName") + "/" + details.get("resourceId"); } else { path = details.get("resourceName"); } } catch (NotFoundException e) { DEBUG.message("Resource " + request.getPathInfo() + " not found."); return false; } Endpoint requestEndpoint = new Endpoint(path, request.getMethod()); if (endpoints.contains(requestEndpoint)) { int index = endpoints.indexOf(requestEndpoint); Endpoint endpoint = endpoints.get(index); return matchQueryParameters(request, endpoint); } return false; } EndpointMatcher(String rootPath, RestDispatcher restDispatcher); boolean match(HttpServletRequest request); void endpoint(String uri, String httpMethod); void endpoint(String uri, String httpMethod, String queryParam, String... queryParamValues); }
|
@Test public void shouldMatchEndpointWithNoQueryParams() throws NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/URI_A"); given(request.getMethod()).willReturn("GET"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/URI_A"); given(restDispatcher.getRequestDetails("/URI_A")).willReturn(details); boolean matches = endpointMatcher.match(request); assertTrue(matches); }
@Test public void shouldNotMatchEndpointWithNoQueryParams() throws NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/URI_B"); given(request.getMethod()).willReturn("GET"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/URI_B"); given(restDispatcher.getRequestDetails("/URI_B")).willReturn(details); boolean matches = endpointMatcher.match(request); assertFalse(matches); }
@Test public void shouldMatchEndpointWithQueryParams() throws NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/URI_C"); given(request.getMethod()).willReturn("PUT"); given(request.getQueryString()).willReturn("other1=valueA&QUERY_PARAM=VALUEA&other2=valueb"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/URI_C"); given(restDispatcher.getRequestDetails("/URI_C")).willReturn(details); boolean matches = endpointMatcher.match(request); assertTrue(matches); }
@Test public void shouldNotMatchEndpointWithQueryParams() throws NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/URI_C"); given(request.getMethod()).willReturn("PUT"); given(request.getQueryString()).willReturn("other1=valueA&QUERY_PARAM=VALUEC&other2=valueb"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/URI_C"); given(restDispatcher.getRequestDetails("/URI_C")).willReturn(details); boolean matches = endpointMatcher.match(request); assertFalse(matches); }
@Test public void shouldMatchEndpointWithPathInfo() throws NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getPathInfo()).willReturn("/URI_A"); given(request.getMethod()).willReturn("GET"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/URI_A"); given(restDispatcher.getRequestDetails("/URI_A")).willReturn(details); boolean matches = endpointMatcher.match(request); assertTrue(matches); }
@Test public void shouldMatchEndpointWithResourceNameAndId() throws NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); given(request.getPathInfo()).willReturn("/URI_A"); given(request.getMethod()).willReturn("GET"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceId", "URI_A"); details.put("resourceName", "/URI_B"); given(restDispatcher.getRequestDetails("/URI_A")).willReturn(details); boolean matches = endpointMatcher.match(request); assertTrue(matches); }
|
AMAuthNFilter extends AuthNFilter { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; String contextPath = request.getContextPath(); String requestURI = request.getRequestURI(); String path = requestURI.substring(contextPath.length()); if (endpointMatcher.match(request)) { DEBUG.message("Path: " + path + " Method: " + request.getMethod() + " Added as exception. Not protected."); filterChain.doFilter(servletRequest, servletResponse); } else { DEBUG.message("Path: " + path + " Method: " + request.getMethod() + " Protected resource."); super.doFilter(servletRequest, servletResponse, filterChain); } } AMAuthNFilter(); AMAuthNFilter(RestDispatcher restDispatcher); void init(FilterConfig filterConfig); void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain); }
|
@Test public void shouldAllowUnauthenticatedRestAuthEndpointWithPOST() throws IOException, ServletException, NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/authenticate"); given(request.getMethod()).willReturn("POST"); given(request.getRequestURL()).willReturn(new StringBuffer("http: given(request.getContextPath()).willReturn("/openam"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/authenticate"); given(restDispatcher.getRequestDetails("/authenticate")).willReturn(details); amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain).doFilter(request, response); }
@Test public void shouldAllowUnauthenticatedRestUsersEndpointWithPOSTAndActionRegister() throws IOException, ServletException, NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getQueryString()).willReturn("other1=valueA&_action=register&other2=valueb"); given(request.getMethod()).willReturn("POST"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/users"); given(restDispatcher.getRequestDetails("/users")).willReturn(details); amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain).doFilter(request, response); }
@Test public void shouldAllowUnauthenticatedRestUsersEndpointWithPOSTAndActionConfirm() throws IOException, ServletException, NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getQueryString()).willReturn("other1=valueA&_action=confirm&other2=valueb"); given(request.getMethod()).willReturn("POST"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/users"); given(restDispatcher.getRequestDetails("/users")).willReturn(details); amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain).doFilter(request, response); }
@Test public void shouldAllowUnauthenticatedRestUsersEndpointWithPOSTAndActionForgotPassword() throws IOException, ServletException, NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getQueryString()).willReturn("other1=valueA&_action=forgotPassword&other2=valueb"); given(request.getMethod()).willReturn("POST"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/users"); given(restDispatcher.getRequestDetails("/users")).willReturn(details); amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain).doFilter(request, response); }
@Test public void shouldAllowUnauthenticatedRestUsersEndpointWithPOSTAndActionForgotPasswordReset() throws IOException, ServletException, NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getQueryString()).willReturn("other1=valueA&_action=forgotPasswordReset&other2=valueb"); given(request.getMethod()).willReturn("POST"); Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/users"); given(restDispatcher.getRequestDetails("/users")).willReturn(details); amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain).doFilter(request, response); }
@Test public void shouldANotllowUnauthenticatedRestUsersEndpointWithPOSTAndActionForgotIdFromSession() throws IOException, ServletException, NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getQueryString()).willReturn("other1=valueA&_action=idFromSession&other2=valueb"); given(request.getMethod()).willReturn("POST"); given(request.getRequestURL()).willReturn(new StringBuffer("http: Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/users"); given(restDispatcher.getRequestDetails("/users")).willReturn(details); amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain, never()).doFilter(request, response); }
@Test public void shouldNotAllowUnauthenticatedRestUsersEndpointWithGET() throws IOException, ServletException, NotFoundException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getMethod()).willReturn("GET"); given(request.getRequestURL()).willReturn(new StringBuffer("http: Map<String, String> details = new HashMap<String, String>(); details.put("resourceName", "/users"); given(restDispatcher.getRequestDetails("/users")).willReturn(details); amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain, never()).doFilter(request, response); }
@Test public void shouldNotAllowUnauthenticatedRestUsersEndpointWithPUT() throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getMethod()).willReturn("PUT"); given(request.getRequestURL()).willReturn(new StringBuffer("http: amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain, never()).doFilter(request, response); }
@Test public void shouldNotAllowUnauthenticatedRestUsersEndpointWithPATCH() throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getMethod()).willReturn("PATCH"); given(request.getRequestURL()).willReturn(new StringBuffer("http: amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain, never()).doFilter(request, response); }
@Test public void shouldNotAllowUnauthenticatedRestUsersEndpointWithDELETE() throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getContextPath()).willReturn("/openam"); given(request.getRequestURI()).willReturn("/openam/json/users"); given(request.getMethod()).willReturn("DELETE"); given(request.getRequestURL()).willReturn(new StringBuffer("http: amAuthNFilter.doFilter(request, response, filterChain); verify(filterChain, never()).doFilter(request, response); }
|
Endpoint { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Endpoint that = (Endpoint) o; if (!httpMethod.equals(that.httpMethod)) return false; if (!uri.startsWith(that.uri)) return false; return true; } Endpoint(String uri, String httpMethod); Endpoint(String uri, String httpMethod, String queryParam, String... queryParamValues); Set<QueryParameterMatcher> getQueryParamMatchers(); @Override boolean equals(Object o); @Override int hashCode(); }
|
@Test public void shouldEquals() { Endpoint endpointOne = new Endpoint("URI", "HTTP_METHOD"); Endpoint endpointTwo = new Endpoint("URI", "HTTP_METHOD", "QUERY_PARAM", "VALUE"); Endpoint endpointThree = new Endpoint("URI", "HTTP_METHOD", "QUERY_PARAM", "VALUE", "VALUE2"); boolean oneEqualsTwo = endpointOne.equals(endpointTwo); boolean oneEqualsThree = endpointOne.equals(endpointThree); boolean twoEqualsOne = endpointTwo.equals(endpointOne); boolean twoEqualsThree = endpointTwo.equals(endpointThree); boolean threeEqualsOne = endpointThree.equals(endpointOne); boolean threeEqualsTwo = endpointThree.equals(endpointTwo); assertTrue(oneEqualsTwo); assertTrue(oneEqualsThree); assertTrue(twoEqualsOne); assertTrue(twoEqualsThree); assertTrue(threeEqualsOne); assertTrue(threeEqualsTwo); }
|
Endpoint { @Override public int hashCode() { int result = uri.hashCode(); result = 31 * result + httpMethod.hashCode(); return result; } Endpoint(String uri, String httpMethod); Endpoint(String uri, String httpMethod, String queryParam, String... queryParamValues); Set<QueryParameterMatcher> getQueryParamMatchers(); @Override boolean equals(Object o); @Override int hashCode(); }
|
@Test public void shouldHashCodesEqual() { Endpoint endpointOne = new Endpoint("URI", "HTTP_METHOD"); Endpoint endpointTwo = new Endpoint("URI", "HTTP_METHOD", "QUERY_PARAM", "VALUE"); Endpoint endpointThree = new Endpoint("URI", "HTTP_METHOD", "QUERY_PARAM", "VALUE", "VALUE2"); int oneHashCode = endpointOne.hashCode(); int twoHashCode = endpointTwo.hashCode(); int threeHashCode = endpointThree.hashCode(); assertEquals(oneHashCode, twoHashCode); assertEquals(oneHashCode, threeHashCode); assertEquals(twoHashCode, threeHashCode); }
|
Endpoint { public Set<QueryParameterMatcher> getQueryParamMatchers() { Set<QueryParameterMatcher> queryParamMatchers = new HashSet<QueryParameterMatcher>(); if (queryParam != null) { for (String queryParamValue : queryParamValues) { queryParamMatchers.add(new QueryParameterMatcher(queryParam, queryParamValue)); } } return queryParamMatchers; } Endpoint(String uri, String httpMethod); Endpoint(String uri, String httpMethod, String queryParam, String... queryParamValues); Set<QueryParameterMatcher> getQueryParamMatchers(); @Override boolean equals(Object o); @Override int hashCode(); }
|
@Test public void shouldGetQueryParamMatchers() { Endpoint endpoint = new Endpoint("URI", "HTTP_METHOD", "QUERY_PARAM", "VALUE", "VALUE2"); Set<QueryParameterMatcher> queryParamMatchers = endpoint.getQueryParamMatchers(); assertEquals(queryParamMatchers.size(), 2); }
@Test public void shouldGetEmptyQueryParamMatchersWhenOnlyQueryParamNameSet() { Endpoint endpoint = new Endpoint("/URI_C", "POST", "QUERY_PARAM"); Set<QueryParameterMatcher> queryParamMatchers = endpoint.getQueryParamMatchers(); assertTrue(queryParamMatchers.isEmpty()); }
|
RestSecurityContextMapper implements Filter { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; String authcid = request.getHeader(AuthNFilter.ATTRIBUTE_AUTH_PRINCIPAL); Map<String, Object> authzid = (Map<String, Object>) request.getAttribute(AuthNFilter.ATTRIBUTE_AUTH_CONTEXT); request.setAttribute(SecurityContextFactory.ATTRIBUTE_AUTHCID, authcid); request.setAttribute(SecurityContextFactory.ATTRIBUTE_AUTHZID, authzid); filterChain.doFilter(request, servletResponse); } void init(FilterConfig filterConfig); void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain); void destroy(); }
|
@Test public void shouldMapAuthAttributesToCRESTAttributesWithNulls() throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); given(request.getHeader(AMAuthNFilter.ATTRIBUTE_AUTH_PRINCIPAL)).willReturn(null); given(request.getAttribute(AMAuthNFilter.ATTRIBUTE_AUTH_CONTEXT)).willReturn(null); restSecurityContextMapper.doFilter(request, response, filterChain); verify(request).setAttribute(SecurityContextFactory.ATTRIBUTE_AUTHCID, null); verify(request).setAttribute(SecurityContextFactory.ATTRIBUTE_AUTHZID, null); verify(filterChain).doFilter(request, response); }
@Test public void shouldMapAuthAttributesToCRESTAttributes() throws IOException, ServletException { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain filterChain = mock(FilterChain.class); Map<String, Object> authenticationContext = new HashMap<String, Object>(); authenticationContext.put("ssoTokenId", "asdweq ED23RFCD"); given(request.getHeader(AMAuthNFilter.ATTRIBUTE_AUTH_PRINCIPAL)).willReturn("AUTHC_ID"); given(request.getAttribute(AMAuthNFilter.ATTRIBUTE_AUTH_CONTEXT)).willReturn(authenticationContext); restSecurityContextMapper.doFilter(request, response, filterChain); verify(request).setAttribute(SecurityContextFactory.ATTRIBUTE_AUTHCID, "AUTHC_ID"); verify(request).setAttribute(SecurityContextFactory.ATTRIBUTE_AUTHZID, authenticationContext); verify(filterChain).doFilter(request, response); }
|
LocalSSOTokenSessionModule implements ServerAuthModule { @Override public Class[] getSupportedMessageTypes() { return new Class[]{HttpServletRequest.class, HttpServletResponse.class}; } LocalSSOTokenSessionModule(); LocalSSOTokenSessionModule(AuthnRequestUtils requestUtils, SSOTokenFactory factory,
AuthUtilsWrapper authUtilsWrapper); @Override void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler,
Map options); @Override Class[] getSupportedMessageTypes(); @Override AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject,
Subject serviceSubject); @Override AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject); @Override void cleanSubject(MessageInfo messageInfo, Subject subject); AuthnRequestUtils getRequestUtils(); SSOTokenFactory getFactory(); }
|
@Test public void shouldGetSupportedMessageTypes() { Class[] supportedMessageTypes = localSSOTokenSessionModule.getSupportedMessageTypes(); assertEquals(supportedMessageTypes.length, 2); assertEquals(supportedMessageTypes[0], HttpServletRequest.class); assertEquals(supportedMessageTypes[1], HttpServletResponse.class); }
|
LocalSSOTokenSessionModule implements ServerAuthModule { @Override public AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject, Subject serviceSubject) throws AuthException { if (!isInitialised()) { initDependencies(); } final HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage(); String requester = request.getParameter(REQUESTER_URL_PARAM); if (requester != null) { try { SSOToken requesterToken = getFactory().getTokenFromId(requester); if (getFactory().isTokenValid(requesterToken)) { Object o = RestrictedTokenContext.doUsing(requesterToken, new RestrictedTokenAction() { public Object run() throws Exception { return validate(request, messageInfo, clientSubject); } }); return (AuthStatus) o; } } catch (Exception ex) { throw new AuthException("An error occurred whilst trying to use restricted token."); } } return validate(request, messageInfo, clientSubject); } LocalSSOTokenSessionModule(); LocalSSOTokenSessionModule(AuthnRequestUtils requestUtils, SSOTokenFactory factory,
AuthUtilsWrapper authUtilsWrapper); @Override void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler,
Map options); @Override Class[] getSupportedMessageTypes(); @Override AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject,
Subject serviceSubject); @Override AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject); @Override void cleanSubject(MessageInfo messageInfo, Subject subject); AuthnRequestUtils getRequestUtils(); SSOTokenFactory getFactory(); }
|
@Test public void shouldValidateRequestWithCookiesNull() throws AuthException { MessageInfo messageInfo = mock(MessageInfo.class); Subject clientSubject = new Subject(); Subject serviceSubject = new Subject(); HttpServletRequest request = mock(HttpServletRequest.class); given(messageInfo.getRequestMessage()).willReturn(request); AuthStatus authStatus = localSSOTokenSessionModule.validateRequest(messageInfo, clientSubject, serviceSubject); assertEquals(authStatus, AuthStatus.SEND_FAILURE); }
@Test public void shouldValidateRequestWithCookiesEmpty() throws AuthException { MessageInfo messageInfo = mock(MessageInfo.class); Subject clientSubject = new Subject(); Subject serviceSubject = new Subject(); HttpServletRequest request = mock(HttpServletRequest.class); given(messageInfo.getRequestMessage()).willReturn(request); given(request.getCookies()).willReturn(new Cookie[0]); AuthStatus authStatus = localSSOTokenSessionModule.validateRequest(messageInfo, clientSubject, serviceSubject); assertEquals(authStatus, AuthStatus.SEND_FAILURE); }
@Test public void shouldValidateRequestWithCookiesNoSSOToken() throws AuthException { MessageInfo messageInfo = mock(MessageInfo.class); Subject clientSubject = new Subject(); Subject serviceSubject = new Subject(); HttpServletRequest request = mock(HttpServletRequest.class); given(messageInfo.getRequestMessage()).willReturn(request); given(request.getCookies()).willReturn(new Cookie[]{new Cookie("2", "2"), new Cookie("1", "1")}); AuthStatus authStatus = localSSOTokenSessionModule.validateRequest(messageInfo, clientSubject, serviceSubject); assertEquals(authStatus, AuthStatus.SEND_FAILURE); }
@Test public void shouldValidateRequestWithCookiesIncludingInvalidSSOToken() throws SSOException, AuthException { String tokenName = "SSO_TOKEN_ID"; MessageInfo messageInfo = mock(MessageInfo.class); Subject clientSubject = new Subject(); Subject serviceSubject = new Subject(); HttpServletRequest request = mock(HttpServletRequest.class); given(messageInfo.getRequestMessage()).willReturn(request); given(request.getCookies()).willReturn(new Cookie[]{new Cookie("2", "2"), new Cookie(AuthnRequestUtils.SSOTOKEN_COOKIE_NAME, tokenName), new Cookie("1", "1")}); given(mockUtils.getTokenId(eq(request))).willReturn(tokenName); given(mockFactory.getTokenFromId(anyString())).willReturn(null); AuthStatus authStatus = localSSOTokenSessionModule.validateRequest(messageInfo, clientSubject, serviceSubject); assertEquals(authStatus, AuthStatus.SEND_FAILURE); }
|
LocalSSOTokenSessionModule implements ServerAuthModule { @Override public AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject) { return AuthStatus.SEND_SUCCESS; } LocalSSOTokenSessionModule(); LocalSSOTokenSessionModule(AuthnRequestUtils requestUtils, SSOTokenFactory factory,
AuthUtilsWrapper authUtilsWrapper); @Override void initialize(MessagePolicy requestPolicy, MessagePolicy responsePolicy, CallbackHandler handler,
Map options); @Override Class[] getSupportedMessageTypes(); @Override AuthStatus validateRequest(final MessageInfo messageInfo, final Subject clientSubject,
Subject serviceSubject); @Override AuthStatus secureResponse(MessageInfo messageInfo, Subject serviceSubject); @Override void cleanSubject(MessageInfo messageInfo, Subject subject); AuthnRequestUtils getRequestUtils(); SSOTokenFactory getFactory(); }
|
@Test public void shouldSecureResponse() { MessageInfo messageInfo = mock(MessageInfo.class); Subject serviceSubject = new Subject(); AuthStatus authStatus = localSSOTokenSessionModule.secureResponse(messageInfo, serviceSubject); assertEquals(authStatus, AuthStatus.SEND_SUCCESS); }
|
AuthZAuditLogger implements AuditLogger { @Override public void audit(AuditRecord auditRecord) { String tokenId = requestUtils.getTokenId(auditRecord.getHttpServletRequest()); String message; Logger logger; switch (auditRecord.getAuthResult()) { case SUCCESS: { message = "Authorization Succeeded. " + auditRecord.getHttpServletRequest().getRequestURI(); logger = loggerFactory.getLogger(AUDIT_LOG_NAME + ".access"); break; } default: { message = "Authorization Failed. " + auditRecord.getHttpServletRequest().getRequestURI(); logger = loggerFactory.getLogger(AUDIT_LOG_NAME + ".error"); } } SSOToken adminToken = ssoTokenFactory.getAdminToken(); SSOToken subjectToken = ssoTokenFactory.getTokenFromId(tokenId); LogRecord logRecord = new LogRecord(Level.INFO, message, subjectToken); logger.log(logRecord, adminToken); logger.flush(); } @Inject AuthZAuditLogger(SSOTokenFactory ssoTokenFactory, AuthnRequestUtils requestUtils,
LoggerFactory loggerFactory); @Override void audit(AuditRecord auditRecord); }
|
@Test public void shouldAuditLogSuccessfulAuthorization() throws SSOException { AuditRecord auditRecord = mock(AuditRecord.class); HttpServletRequest request = mock(HttpServletRequest.class); SSOToken subjectToken = mock(SSOToken.class); SSOTokenID subjectTokenId = mock(SSOTokenID.class); Principal principal = mock(Principal.class); given(auditRecord.getHttpServletRequest()).willReturn(request); given(auditRecord.getAuthResult()).willReturn(AuthResult.SUCCESS); given(request.getRequestURI()).willReturn("REQUEST_URI"); given(requestUtils.getTokenId(request)).willReturn("TOKEN_ID"); given(ssoTokenFactory.getTokenFromId("TOKEN_ID")).willReturn(subjectToken); given(subjectToken.getTokenID()).willReturn(subjectTokenId); given(subjectTokenId.toString()).willReturn("TOKEN_ID"); given(subjectToken.getPrincipal()).willReturn(principal); given(principal.getName()).willReturn("PRINCIPAL_NAME"); authZAuditLogger.audit(auditRecord); verify(loggerFactory).getLogger("amAuthorization.access"); ArgumentCaptor<LogRecord> logRecordCaptor = ArgumentCaptor.forClass(LogRecord.class); verify(logger).log(logRecordCaptor.capture(), eq(adminToken)); LogRecord logRecord = logRecordCaptor.getValue(); assertEquals(logRecord.getLevel(), Level.INFO); assertTrue(logRecord.getMessage().contains("Succeeded")); assertEquals(logRecord.getLogFor(), subjectToken); verify(logger).flush(); }
@Test public void shouldAuditLogUnsuccessfulAuthorization() throws SSOException { AuditRecord auditRecord = mock(AuditRecord.class); HttpServletRequest request = mock(HttpServletRequest.class); SSOToken subjectToken = mock(SSOToken.class); SSOTokenID subjectTokenId = mock(SSOTokenID.class); Principal principal = mock(Principal.class); given(auditRecord.getHttpServletRequest()).willReturn(request); given(auditRecord.getAuthResult()).willReturn(AuthResult.FAILURE); given(request.getRequestURI()).willReturn("REQUEST_URI"); given(requestUtils.getTokenId(request)).willReturn("TOKEN_ID"); given(ssoTokenFactory.getTokenFromId("TOKEN_ID")).willReturn(subjectToken); given(subjectToken.getTokenID()).willReturn(subjectTokenId); given(subjectTokenId.toString()).willReturn("TOKEN_ID"); given(subjectToken.getPrincipal()).willReturn(principal); given(principal.getName()).willReturn("PRINCIPAL_NAME"); authZAuditLogger.audit(auditRecord); verify(loggerFactory).getLogger("amAuthorization.error"); ArgumentCaptor<LogRecord> logRecordCaptor = ArgumentCaptor.forClass(LogRecord.class); verify(logger).log(logRecordCaptor.capture(), eq(adminToken)); LogRecord logRecord = logRecordCaptor.getValue(); assertEquals(logRecord.getLevel(), Level.INFO); assertTrue(logRecord.getMessage().contains("Failed")); assertEquals(logRecord.getLogFor(), subjectToken); verify(logger).flush(); }
|
AdminAuthorizationFilter implements AuthorizationFilter { @Override public boolean authorize(HttpServletRequest servletRequest, HttpServletResponse servletResponse) { String tokenId = requestUtils.getTokenId(servletRequest); if (StringUtils.isEmpty(tokenId)) { tokenId = servletRequest.getHeader(getCookieHeaderName()); } if (StringUtils.isEmpty(tokenId)) { return false; } SSOToken token = ssoTokenFactory.getTokenFromId(tokenId); if (token == null) { return false; } String userId; try { userId = token.getProperty(Constants.UNIVERSAL_IDENTIFIER); } catch (SSOException e) { debugLogger.error("Failed to get userId", e); throw new IllegalStateException(e); } return sessionService.isSuperUser(userId); } @Inject AdminAuthorizationFilter(SSOTokenFactory ssoTokenFactory, AuthnRequestUtils requestUtils,
SessionService sessionService, AuthUtilsWrapper authUtilsWrapper); @Override void initialise(LoggingConfigurator configuration, AuditLogger auditLogger, DebugLogger debugLogger); @Override boolean authorize(HttpServletRequest servletRequest, HttpServletResponse servletResponse); }
|
@Test public void shouldReturnFalseWhenTokenIdNotInRequest() { HttpServletRequest request = mock(HttpServletRequest.class); given(requestUtils.getTokenId(request)).willReturn(null); boolean authorized = filter.authorize(request, null); assertFalse(authorized); }
@Test public void shouldReturnFalseWhenTokenIdCannotBeResolved() { HttpServletRequest request = mock(HttpServletRequest.class); given(requestUtils.getTokenId(request)).willReturn("TOKEN_ID"); given(ssoTokenFactory.getTokenFromId("TOKEN_ID")).willReturn(null); boolean authorized = filter.authorize(request, null); assertFalse(authorized); }
@Test (expectedExceptions = IllegalStateException.class) public void shouldThrowSSOExceptionWhenUserIdNotFound() throws SSOException { HttpServletRequest request = mock(HttpServletRequest.class); SSOToken token = mock(SSOToken.class); given(requestUtils.getTokenId(request)).willReturn("TOKEN_ID"); given(ssoTokenFactory.getTokenFromId("TOKEN_ID")).willReturn(token); given(token.getProperty(Constants.UNIVERSAL_IDENTIFIER)).willThrow(SSOException.class); filter.authorize(request, null); fail(); }
@Test public void shouldDelegateSuperUserCheckToSessionService() throws SSOException { HttpServletRequest request = mock(HttpServletRequest.class); SSOToken token = mock(SSOToken.class); given(requestUtils.getTokenId(request)).willReturn("TOKEN_ID"); given(ssoTokenFactory.getTokenFromId("TOKEN_ID")).willReturn(token); given(token.getProperty(Constants.UNIVERSAL_IDENTIFIER)).willReturn("USER_ID"); filter.authorize(request, null); verify(sessionService).isSuperUser("USER_ID"); }
|
SessionResourceAuthzFilter extends AdminAuthorizationFilter { @Override public boolean authorize(HttpServletRequest servletRequest, HttpServletResponse servletResponse) { if (servletRequest != null) { Map<String, String[]> parameterMap = servletRequest.getParameterMap(); if (parameterMap != null && parameterMap.containsKey("_action")) { String[] values = parameterMap.get("_action"); if (values != null && values.length > 0 && "logout".equalsIgnoreCase(values[0])) { return true; } } } return super.authorize(servletRequest, servletResponse); } @Inject SessionResourceAuthzFilter(SSOTokenFactory ssoTokenFactory, AuthnRequestUtils requestUtils,
SessionService sessionService, AuthUtilsWrapper authUtilsWrapper); @Override boolean authorize(HttpServletRequest servletRequest, HttpServletResponse servletResponse); }
|
@Test public void shouldReturnTrueWhenRequestQueryParamsContainsActionLogout() { HttpServletRequest request = mock(HttpServletRequest.class); Map<String, String[]> parameterMap = new HashMap<String, String[]>(); given(request.getParameterMap()).willReturn(parameterMap); parameterMap.put("_action", new String[]{"logOUT"}); boolean authorized = sessionResourceAuthzFilter.authorize(request, null); assertTrue(authorized); }
@Test public void shouldFallbackToAdminOnlyAuthzAndReturnFalse() { HttpServletRequest request = mock(HttpServletRequest.class); Map<String, String> parameterMap = new HashMap<String, String>(); given(request.getParameterMap()).willReturn(parameterMap); boolean authorized = sessionResourceAuthzFilter.authorize(request, null); assertFalse(authorized); }
|
RestAuthorizationDispatcherFilter implements Filter { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { throw new ServletException("Request must be of types HttpServletRequest"); } HttpServletRequest request = (HttpServletRequest) servletRequest; try { final String resourcePath = request.getPathInfo(); Map<String, String> details = restDispatcher.getRequestDetails(resourcePath == null ? "/" : resourcePath); String endpoint = details.get("resourceName"); if (RestDispatcher.REALMS.equalsIgnoreCase(endpoint)) { authorize(realmsAuthzConfiguratorClassName, request, servletResponse, chain); } else if (RestDispatcher.USERS.equalsIgnoreCase(endpoint)) { authorize(usersAuthzConfiguratorClassName, request, servletResponse, chain); } else if (RestDispatcher.GROUPS.equalsIgnoreCase(endpoint)) { authorize(groupsAuthzConfiguratorClassName, request, servletResponse, chain); } else if (RestDispatcher.AGENTS.equalsIgnoreCase(endpoint)) { authorize(agentsAuthzConfiguratorClassName, request, servletResponse, chain); } else if (RestDispatcher.SERVER_INFO.equalsIgnoreCase(endpoint)) { authorize(serverInfoAuthzConfiguratorClassName, request, servletResponse, chain); } else if (RestDispatcher.SESSIONS.equalsIgnoreCase(endpoint)) { authorize(sessionAuthzConfiguratorClassName, request, servletResponse, chain); } } catch (NotFoundException e) { DEBUG.message("Resource " + request.getPathInfo() + " not found. Not performing authorization on request."); chain.doFilter(servletRequest, servletResponse); } } RestAuthorizationDispatcherFilter(); RestAuthorizationDispatcherFilter(RestDispatcher restDispatcher, AuthZFilter authZFilter); void init(FilterConfig filterConfig); void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain); void destroy(); }
|
@Test(expectedExceptions = ServletException.class) public void shouldThrowServletExceptionIfRequestIsNotHttpServletRequest() throws Exception { initFilter(INIT_PARAMS); ServletRequest request = mock(ServletRequest.class); ServletResponse response = mock(ServletResponse.class); FilterChain filterChain = mock(FilterChain.class); restAuthorizationDispatcherFilter.doFilter(request, response, filterChain); }
|
RestAuthorizationDispatcherFilter implements Filter { public void destroy() { filterConfig = null; realmsAuthzConfiguratorClassName = null; usersAuthzConfiguratorClassName = null; groupsAuthzConfiguratorClassName = null; agentsAuthzConfiguratorClassName = null; } RestAuthorizationDispatcherFilter(); RestAuthorizationDispatcherFilter(RestDispatcher restDispatcher, AuthZFilter authZFilter); void init(FilterConfig filterConfig); void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain); void destroy(); }
|
@Test public void shouldDestroyFilter() { restAuthorizationDispatcherFilter.destroy(); }
|
RestAuthorizationDispatcherFilterConfig implements FilterConfig { public String getFilterName() { return filterConfig.getFilterName(); } RestAuthorizationDispatcherFilterConfig(final FilterConfig filterConfig,
final String authzConfiguratorClassName); String getFilterName(); ServletContext getServletContext(); String getInitParameter(String name); @SuppressWarnings("unchecked") Enumeration<String> getInitParameterNames(); }
|
@Test public void shouldGetFilterName() { filterConfig.getFilterName(); verify(wrappedFilterConfig).getFilterName(); }
|
RestAuthorizationDispatcherFilterConfig implements FilterConfig { public ServletContext getServletContext() { return filterConfig.getServletContext(); } RestAuthorizationDispatcherFilterConfig(final FilterConfig filterConfig,
final String authzConfiguratorClassName); String getFilterName(); ServletContext getServletContext(); String getInitParameter(String name); @SuppressWarnings("unchecked") Enumeration<String> getInitParameterNames(); }
|
@Test public void shouldGetServletContext() { filterConfig.getServletContext(); verify(wrappedFilterConfig).getServletContext(); }
|
RestAuthorizationDispatcherFilterConfig implements FilterConfig { public String getInitParameter(String name) { if (INIT_PARAM_AUTHZ_CONFIGURATOR.equals(name)) { return authzConfiguratorClassName; } return filterConfig.getInitParameter(name); } RestAuthorizationDispatcherFilterConfig(final FilterConfig filterConfig,
final String authzConfiguratorClassName); String getFilterName(); ServletContext getServletContext(); String getInitParameter(String name); @SuppressWarnings("unchecked") Enumeration<String> getInitParameterNames(); }
|
@Test public void shouldGetConfiguratorInitParameter() { given(wrappedFilterConfig.getInitParameter("other")).willReturn("OTHER"); String initParam = filterConfig.getInitParameter("configurator"); assertEquals(initParam, authzConfiguratorClassName); }
@Test public void shouldGetOtherInitParameter() { given(wrappedFilterConfig.getInitParameter("other")).willReturn("OTHER"); String initParam = filterConfig.getInitParameter("other"); assertEquals(initParam, "OTHER"); }
|
RestAuthorizationDispatcherFilterConfig implements FilterConfig { @SuppressWarnings("unchecked") public Enumeration<String> getInitParameterNames() { List<String> names = Collections.list(filterConfig.getInitParameterNames()); names.add(INIT_PARAM_AUTHZ_CONFIGURATOR); return Collections.enumeration(names); } RestAuthorizationDispatcherFilterConfig(final FilterConfig filterConfig,
final String authzConfiguratorClassName); String getFilterName(); ServletContext getServletContext(); String getInitParameter(String name); @SuppressWarnings("unchecked") Enumeration<String> getInitParameterNames(); }
|
@Test public void shouldGetInitParameterNames() { given(wrappedFilterConfig.getInitParameterNames()).willReturn(Collections.enumeration(Collections.emptyList())); Enumeration<String> initParameterNames = filterConfig.getInitParameterNames(); verify(wrappedFilterConfig).getInitParameterNames(); assertEquals(initParameterNames.nextElement(), "configurator"); }
|
SSOTokenFactory { public SSOToken getTokenFromId(String tokenId) { if (StringUtils.isEmpty(tokenId)) { return null; } if (debug.messageEnabled()) { debug.message("Creating SSOToken for ID: " + tokenId); } try { return manager.createSSOToken(tokenId); } catch (SSOException e) { debug.warning("Failed to create SSO Token for ID: " + tokenId, e); return null; } } @Inject SSOTokenFactory(SSOTokenManager manager); SSOTokenFactory(SSOTokenManager manager, Debug debug); SSOToken getTokenFromId(String tokenId); boolean isTokenValid(SSOToken token); SSOToken getAdminToken(); }
|
@Test public void shouldRejectEmptyTokenId() { SSOTokenManager mockManager = mock(SSOTokenManager.class); SSOTokenFactory tokenFactory = new SSOTokenFactory(mockManager); assertNull(tokenFactory.getTokenFromId("")); }
@Test public void shouldRejectEmptyTokenNull() { SSOTokenManager mockManager = mock(SSOTokenManager.class); SSOTokenFactory tokenFactory = new SSOTokenFactory(mockManager); assertNull(tokenFactory.getTokenFromId(null)); }
@Test public void shouldUseManagerToCreateSSOToken() throws SSOException { String key = "badger"; SSOTokenManager mockManager = mock(SSOTokenManager.class); SSOTokenFactory tokenFactory = new SSOTokenFactory(mockManager); tokenFactory.getTokenFromId(key); verify(mockManager).createSSOToken(eq(key)); }
|
AuthnRequestUtils { public String getTokenId(HttpServletRequest request) { return CookieUtils.getCookieValueFromReq(request, ssoTokenCookieName); } @Inject AuthnRequestUtils(@Named(SSOTOKEN_COOKIE_NAME) String ssoTokenCookieName); String getTokenId(HttpServletRequest request); static final String SSOTOKEN_COOKIE_NAME; }
|
@Test public void shouldReturnNullIfNoCookies() { String key = "badger"; HttpServletRequest request = mock(HttpServletRequest.class); AuthnRequestUtils utils = new AuthnRequestUtils(key); String response = utils.getTokenId(request); assertNull(response); }
@Test public void shouldUseCookiesToFindTokenId() { String key = "badger"; HttpServletRequest request = mock(HttpServletRequest.class); given(request.getCookies()).willReturn(new Cookie[]{}); AuthnRequestUtils utils = new AuthnRequestUtils(key); utils.getTokenId(request); verify(request).getCookies(); }
@Test public void shouldUseCookieNameToSelectCookie() { String key = "badger"; HttpServletRequest request = mock(HttpServletRequest.class); Cookie one = mock(Cookie.class); given(one.getName()).willReturn(key); given(request.getCookies()).willReturn(new Cookie[]{one}); AuthnRequestUtils utils = new AuthnRequestUtils(key); utils.getTokenId(request); verify(one).getValue(); }
|
OAuthTokenStore { public void create(JsonValue token) throws CoreTokenException { cts.create(tokenAdapter.toToken(token)); } @Inject OAuthTokenStore(CTSPersistentStore cts, TokenAdapter<JsonValue> tokenAdapter,
TokenIdFactory tokenIdFactory); void create(JsonValue token); JsonValue read(String id); void update(JsonValue token); void delete(String id); JsonValue query(Map<String, Object> queryParameters); JsonValue query(Map<String, Object> queryParameters, boolean and); }
|
@Test public void shouldCreate() throws CoreTokenException { JsonValue oAuthToken = mock(JsonValue.class); Token token = mock(Token.class); given(tokenAdapter.toToken(oAuthToken)).willReturn(token); oAuthTokenStore.create(oAuthToken); verify(cts).create(token); }
|
OAuthTokenStore { public JsonValue read(String id) throws CoreTokenException { Token token = cts.read(tokenIdFactory.getOAuthTokenId(id)); if (token == null) { return null; } return tokenAdapter.fromToken(token); } @Inject OAuthTokenStore(CTSPersistentStore cts, TokenAdapter<JsonValue> tokenAdapter,
TokenIdFactory tokenIdFactory); void create(JsonValue token); JsonValue read(String id); void update(JsonValue token); void delete(String id); JsonValue query(Map<String, Object> queryParameters); JsonValue query(Map<String, Object> queryParameters, boolean and); }
|
@Test public void shouldRead() throws CoreTokenException { Token token = mock(Token.class); given(tokenIdFactory.getOAuthTokenId("ID")).willReturn("ID2"); given(cts.read("ID2")).willReturn(token); JsonValue oAuthToken = oAuthTokenStore.read("ID"); verify(tokenAdapter).fromToken(token); }
|
OAuthTokenStore { public void update(JsonValue token) throws CoreTokenException { cts.update(tokenAdapter.toToken(token)); } @Inject OAuthTokenStore(CTSPersistentStore cts, TokenAdapter<JsonValue> tokenAdapter,
TokenIdFactory tokenIdFactory); void create(JsonValue token); JsonValue read(String id); void update(JsonValue token); void delete(String id); JsonValue query(Map<String, Object> queryParameters); JsonValue query(Map<String, Object> queryParameters, boolean and); }
|
@Test public void shouldUpdate() throws CoreTokenException { JsonValue oAuthToken = mock(JsonValue.class); Token token = mock(Token.class); given(tokenAdapter.toToken(oAuthToken)).willReturn(token); oAuthTokenStore.update(oAuthToken); verify(cts).update(token); }
|
OAuthTokenStore { public void delete(String id) throws DeleteFailedException { cts.delete(id); } @Inject OAuthTokenStore(CTSPersistentStore cts, TokenAdapter<JsonValue> tokenAdapter,
TokenIdFactory tokenIdFactory); void create(JsonValue token); JsonValue read(String id); void update(JsonValue token); void delete(String id); JsonValue query(Map<String, Object> queryParameters); JsonValue query(Map<String, Object> queryParameters, boolean and); }
|
@Test public void shouldDelete() throws CoreTokenException { oAuthTokenStore.delete("ID"); verify(cts).delete("ID"); }
|
OAuthTokenStore { public JsonValue query(Map<String, Object> queryParameters) throws CoreTokenException { return query(queryParameters, false); } @Inject OAuthTokenStore(CTSPersistentStore cts, TokenAdapter<JsonValue> tokenAdapter,
TokenIdFactory tokenIdFactory); void create(JsonValue token); JsonValue read(String id); void update(JsonValue token); void delete(String id); JsonValue query(Map<String, Object> queryParameters); JsonValue query(Map<String, Object> queryParameters, boolean and); }
|
@Test public void shouldQuery() throws CoreTokenException { Map<String, Object> queryParameters = new HashMap<String, Object>(); Collection<Token> tokens = new HashSet<Token>(); given(cts.list(Matchers.<Filter>anyObject())).willReturn(tokens); oAuthTokenStore.query(queryParameters); verify(cts).list(Matchers.<Filter>anyObject()); }
|
ScopeImpl implements Scope { public Set<String> scopeToPresentOnAuthorizationPage(Set<String> requestedScope, Set<String> availableScopes, Set<String> defaultScopes){ if (requestedScope == null || requestedScope.isEmpty()) { return defaultScopes; } Set<String> scopes = new HashSet<String>(availableScopes); scopes.retainAll(requestedScope); return scopes; } ScopeImpl(); ScopeImpl(OAuth2TokenStore store, AMIdentity id); Set<String> scopeToPresentOnAuthorizationPage(Set<String> requestedScope, Set<String> availableScopes, Set<String> defaultScopes); Set<String> scopeRequestedForAccessToken(Set<String> requestedScope, Set<String> availableScopes, Set<String> defaultScopes); Set<String> scopeRequestedForRefreshToken(Set<String> requestedScope,
Set<String> availableScopes,
Set<String> allScopes,
Set<String> defaultScopes); Map<String, Object> evaluateScope(CoreToken token); Map<String, Object> extraDataToReturnForTokenEndpoint(Map<String, String> parameters, CoreToken token); Map<String, String> extraDataToReturnForAuthorizeEndpoint(Map<String, String> parameters, Map<String, CoreToken> tokens); Map<String,Object> getUserInfo(CoreToken token); }
|
@Test public void testGetDefaultScopeForScopeToPresentOnAuthorizationPage() { suppress(constructor(DefaultOAuthTokenStoreImpl.class)); OAuth2TokenStore store = mock(DefaultOAuthTokenStoreImpl.class); AMIdentity id = PowerMockito.mock(AMIdentity.class); scopeImpl = new ScopeImpl(store, id); Set<String> requestedScope = new HashSet<String>(); Set<String> availableScope = new HashSet<String>(); Set<String> defaultScope = new HashSet<String>(); defaultScope.add("scope1"); defaultScope.add("scope2"); Set<String> returnedScope = scopeImpl.scopeToPresentOnAuthorizationPage(requestedScope, availableScope, defaultScope); assertEquals(returnedScope, defaultScope); }
@Test public void testGetRequestedScopeForScopeToPresentOnAuthorizationPage() { suppress(constructor(DefaultOAuthTokenStoreImpl.class)); OAuth2TokenStore store = mock(DefaultOAuthTokenStoreImpl.class); AMIdentity id = PowerMockito.mock(AMIdentity.class); scopeImpl = new ScopeImpl(store, id); Set<String> requestedScope = new HashSet<String>(); Set<String> availableScope = new HashSet<String>(); Set<String> defaultScope = new HashSet<String>(); defaultScope.add("scope1"); defaultScope.add("scope2"); requestedScope.add("scope3"); requestedScope.add("scope4"); availableScope.add("scope3"); availableScope.add("scope4"); availableScope.add("scope5"); Set<String> returnedScope = scopeImpl.scopeToPresentOnAuthorizationPage(requestedScope, availableScope, defaultScope); assertEquals(returnedScope, requestedScope); }
@Test public void testGetRequestedScopeForScopeToPresentOnAuthorizationPageWithExtraScopeRequest() { suppress(constructor(DefaultOAuthTokenStoreImpl.class)); OAuth2TokenStore store = mock(DefaultOAuthTokenStoreImpl.class); AMIdentity id = PowerMockito.mock(AMIdentity.class); scopeImpl = new ScopeImpl(store, id); Set<String> requestedScope = new HashSet<String>(); Set<String> availableScope = new HashSet<String>(); Set<String> defaultScope = new HashSet<String>(); defaultScope.add("scope1"); defaultScope.add("scope2"); requestedScope.add("scope3"); requestedScope.add("scope4"); requestedScope.add("scope6"); availableScope.add("scope3"); availableScope.add("scope4"); availableScope.add("scope5"); Set<String> returnedScope = scopeImpl.scopeToPresentOnAuthorizationPage(requestedScope, availableScope, defaultScope); Set<String> expectedScope = new HashSet<String>(requestedScope); expectedScope.remove("scope6"); assertEquals(returnedScope, expectedScope); }
|
ScopeImpl implements Scope { public Map<String,Object> getUserInfo(CoreToken token){ Set<String> scopes = token.getScope(); Map<String,Object> response = new HashMap<String, Object>(); AMIdentity id = null; if (this.id == null){ id = OAuth2Utils.getIdentity(token.getUserID(), token.getRealm()); } else { id = this.id; } response.put("sub", token.getUserID()); for(String scope: scopes){ Object attributes = scopeToUserUserProfileAttributes.get(scope); if (attributes == null){ OAuth2Utils.DEBUG.error("ScopeImpl.getUserInfo()::Invalid Scope in token scope="+ scope); } else if (attributes instanceof String){ Set<String> attr = null; try { attr = id.getAttribute((String)attributes); } catch (IdRepoException e) { OAuth2Utils.DEBUG.error("ScopeImpl.getUserInfo(): Unable to retrieve atrribute", e); } catch (SSOException e) { OAuth2Utils.DEBUG.error("ScopeImpl.getUserInfo(): Unable to retrieve atrribute", e); } if (attr != null && attr.size() == 1){ response.put(scope, attr.iterator().next()); } else if (attr != null && attr.size() > 1){ response.put(scope, attr); } else { OAuth2Utils.DEBUG.error("ScopeImpl.getUserInfo(): Got an empty result for scope=" + scope); } } else if (attributes instanceof Map){ if (attributes != null && !((Map<String,String>) attributes).isEmpty()){ for (Map.Entry<String, String> entry: ((Map<String, String>) attributes).entrySet()){ String attribute = null; attribute = (String)entry.getValue(); Set<String> attr = null; try { attr = id.getAttribute(attribute); } catch (IdRepoException e) { OAuth2Utils.DEBUG.error("ScopeImpl.getUserInfo(): Unable to retrieve atrribute", e); } catch (SSOException e) { OAuth2Utils.DEBUG.error("ScopeImpl.getUserInfo(): Unable to retrieve atrribute", e); } if (attr != null && attr.size() == 1){ response.put(entry.getKey(), attr.iterator().next()); } else if (attr != null && attr.size() > 1){ response.put(entry.getKey(), attr); } else { OAuth2Utils.DEBUG.error("ScopeImpl.getUserInfo(): Got an empty result for scope=" + scope); } } } } } return response; } ScopeImpl(); ScopeImpl(OAuth2TokenStore store, AMIdentity id); Set<String> scopeToPresentOnAuthorizationPage(Set<String> requestedScope, Set<String> availableScopes, Set<String> defaultScopes); Set<String> scopeRequestedForAccessToken(Set<String> requestedScope, Set<String> availableScopes, Set<String> defaultScopes); Set<String> scopeRequestedForRefreshToken(Set<String> requestedScope,
Set<String> availableScopes,
Set<String> allScopes,
Set<String> defaultScopes); Map<String, Object> evaluateScope(CoreToken token); Map<String, Object> extraDataToReturnForTokenEndpoint(Map<String, String> parameters, CoreToken token); Map<String, String> extraDataToReturnForAuthorizeEndpoint(Map<String, String> parameters, Map<String, CoreToken> tokens); Map<String,Object> getUserInfo(CoreToken token); }
|
@Test public void testGetUserInfo(){ suppress(constructor(DefaultOAuthTokenStoreImpl.class)); OAuth2TokenStore store = mock(DefaultOAuthTokenStoreImpl.class); AMIdentity id = PowerMockito.mock(AMIdentity.class); CoreToken token = mock(CoreToken.class); scopeImpl = new ScopeImpl(store, id); Set idAttribute = new HashSet<String>(); idAttribute.add("attributeValue"); Set scopeValue = new HashSet<String>(); scopeValue.add("email"); try { when(id.getAttribute(anyString())).thenReturn(idAttribute); } catch (Exception e){ } when(token.getUserID()).thenReturn("user"); when(token.getScope()).thenReturn(scopeValue); when(token.getRealm()).thenReturn("/"); Map<String, Object> returnValues = scopeImpl.getUserInfo(token); assert(returnValues.containsKey("sub") && returnValues.get("sub").equals("user")); assert(returnValues.containsKey("email") && returnValues.get("email").equals("attributeValue")); }
|
OpenIDConnectDiscovery extends ServerResource { @Get public Representation discovery(){ String resource = OAuth2Utils.getRequestParameter(getRequest(), "resource", String.class); String rel = OAuth2Utils.getRequestParameter(getRequest(), "rel", String.class); String realm = OAuth2Utils.getRealm(getRequest()); if (resource == null || resource.isEmpty()){ OAuth2Utils.DEBUG.error("OpenIDConnectDiscovery.discover()::No resource provided in discovery."); throw OAuthProblemException.OAuthError.BAD_REQUEST.handle(null, "OpenIDConnectDiscovery.discover()::No resource provided in discovery."); } if (rel == null || rel.isEmpty() || !rel.equalsIgnoreCase("http: OAuth2Utils.DEBUG.error("OpenIDConnectDiscovery.discover()::No or invalid rel provided in discovery."); throw OAuthProblemException.OAuthError.BAD_REQUEST.handle(null, "OpenIDConnectDiscovery.discover()::No or invalid rel provided in discovery."); } String userid = null; try { URI object = new URI(resource); if (object.getScheme().equalsIgnoreCase("https") || object.getScheme().equalsIgnoreCase("http")){ if (object.getPath().isEmpty()){ } else { userid = object.getPath(); userid = userid.substring(1,userid.length()); } } else if (object.getScheme().equalsIgnoreCase("acct")) { String s = new String(resource); s = s.replaceFirst("acct:", ""); int firstAt = s.indexOf('@'); userid = s.substring(0,firstAt); } else { OAuth2Utils.DEBUG.error("OpenIDConnectDiscovery.discover()::Invalid parameters."); throw OAuthProblemException.OAuthError.BAD_REQUEST.handle(null, "OpenIDConnectDiscovery.discover()::Invalid parameters."); } } catch (Exception e){ OAuth2Utils.DEBUG.error("OpenIDConnectDiscovery.discover()::Invalid parameters.", e); throw OAuthProblemException.OAuthError.BAD_REQUEST.handle(null, "OpenIDConnectDiscovery.discover()::Invalid parameters."); } if (userid != null){ AMIdentity id = null; try { id = OAuth2Utils.getIdentity(userid, realm); } catch (Exception e){ OAuth2Utils.DEBUG.error("OpenIDConnectDiscovery.discover()::Invalid parameters.", e); throw OAuthProblemException.OAuthError.NOT_FOUND.handle(null, "OpenIDConnectDiscovery.discover()::Invalid parameters."); } if (id == null){ OAuth2Utils.DEBUG.error("OpenIDConnectDiscovery.discover()::Invalid parameters."); throw OAuthProblemException.OAuthError.NOT_FOUND.handle(null, "OpenIDConnectDiscovery.discover()::Invalid parameters."); } } Map<String, Object> response = new HashMap<String, Object>(); response.put("subject", resource); Set<Object> set = new HashSet<Object>(); Map<String, Object> objectMap = new HashMap<String, Object>(); objectMap.put("rel", rel); objectMap.put("href", OAuth2Utils.getDeploymentURL(getRequest())); set.add(objectMap); response.put("links",set); return new JsonRepresentation(response); } @Get Representation discovery(); }
|
@Test public void testGetServerUsingEmailAddress() { AMIdentity id = PowerMockito.mock(AMIdentity.class); PowerMockito.mockStatic(OAuth2Utils.class); when(OAuth2Utils.getRequestParameter(any(Request.class), eq("resource"), any(Class.class))) .thenReturn("acct:[email protected]"); when(OAuth2Utils.getRequestParameter(any(Request.class), eq("rel"), any(Class.class))) .thenReturn("http: when(OAuth2Utils.getIdentity(any(String.class), any(String.class))).thenReturn(id); when(OAuth2Utils.getRealm(any(Request.class))).thenReturn("/"); when(OAuth2Utils.getDeploymentURL(any(Request.class))) .thenReturn("http: OpenIDConnectDiscovery test = new OpenIDConnectDiscovery(); Representation r = test.discovery(); Map<String, Object> response = new HashMap<String, Object>(); response.put("subject", "acct:[email protected]"); Set<Object> set = new HashSet<Object>(); Map<String, Object> objectMap = new HashMap<String, Object>(); objectMap.put("rel", "http: objectMap.put("href", "http: set.add(objectMap); response.put("links",set); JsonRepresentation expected = new JsonRepresentation(response); assert(r.equals(expected)); }
@Test public void testGetServerUsingURL() { AMIdentity id = PowerMockito.mock(AMIdentity.class); PowerMockito.mockStatic(OAuth2Utils.class); when(OAuth2Utils.getRequestParameter(any(Request.class), eq("resource"), any(Class.class))) .thenReturn("http: when(OAuth2Utils.getRequestParameter(any(Request.class), eq("rel"), any(Class.class))) .thenReturn("http: when(OAuth2Utils.getIdentity(any(String.class), any(String.class))).thenReturn(id); when(OAuth2Utils.getRealm(any(Request.class))).thenReturn("/"); when(OAuth2Utils.getDeploymentURL(any(Request.class))) .thenReturn("http: OpenIDConnectDiscovery test = new OpenIDConnectDiscovery(); Representation r = test.discovery(); Map<String, Object> response = new HashMap<String, Object>(); response.put("subject", "http: Set<Object> set = new HashSet<Object>(); Map<String, Object> objectMap = new HashMap<String, Object>(); objectMap.put("rel", "http: objectMap.put("href", "http: set.add(objectMap); response.put("links",set); JsonRepresentation expected = new JsonRepresentation(response); assert(r.equals(expected)); }
|
RefreshTokenServerResource extends AbstractFlow { private CoreToken createRefreshToken(CoreToken refreshToken) { return getTokenStore().createRefreshToken(refreshToken.getScope(), OAuth2Utils.getRealm(getRequest()), refreshToken.getUserID(), refreshToken.getClientID(), refreshToken.getRedirectURI(), refreshToken.getGrantType()); } @Post("form:json") Representation represent(Representation entity); }
|
@Test public void testValidRequest() throws Exception { Reference reference = new Reference("riap: Request request = new Request(Method.POST, reference); Response response = new Response(request); CoreToken refreshToken = realm.getTokenStore().createRefreshToken(OAuth2Utils.split("read write", null), "test", "admin", "cid", null, OAuth2Constants.Params.REFRESH_TOKEN); Form parameters = new Form(); parameters.add(OAuth2Constants.Params.GRANT_TYPE, OAuth2Constants.Params.REFRESH_TOKEN); parameters.add(OAuth2Constants.Params.REFRESH_TOKEN, refreshToken.getTokenID()); parameters.add(OAuth2Constants.Params.SCOPE, OAuth2Utils.join(refreshToken.getScope(), "")); parameters.add(OAuth2Constants.Params.STATE, "random"); request.setEntity(parameters.getWebRepresentation()); getClient().handle(request, response); assertTrue(MediaType.APPLICATION_JSON.equals(response.getEntity().getMediaType())); JacksonRepresentation<Map> representation = new JacksonRepresentation<Map>(response.getEntity(), Map.class); assertThat(representation.getObject()).includes( MapAssert.entry(OAuth2Constants.Params.TOKEN_TYPE, OAuth2Constants.Bearer.BEARER), MapAssert.entry(OAuth2Constants.Params.EXPIRES_IN, 3600)).is(new Condition<Map<?, ?>>() { @Override public boolean matches(Map<?, ?> value) { return value.containsKey(OAuth2Constants.Params.ACCESS_TOKEN) && value.containsKey(OAuth2Constants.Params.REFRESH_TOKEN); } }); }
@Test public void testProxy() throws Exception { BearerOAuth2Proxy auth2Proxy = BearerOAuth2Proxy.popOAuth2Proxy(component.getContext()); assertNotNull(auth2Proxy); CoreToken refreshToken = realm.getTokenStore().createRefreshToken(OAuth2Utils.split("read write", null), "test", "admin", "cid", null, OAuth2Constants.Params.REFRESH_TOKEN); BearerToken token = auth2Proxy.flowRefreshToken(refreshToken.getTokenID()); assertNotNull(token); }
|
OpenIDPromptParameter { public boolean noPrompts() { if (isValid() && prompts.contains(PROMPT_NONE)) { return true; } return false; } OpenIDPromptParameter(String promptString); boolean noPrompts(); boolean promptLogin(); boolean promptConsent(); boolean isValid(); }
|
@Test public void testNoPrompts() { String parameterString = "none"; OpenIDPromptParameter openIDPromptParameter = new OpenIDPromptParameter(parameterString); assert openIDPromptParameter.isValid(); assert openIDPromptParameter.noPrompts(); }
|
OpenIDPromptParameter { public boolean isValid() { if (prompts.contains(PROMPT_NONE) && (prompts.contains(PROMPT_CONSENT) || prompts.contains(PROMPT_LOGIN))) { return false; } return true; } OpenIDPromptParameter(String promptString); boolean noPrompts(); boolean promptLogin(); boolean promptConsent(); boolean isValid(); }
|
@Test public void testIsValidWithTwoValidValues() { String parameterString = "consent login"; OpenIDPromptParameter openIDPromptParameter = new OpenIDPromptParameter(parameterString); assert openIDPromptParameter.isValid(); }
|
OpenAMParameters { public Reference getOpenAMServerRef() { Reference baseRef = new Reference(); baseRef.setScheme(getServerProtocol().getSchemeName()); baseRef.setHostDomain(getServerHost()); baseRef.setHostPort(getServerPort()); baseRef.setPath(getServerDeploymentURI()); return baseRef; } OpenAMParameters(); Reference getOpenAMServerRef(); Protocol getServerProtocol(); void setServerProtocol(Protocol serverProtocol); String getServerHost(); void setServerHost(String serverHost); int getServerPort(); void setServerPort(int serverPort); String getServerDeploymentURI(); void setServerDeploymentURI(String serverDeploymentURI); String getDebugDirectory(); void setDebugDirectory(String debugDirectory); String getApplicationUserName(); void setApplicationUserName(String applicationUserName); String getApplicationUserPassword(); void setApplicationUserPassword(String applicationUserPassword); String getLoginIndexName(); void setLoginIndexName(String loginIndexName); String getOrgName(); void setOrgName(String orgName); String getLocale(); void setLocale(String locale); IndexType getLoginIndexType(); void setLoginIndexType(IndexType loginIndexType); ConcurrentMap<String, Object> getAttributes(); static final String AUTHENTICATE; static final String LOGOUT; static final String ISTOKENVALID; static final String ATTRIBUTES; static final String AUTHORIZE; static final String AM_SERVER_PROTOCOL; static final String AM_SERVER_HOST; static final String AM_SERVER_PORT; static final String AM_SERVICES_DEPLOYMENT_DESCRIPTOR; static final String SERVICES_DEBUG_DIRECTORY; static final String AM_APPLICATION_USERNAME; static final String AM_APPLICATION_PASSWORD; static final String AM_SERVER_LOGINURL; static final boolean OPENAM_SDK; }
|
@Test public void testGetOpenAMServerRef() throws Exception { OpenAMParameters parameters = new OpenAMParameters(); Reference baseRef = new Reference(); baseRef.setScheme(parameters.getServerProtocol().getSchemeName()); baseRef.setHostDomain(parameters.getServerHost()); baseRef.setHostPort(parameters.getServerPort()); baseRef.setPath(parameters.getServerDeploymentURI()); Assert.assertEquals(baseRef.toString(), "http: baseRef.setPath(baseRef.getPath() + "/UI/Login"); Assert.assertEquals(baseRef.toString(), "http: }
|
RedirectUrlValidator { public boolean isRedirectUrlValid(final String url, final T configInfo) { if (url == null || url.isEmpty()) { return false; } final Collection<String> patterns = domainExtractor.extractValidDomains(configInfo); if (DEBUG.messageEnabled()) { DEBUG.message("Validating goto URL " + url + " against patterns:\n" + patterns); } if (url.length() > MAX_URL_LENGTH) { return false; } try { final URI uri = new URI(url); if (!uri.isAbsolute() && !url.startsWith(" return true; } if (uri.getScheme() != null && !uri.getScheme().equals("http") && !uri.getScheme().equals("https")) { return false; } } catch (final URISyntaxException urise) { if (DEBUG.messageEnabled()) { DEBUG.message("The goto URL " + url + " is not a valid URI", urise); } return false; } if (patterns == null || patterns.isEmpty()) { if (DEBUG.messageEnabled()) { DEBUG.message("There are no patterns to validate the URL against, the goto URL is considered valid"); } return true; } final URLPatternMatcher patternMatcher = new URLPatternMatcher(); try { return patternMatcher.match(url, patterns, true); } catch (MalformedURLException murle) { DEBUG.error("An error occurred while validating goto URL: " + url, murle); return false; } } RedirectUrlValidator(final ValidDomainExtractor<T> domainExtractor); boolean isRedirectUrlValid(final String url, final T configInfo); final static String GOTO; final static String GOTO_ON_FAIL; }
|
@Test(dataProvider = "wildcardInProto") public void testWildcardInProtocol(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http*: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "wildcardInHost") public void testWildcardInHost(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "wildcardInPort") public void testWildcardInPort(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "wildcardInPath") public void testWildcardInPath(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "wildcardInQuery") public void testWildcardInQuery(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "schemeRelative") public void testSchemeRelativeUrls(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "relative") public void testRelativeUrlsWithWhitelist(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "relative") public void testRelativeUrlsWithoutWhitelist(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(null); assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "javascript") public void testJavaScriptUrlsWithWhitelist(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "javascript") public void testJavaScriptUrlsWithoutWhitelist(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(null); assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "malformed") public void testMalformedUrlsWithWhitelist(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(asSet("http: assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
@Test(dataProvider = "malformed") public void testMalformedUrlsWithoutWhitelist(String url, boolean result) { RedirectUrlValidator<String> validator = getValidator(null); assertThat(validator.isRedirectUrlValid(url, null)).isEqualTo(result); }
|
GuiceModuleCreator { public <T extends Module> T createInstance(Class<T> clazz) { try { Constructor<T> constructor = getConstructor(clazz); return constructor.newInstance(); } catch (InstantiationException e) { throw new ModuleCreationException(e); } catch (IllegalAccessException e) { throw new ModuleCreationException(e); } catch (NoSuchMethodException e) { throw new ModuleCreationException(e); } catch (InvocationTargetException e) { throw new ModuleCreationException(e); } } T createInstance(Class<T> clazz); }
|
@Test public void shouldCreateInstanceWithPublicNoArgConstructor() { Class<? extends Module> moduleClass = TestModule2.class; Object module = guiceModuleCreator.createInstance(moduleClass); assertNotNull(module); }
@Test (expectedExceptions = ModuleCreationException.class) public void shouldFailToCreateInstanceWithPrivateNoArgConstructor() { Class<? extends Module> moduleClass = TestModule1.class; guiceModuleCreator.createInstance(moduleClass); fail(); }
@Test (expectedExceptions = ModuleCreationException.class) public void shouldFailToCreateInstanceWithPublicArgsConstructor() { Class<? extends Module> moduleClass = TestModule3.class; guiceModuleCreator.createInstance(moduleClass); fail(); }
|
InjectorFactory { public synchronized Injector createInjector(Class<? extends Annotation> moduleAnnotation) { return injectorCreator.createInjector(createModules(moduleAnnotation)); } InjectorFactory(GuiceConfiguration guiceConfiguration, GuiceModuleCreator moduleCreator,
GuiceInjectorCreator injectorCreator); synchronized Injector createInjector(Class<? extends Annotation> moduleAnnotation); }
|
@Test public void shouldCreateInjector() { Class<AMGuiceModule> moduleAnnotation = AMGuiceModule.class; Set<Class<?>> modules = new HashSet<Class<?>>(asList(TestModule1.class, TestModule2.class)); given(guiceConfiguration.getGuiceModuleClasses(moduleAnnotation)).willReturn(modules); TestModule1 testModule1 = mock(TestModule1.class); given(moduleCreator.createInstance(TestModule1.class)).willReturn(testModule1); TestModule2 testModule2 = mock(TestModule2.class); given(moduleCreator.createInstance(TestModule2.class)).willReturn(testModule2); Injector mockInjector = mock(Injector.class); given(injectorCreator.createInjector(Matchers.<Iterable<? extends Module>>anyObject())) .willReturn(mockInjector); Injector injector = injectorFactory.createInjector(moduleAnnotation); assertEquals(injector, mockInjector); }
@Test (expectedExceptions = IllegalArgumentException.class) public void shouldFailToCreateInjectorIfModuleDoesNotImplementInterface() { Class<AMGuiceModule> moduleAnnotation = AMGuiceModule.class; Set<Class<?>> modules = new HashSet<Class<?>>(asList(TestModule1.class, BadModule.class, TestModule2.class)); given(guiceConfiguration.getGuiceModuleClasses(moduleAnnotation)).willReturn(modules); injectorFactory.createInjector(moduleAnnotation); fail(); }
|
JsonValueBuilder { public static JsonObject jsonValue() { return new JsonObject(); } static JsonObject jsonValue(); static JsonValue toJsonValue(String json); static ObjectMapper getObjectMapper(); }
|
@Test public void shouldCreateJsonValue() { List<String> list = new ArrayList<String>(); list.add("LIST_VALUE_1"); list.add("LIST_VALUE_2"); list.add("LIST_VALUE_3"); Map<String, String> map = new LinkedHashMap<String, String>(); map.put("MAP_KEY_1", "MAP_VALUE_1"); map.put("MAP_KEY_2", "MAP_VALUE_2"); map.put("MAP_KEY_3", "MAP_VALUE_3"); Map<String, String> mapParam = new LinkedHashMap<String, String>(); mapParam.put("MAP_PARAM_KEY_1", "MAP_PARAM_VALUE_1"); mapParam.put("MAP_PARAM_KEY_2", "MAP_PARAM_VALUE_2"); JsonValue jsonValueParam1 = new JsonValue(mapParam); List<String> listParam = new ArrayList<String>(); listParam.add("LIST_PARAM_VALUE_1"); listParam.add("LIST_PARAM_VALUE_2"); JsonValue jsonValueParam2 = new JsonValue(listParam); JsonValue jsonValue = JsonValueBuilder.jsonValue() .put("KEY1", 1) .put("KEY2", 4L) .put("KEY3", 34.56) .put("KEY4", list) .put("KEY5", map) .put("KEY6", "VALUE") .put("KEY7", jsonValueParam1) .put("KEY8", jsonValueParam2) .array("KEY9") .add("KEY9_VALUE_1") .addLast("KEY9_VALUE_2") .build(); JsonValue expectedJsonValue = getExpectedJsonValue(); assertEquals(jsonValue.toString(), expectedJsonValue.toString()); }
|
JsonValueBuilder { public static JsonValue toJsonValue(String json) throws JsonException { try { return new JsonValue(mapper.readValue(json, Map.class)); } catch (IOException e) { throw new JsonException("Failed to parse json", e); } } static JsonObject jsonValue(); static JsonValue toJsonValue(String json); static ObjectMapper getObjectMapper(); }
|
@Test public void shouldConvertJsonStringToJsonValue() throws IOException { JsonValue expectedJsonValue = getExpectedJsonValue(); JsonValue jsonValue = JsonValueBuilder.toJsonValue(expectedJsonValue.toString()); assertEquals(jsonValue.toString(), expectedJsonValue.toString()); }
|
AMKeyProvider implements KeyProvider { public java.security.PublicKey getPublicKey (String keyAlias) { if (keyAlias == null || keyAlias.length() == 0) { return null; } java.security.PublicKey pkey = null; try { X509Certificate cert = (X509Certificate) ks.getCertificate(keyAlias); pkey = cert.getPublicKey(); } catch (KeyStoreException e) { logger.error("Unable to get public key:" + keyAlias, e); } return pkey; } AMKeyProvider(); AMKeyProvider(
String keyStoreFilePropName,String keyStorePassFilePropName,
String keyStoreTypePropName, String privateKeyPassFilePropName); AMKeyProvider( boolean alreadyResolved,
String keyStoreFile,String keyStorePass,
String keyStoreType, String privateKeyPass); static String decodePassword(String password); void setLogger(Debug logger); void setKey(String storepass, String keypass); java.security.cert.X509Certificate getX509Certificate(
String certAlias); java.security.PublicKey getPublicKey(String keyAlias); java.security.PrivateKey getPrivateKey(String certAlias); PrivateKey getPrivateKey(String certAlias, String encryptedKeyPass); String getCertificateAlias(Certificate cert); char[] getKeystorePass(); String getPrivateKeyPass(); String getKeystoreType(); String getKeystoreFilePath(); KeyStore getKeyStore(); void setCertificateEntry(String certAlias, Certificate cert); Certificate getCertificate(String certAlias); void store(); Certificate getCertificate(
java.security.PublicKey publicKey); }
|
@Test public void getDefaultPublicKey() { PublicKey key = amKeyProvider.getPublicKey(DEFAULT_PRIVATE_KEY_ALIAS); Assert.assertNotNull(key); }
@Test public void getPublicKey() { PublicKey key = amKeyProvider.getPublicKey(PRIVATE_KEY_ALIAS); Assert.assertNotNull(key); }
|
AMKeyProvider implements KeyProvider { public java.security.cert.X509Certificate getX509Certificate ( String certAlias) { if (certAlias == null || certAlias.length() == 0) { return null; } java.security.cert.X509Certificate cert = null; try { cert = (X509Certificate) ks.getCertificate(certAlias); } catch (KeyStoreException e) { logger.error("Unable to get cert alias:" + certAlias, e); } return cert; } AMKeyProvider(); AMKeyProvider(
String keyStoreFilePropName,String keyStorePassFilePropName,
String keyStoreTypePropName, String privateKeyPassFilePropName); AMKeyProvider( boolean alreadyResolved,
String keyStoreFile,String keyStorePass,
String keyStoreType, String privateKeyPass); static String decodePassword(String password); void setLogger(Debug logger); void setKey(String storepass, String keypass); java.security.cert.X509Certificate getX509Certificate(
String certAlias); java.security.PublicKey getPublicKey(String keyAlias); java.security.PrivateKey getPrivateKey(String certAlias); PrivateKey getPrivateKey(String certAlias, String encryptedKeyPass); String getCertificateAlias(Certificate cert); char[] getKeystorePass(); String getPrivateKeyPass(); String getKeystoreType(); String getKeystoreFilePath(); KeyStore getKeyStore(); void setCertificateEntry(String certAlias, Certificate cert); Certificate getCertificate(String certAlias); void store(); Certificate getCertificate(
java.security.PublicKey publicKey); }
|
@Test public void getDefaultX509Certificate() { X509Certificate certificate = amKeyProvider.getX509Certificate(DEFAULT_PRIVATE_KEY_ALIAS); Assert.assertNotNull(certificate); }
@Test public void getX509Certificate() { X509Certificate certificate = amKeyProvider.getX509Certificate(PRIVATE_KEY_ALIAS); Assert.assertNotNull(certificate); }
|
AMKeyProvider implements KeyProvider { public java.security.PrivateKey getPrivateKey (String certAlias) { java.security.PrivateKey key = null; try { key = (PrivateKey) ks.getKey(certAlias, privateKeyPass.toCharArray()); } catch (KeyStoreException e) { logger.error(e.getMessage()); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage()); } catch (UnrecoverableKeyException e) { logger.error(e.getMessage()); } return key; } AMKeyProvider(); AMKeyProvider(
String keyStoreFilePropName,String keyStorePassFilePropName,
String keyStoreTypePropName, String privateKeyPassFilePropName); AMKeyProvider( boolean alreadyResolved,
String keyStoreFile,String keyStorePass,
String keyStoreType, String privateKeyPass); static String decodePassword(String password); void setLogger(Debug logger); void setKey(String storepass, String keypass); java.security.cert.X509Certificate getX509Certificate(
String certAlias); java.security.PublicKey getPublicKey(String keyAlias); java.security.PrivateKey getPrivateKey(String certAlias); PrivateKey getPrivateKey(String certAlias, String encryptedKeyPass); String getCertificateAlias(Certificate cert); char[] getKeystorePass(); String getPrivateKeyPass(); String getKeystoreType(); String getKeystoreFilePath(); KeyStore getKeyStore(); void setCertificateEntry(String certAlias, Certificate cert); Certificate getCertificate(String certAlias); void store(); Certificate getCertificate(
java.security.PublicKey publicKey); }
|
@Test public void getDefaultPrivateKeyUsingDefaultPassword() { PrivateKey key = amKeyProvider.getPrivateKey(DEFAULT_PRIVATE_KEY_ALIAS); Assert.assertNotNull(key); }
@Test public void getPrivateKeyUsingProvidedPassword() { String encodedPrivatePass = AccessController.doPrivileged(new EncodeAction(PRIVATE_KEY_PASS)); PrivateKey key = amKeyProvider.getPrivateKey(PRIVATE_KEY_ALIAS, encodedPrivatePass); Assert.assertNotNull(key); }
@Test public void getPrivateKeyUsingNullPassword() { PrivateKey key = amKeyProvider.getPrivateKey(PRIVATE_KEY_ALIAS, null); Assert.assertNull(key); }
@Test public void getPrivateKeyUsingDefaultPassword() { PrivateKey key = amKeyProvider.getPrivateKey(PRIVATE_KEY_ALIAS); Assert.assertNull(key); }
|
XMLUtils { public static String removeInvalidXMLChars(String text) { if (text == null || text.isEmpty()) { return text; } return text.replaceAll(INVALID_XML_CHARACTERS, ""); } String getATTR_VALUE_PAIR_NODE(); static Document toDOMDocument(String xmlString, Debug debug); static Document toDOMDocument(InputStream is, Debug debug); static Set parseAttributesTag(Node n); static Map<String, Set<String>> parseAttributeValuePairTags(Node parentNode); static Document newDocument(); static Document getXMLDocument(InputStream in); static Node getRootNode(Document doc, String nodeName); static Node getChildNode(Node parentNode, String childName); static boolean hasElementChild(Node node); static Node getNamedChildNode(Node parentNode, String childNodeName,
String attrName, String attrValue); static Set getChildNodes(Node parentNode, String childName); static String getElementValue(Element element); static String getChildrenValue(Element element); static String getElementString(Element element); static String getNodeAttributeValue(Node node, String attrName); static String getNodeAttributeValueNS(Node node,
String namespaceURI, String attrName); static Set getAttributeValuePair(Node node); static Set getAttributeValuePair(Node node, boolean unescape); static String getValueOfValueNode(Node n); static String getValueOfValueNode(Node n, boolean unescape); static String getValueOfValueNodeNoTrim(Node n); static String getValueOfValueNodeNoTrim(Node n, boolean unescape); static List getElementsByTagNameNS1(
Element element,
String nsName,
String tagName
); static String printAttributeValue(Element node, String prefix); static String print(Node node); static String print(Node node, String encoding); static String unescapeSpecialCharacters(String text); static String escapeSpecialCharacters(String text); static String removeInvalidXMLChars(String text); static Set encodeAttributeSet(Set set, Debug debug); static Set decodeAttributeSet(Set set); static String removeNullCharAtEnd(String st); static DocumentBuilder getSafeDocumentBuilder(boolean validating); static SAXParser getSafeSAXParser(boolean validating); static TransformerFactory getTransformerFactory(); static SAXSource createSAXSource(InputSource source); }
|
@Test(dataProvider = "invalid") public void invalidCharactersAreCorrectlyRemoved(String invalid) { assertThat(XMLUtils.removeInvalidXMLChars(invalid)).isEqualTo("helloworld"); }
|
XMLUtils { public static String escapeSpecialCharacters(String text) { text = removeInvalidXMLChars(text); if (text == null || text.isEmpty()) { return text; } final StringBuilder sb = new StringBuilder(text.length()); for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); switch (c) { case '&': sb.append("&"); break; case '<': sb.append("<"); break; case '>': sb.append(">"); break; case '\"': sb.append("""); break; case '\'': sb.append("'"); break; case '\n': sb.append("
"); break; case '\r': sb.append("
"); break; default: sb.append(c); } } return sb.toString(); } String getATTR_VALUE_PAIR_NODE(); static Document toDOMDocument(String xmlString, Debug debug); static Document toDOMDocument(InputStream is, Debug debug); static Set parseAttributesTag(Node n); static Map<String, Set<String>> parseAttributeValuePairTags(Node parentNode); static Document newDocument(); static Document getXMLDocument(InputStream in); static Node getRootNode(Document doc, String nodeName); static Node getChildNode(Node parentNode, String childName); static boolean hasElementChild(Node node); static Node getNamedChildNode(Node parentNode, String childNodeName,
String attrName, String attrValue); static Set getChildNodes(Node parentNode, String childName); static String getElementValue(Element element); static String getChildrenValue(Element element); static String getElementString(Element element); static String getNodeAttributeValue(Node node, String attrName); static String getNodeAttributeValueNS(Node node,
String namespaceURI, String attrName); static Set getAttributeValuePair(Node node); static Set getAttributeValuePair(Node node, boolean unescape); static String getValueOfValueNode(Node n); static String getValueOfValueNode(Node n, boolean unescape); static String getValueOfValueNodeNoTrim(Node n); static String getValueOfValueNodeNoTrim(Node n, boolean unescape); static List getElementsByTagNameNS1(
Element element,
String nsName,
String tagName
); static String printAttributeValue(Element node, String prefix); static String print(Node node); static String print(Node node, String encoding); static String unescapeSpecialCharacters(String text); static String escapeSpecialCharacters(String text); static String removeInvalidXMLChars(String text); static Set encodeAttributeSet(Set set, Debug debug); static Set decodeAttributeSet(Set set); static String removeNullCharAtEnd(String st); static DocumentBuilder getSafeDocumentBuilder(boolean validating); static SAXParser getSafeSAXParser(boolean validating); static TransformerFactory getTransformerFactory(); static SAXSource createSAXSource(InputSource source); }
|
@Test(dataProvider = "escaping") public void specialCharactersAreCorrectlyEscaped(String content, String escaped) { assertThat(XMLUtils.escapeSpecialCharacters(content)).isEqualTo(escaped); }
|
Debug { public void resetDebug(String mf) { getDebugServiceInstance().resetDebug(mf); } private Debug(IDebug debugServiceInstance); static synchronized Debug getInstance(String debugName); static Collection getInstances(); String getName(); boolean messageEnabled(); boolean warningEnabled(); boolean errorEnabled(); int getState(); void message(String msg); void message(String msg, Throwable t); void warning(String msg); void warning(String msg, Throwable t); void error(String msg); void error(String msg, Throwable t); void setDebug(int debugType); void resetDebug(String mf); void setDebug(String debugType); void destroy(); static final int OFF; static final int ERROR; static final int WARNING; static final int MESSAGE; static final int ON; static final String STR_OFF; static final String STR_ERROR; static final String STR_WARNING; static final String STR_MESSAGE; static final String STR_ON; }
|
@Test public void resetDebug() throws Exception { initializeProvider(DEBUG_CONFIG_FOR_TEST); IDebug debug = provider.getInstance(logName); debug.message("Should appear in log", null); checkLogFileStatus(false, DebugConstants.CONFIG_DEBUG_MERGEALL_FILE); checkLogFileStatus(true, logName); SystemPropertiesManager.initializeProperties(DebugConstants.CONFIG_DEBUG_LEVEL, DebugLevel.ERROR.getName()); debug.resetDebug(MERGE_ALL_ON); debug.error("Should appear in log", null); Assert.assertEquals(debug.getState(), DebugLevel.ERROR.getLevel(), "Debug level state"); checkLogFileStatus(true, DebugConstants.CONFIG_DEBUG_MERGEALL_FILE); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.