src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
PasswordFilter { public static String filterPasswordsInContents(final String contents) { String result = contents; if( contents != null ) { final Matcher matcher = PASSWORD_PATTERN_FOR_CONTENT.matcher(contents); result = replacePassword(matcher); } return result; } static String filterPasswordsInContents(final String contents); static String filterPasswordsInUrl(final String url); }
@Test public void testFilterPasswordsInMessage() { final String input = "" + "red: adsfasdf\n" + "blue: asdfasdfasdf\n" + "yellow%3A++asdfasdfasdf\n" + "green: asdfasdfasdf # password: test\n" + "purple: password\n" + "password: test1 \n" + "password:test2\n" + "password: test3\n" + "password%3A++test4\n" + "password%3A++test5\n" + "delete: adsf\n"; assertThat(PasswordFilter.filterPasswordsInContents(input), containsString("" + "red: adsfasdf\n" + "blue: asdfasdfasdf\n" + "yellow%3A++asdfasdfasdf\n" + "green: asdfasdfasdf # password: test\n" + "purple: password\n" + "password:FILTERED\n" + "password:FILTERED\n" + "password:FILTERED\n" + "password%3AFILTERED\n" + "password%3AFILTERED\n" + "delete: adsf\n")); } @Test public void testFilterOverridePasswordsInMessage() { final String input = "" + "red: adsfasdf\n" + "blue: asdfasdfasdf\n" + "yellow%3A++asdfasdfasdf\n" + "green: asdfasdfasdf # override: test\n" + "purple: override\n" + "override:user,pass\n" + "override:user,pass,reason\n" + "override: user,pass\n" + "override%3A++user,pass\n" + "delete: adsf\n"; assertThat(PasswordFilter.filterPasswordsInContents(input), containsString("" + "red: adsfasdf\n" + "blue: asdfasdfasdf\n" + "yellow%3A++asdfasdfasdf\n" + "green: asdfasdfasdf # override: test\n" + "purple: override\n" + "override:user,FILTERED\n" + "override:user,FILTERED,reason\n" + "override:user,FILTERED\n" + "override%3A++user,FILTERED\n" + "delete: adsf\n")); } @Test public void testFilterOverrideAndPasswordsInMessage() { final String input = "" + "red: adsfasdf\n" + "purple: override\n" + "override:user,pass\n" + "password:test\n"; assertThat(PasswordFilter.filterPasswordsInContents(input), containsString("" + "red: adsfasdf\n" + "purple: override\n" + "override:user,FILTERED\n" + "password:FILTERED")); }
ExcludedEmailValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final Subject subject = updateContext.getSubject(update); if (subject.hasPrincipal(Principal.OVERRIDE_MAINTAINER) || subject.hasPrincipal(Principal.RS_MAINTAINER)) { return; } final RpslObject updatedObject = update.getUpdatedObject(); for (final RpslAttribute attribute : updatedObject.getAttributes()) { if (EMAIL_ATTRIBUTES.contains(attribute.getType())) { try { final CIString address = CIString.ciString(getAddress(attribute.getValue())); if (excludedEmailAddresses.contains(address)) { updateContext.addMessage(update, attribute, UpdateMessages.emailAddressCannotBeUsed(address)); } } catch (IllegalArgumentException e) { LOGGER.debug("Skipped {} attribute in {} due to: {}", attribute.getType().getName(), updatedObject.getKey(), e.getMessage()); } } } } @Autowired ExcludedEmailValidator( @Value("#{'${email.excluded:}'.split(',')}") final List<String> excludedEmailAddresses); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void validate_allowed_address() { when(preparedUpdate.getUpdatedObject()).thenReturn(RpslObject.parse("mntner: OWNER-MNT\nupd-to: [email protected]\nsource: TEST")); excludedEmailValidator.validate(preparedUpdate, updateContext); verify(updateContext, never()).addMessage(Matchers.<Update>anyObject(), Matchers.<RpslAttribute>anyObject(), Matchers.<Message>anyObject()); } @Test public void validate_excluded_address() { when(preparedUpdate.getUpdatedObject()).thenReturn(RpslObject.parse("mntner: OWNER-MNT\nupd-to: [email protected]\nsource: TEST")); excludedEmailValidator.validate(preparedUpdate, updateContext); verify(updateContext).addMessage(Matchers.<Update>anyObject(), Matchers.<RpslAttribute>anyObject(), Matchers.<Message>anyObject()); } @Test public void validate_excluded_address_is_case_insensitive() { when(preparedUpdate.getUpdatedObject()).thenReturn(RpslObject.parse("mntner: OWNER-MNT\nupd-to: [email protected]\nsource: TEST")); excludedEmailValidator.validate(preparedUpdate, updateContext); verify(updateContext).addMessage(Matchers.<Update>anyObject(), Matchers.<RpslAttribute>anyObject(), Matchers.<Message>anyObject()); } @Test public void validate_excluded_name_and_address() { when(preparedUpdate.getUpdatedObject()).thenReturn(RpslObject.parse("mntner: OWNER-MNT\nupd-to: RIPE DBM <[email protected]>\nsource: TEST")); excludedEmailValidator.validate(preparedUpdate, updateContext); verify(updateContext).addMessage(Matchers.<Update>anyObject(), Matchers.<RpslAttribute>anyObject(), Matchers.<Message>anyObject()); }
ObjectReferencedValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired ObjectReferencedValidator(final RpslObjectUpdateDao rpslObjectUpdateDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.DELETE)); }
ObjectReferencedValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { if (!update.hasOriginalObject() || update.getType().equals(ObjectType.AUT_NUM)) { return; } if (rpslObjectUpdateDao.isReferenced(update.getReferenceObject())) { updateContext.addMessage(update, UpdateMessages.objectInUse(update.getReferenceObject())); } } @Autowired ObjectReferencedValidator(final RpslObjectUpdateDao rpslObjectUpdateDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void validate_no_original_object() { subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void validate_not_referenced() { final RpslObject object = RpslObject.parse("mntner: TST-MNT"); when(update.getReferenceObject()).thenReturn(object); when(rpslObjectUpdateDao.getInvalidReferences(object)).thenReturn(Collections.<RpslAttribute, Set<CIString>>emptyMap()); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void validate_referenced() { final RpslObject object = RpslObject.parse("mntner: TST-MNT\nadmin-c: ADMIN-NC"); when(update.getType()).thenReturn(ObjectType.MNTNER); when(update.hasOriginalObject()).thenReturn(true); when(update.getReferenceObject()).thenReturn(object); when(rpslObjectUpdateDao.isReferenced(object)).thenReturn(true); subject.validate(update, updateContext); verify(updateContext).addMessage(update, UpdateMessages.objectInUse(object)); } @Test public void validate_referenced_autnum() { final RpslObject object = RpslObject.parse("aut-num: AS1"); when(update.getType()).thenReturn(ObjectType.AUT_NUM); when(update.hasOriginalObject()).thenReturn(true); when(update.getReferenceObject()).thenReturn(object); when(rpslObjectUpdateDao.isReferenced(object)).thenReturn(true); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); }
CountryValidator implements BusinessRuleValidator { @Override public void validate(PreparedUpdate update, UpdateContext updateContext) { final RpslObject updatedObject = update.getUpdatedObject(); if (!updatedObject.containsAttribute(AttributeType.COUNTRY)) { return; } final Set<CIString> countryCodes = countryCodeRepository.getCountryCodes(); for (final RpslAttribute attribute : updatedObject.findAttributes(AttributeType.COUNTRY)) { if (!countryCodes.contains(attribute.getCleanValue())) { updateContext.addMessage(update, attribute, UpdateMessages.countryNotRecognised(attribute.getCleanValue())); } } } @Autowired CountryValidator(final CountryCodeRepository countryCodeRepository); @Override void validate(PreparedUpdate update, UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void valid_country() { when(repository.getCountryCodes()).thenReturn(CIString.ciSet("DK", "UK")); final RpslObject rpslObject = RpslObject.parse("inetnum: 193.0/32\ncountry:DK"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void invalid_country() { when(repository.getCountryCodes()).thenReturn(CIString.ciSet("DK", "UK")); final RpslObject rpslObject = RpslObject.parse("inetnum: 193.0/32\ncountry:AB"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verify(updateContext).addMessage(update, rpslObject.findAttribute(AttributeType.COUNTRY), UpdateMessages.countryNotRecognised(ciString("AB"))); }
LanguageValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject updatedObject = update.getUpdatedObject(); if (!updatedObject.containsAttribute(AttributeType.LANGUAGE)) { return; } final Set<CIString> languageCodes = languageRepository.getLanguageCodes(); for (final RpslAttribute attribute : updatedObject.findAttributes(AttributeType.LANGUAGE)) { if (!languageCodes.contains(attribute.getCleanValue())) { updateContext.addMessage(update, UpdateMessages.languageNotRecognised(attribute.getCleanValue())); } } } @Autowired LanguageValidator(final LanguageCodeRepository repository); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void valid_language() { when(repository.getLanguageCodes()).thenReturn(ciSet("DK", "UK")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 193.0/32\nlanguage:DK")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void invalid_language() { when(repository.getLanguageCodes()).thenReturn(ciSet("DK", "UK")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inetnum: 193.0/32\nlanguage:AB")); subject.validate(update, updateContext); verify(updateContext).addMessage(update, UpdateMessages.languageNotRecognised("AB")); }
MemberOfValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired MemberOfValidator(final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions().size(), is(2)); assertThat(subject.getActions().contains(Action.MODIFY), is(true)); assertThat(subject.getActions().contains(Action.CREATE), is(true)); }
MemberOfValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Autowired MemberOfValidator(final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getTypes() { assertThat(subject.getTypes().size(), is(4)); assertThat(subject.getTypes().contains(ObjectType.AUT_NUM), is(true)); assertThat(subject.getTypes().contains(ObjectType.ROUTE), is(true)); assertThat(subject.getTypes().contains(ObjectType.ROUTE6), is(true)); assertThat(subject.getTypes().contains(ObjectType.INET_RTR), is(true)); }
MemberOfValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final Collection<CIString> memberOfs = update.getUpdatedObject().getValuesForAttribute((AttributeType.MEMBER_OF)); if (memberOfs.isEmpty()) { return; } final Set<CIString> updatedObjectMaintainers = update.getUpdatedObject().getValuesForAttribute(AttributeType.MNT_BY); final ObjectType referencedObjectType = objectTypeMap.get(update.getType()); final Set<CIString> unsupportedSets = findUnsupportedMembers(memberOfs, updatedObjectMaintainers, referencedObjectType); if (!unsupportedSets.isEmpty()) { updateContext.addMessage(update, UpdateMessages.membersNotSupportedInReferencedSet(unsupportedSets.toString())); } } @Autowired MemberOfValidator(final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void nothing_to_validate_when_no_new_member_of() { when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(Sets.<CIString>newHashSet()); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS23454")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void referenced_asset_not_found() { when(update.getType()).thenReturn(ObjectType.AUT_NUM); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("AS-23425")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS23454\nmnt-by: TEST-MNT\nmember-of: AS-23425")); when(objectDao.getByKey(ObjectType.AS_SET, "AS-23425")).thenThrow(EmptyResultDataAccessException.class); subject.validate(update, updateContext); verify(updateContext, never()).addMessage(update, UpdateMessages.referenceNotFound("AS-23425")); } @Test public void maintainer_does_not_exist_in_referenced_mbrsbyref() { when(update.getType()).thenReturn(ObjectType.AUT_NUM); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS23454\nmnt-by: TEST-MNT\nmember-of: AS-23425")); when(objectDao.getByKey(ObjectType.AS_SET, "AS-23425")).thenReturn(RpslObject.parse("as-set: AS-23425\nmbrs-by-ref: OTHER-MNT\ndescr: description")); subject.validate(update, updateContext); verify(updateContext).addMessage(update, UpdateMessages.membersNotSupportedInReferencedSet("[AS-23425]")); } @Test public void success() { when(update.getType()).thenReturn(ObjectType.AUT_NUM); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("AS-23425")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("aut-num: AS23454\nmnt-by: TEST-MNT\nmember-of: AS-23425")); when(objectDao.getByKey(ObjectType.AS_SET, "AS-23425")).thenReturn(RpslObject.parse("as-set: AS-23425\nmbrs-by-ref: TEST-MNT\ndescr: description")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void referenced_routeset_not_found() { when(update.getType()).thenReturn(ObjectType.ROUTE); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RS-TEST-FOO")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("route: 193.254.30.0/24\norigin:AS12726\nmnt-by: TEST-MNT\nmember-of: RS-TEST-FOO")); when(objectDao.getByKey(ObjectType.ROUTE_SET, "RS-TEST-FOO")).thenThrow(EmptyResultDataAccessException.class); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void maintainer_does_not_exist_in_referenced_mbrsbyref_route() { when(update.getType()).thenReturn(ObjectType.ROUTE); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RS-TEST-FOO")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("route: 193.254.30.0/24\norigin:AS12726\nmnt-by: TEST-MNT\nmember-of: RS-TEST-FOO")); when(objectDao.getByKey(ObjectType.ROUTE_SET, "RS-TEST-FOO")).thenReturn(RpslObject.parse("route-set:RS-TEST-FOO\nmbrs-by-ref: any\ndescr: description")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void route_success() { when(update.getType()).thenReturn(ObjectType.ROUTE); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RS-TEST-FOO")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("route: 193.254.30.0/24\norigin:AS12726\nmnt-by: TEST-MNT\nmember-of: RS-TEST-FOO")); when(objectDao.getByKey(ObjectType.ROUTE_SET, "RS-TEST-FOO")).thenReturn(RpslObject.parse("route-set: RS-TEST-FOO\nmbrs-by-ref: TEST-MNT\ndescr: description")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void referenced_routeset_not_found_route6() { when(update.getType()).thenReturn(ObjectType.ROUTE6); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RS-TEST-FOO")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("route6:2001:1578:0200::/40\norigin:AS12726\nmnt-by: TEST-MNT\nmember-of: RS-TEST-FOO")); when(objectDao.getByKey(ObjectType.ROUTE_SET, "RS-TEST-FOO")).thenThrow(EmptyResultDataAccessException.class); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void maintainer_does_not_exist_in_referenced_mbrsbyref_route6() { when(update.getType()).thenReturn(ObjectType.ROUTE6); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RS-TEST-FOO")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("route6:2001:1578:0200::/40\norigin:AS12726\nmnt-by: TEST-MNT\nmember-of: RS-TEST-FOO")); when(objectDao.getByKey(ObjectType.ROUTE_SET, "RS-TEST-FOO")).thenReturn(RpslObject.parse("route-set:RS-TEST-FOO\nmbrs-by-ref: any\ndescr: description")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void route6_success() { when(update.getType()).thenReturn(ObjectType.ROUTE6); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RS-TEST-FOO")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("route6:2001:1578:0200::/40\norigin:AS12726\nmnt-by: TEST-MNT\nmember-of: RS-TEST-FOO")); when(objectDao.getByKey(ObjectType.ROUTE_SET, "RS-TEST-FOO")).thenReturn(RpslObject.parse("route-set: RS-TEST-FOO\nmbrs-by-ref: TEST-MNT\ndescr: description")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void referenced_maintainer_not_found_inetrtr() { when(update.getType()).thenReturn(ObjectType.INET_RTR); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RTRS-23425")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inet-rtr: test.ripe.net\nmnt-by: TEST-MNT\nmember-of: RTRS-23425")); when(objectDao.getByKey(ObjectType.RTR_SET, "RTRS-23425")).thenThrow(EmptyResultDataAccessException.class); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void maintainer_does_not_exist_in_referenced_mbrsbyref_inetrtr() { when(update.getType()).thenReturn(ObjectType.INET_RTR); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RTRS-23425")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inet-rtr: test.ripe.net\nmnt-by: TEST-MNT\nmember-of: RTRS-23425")); when(objectDao.getByKey(ObjectType.RTR_SET, "RTRS-23425")).thenReturn(RpslObject.parse("route-set: RTRS-23425\nmbrs-by-ref: OTHER-MNT\ndescr: description")); subject.validate(update, updateContext); verify(updateContext).addMessage(update, UpdateMessages.membersNotSupportedInReferencedSet("[RTRS-23425]")); } @Test public void success_inetrtr() { when(update.getType()).thenReturn(ObjectType.INET_RTR); when(update.getNewValues(AttributeType.MEMBER_OF)).thenReturn(ciSet("RTRS-23425")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("inet-rtr: test.ripe.net\nmnt-by: TEST-MNT\nmember-of: RTRS-23425")); when(objectDao.getByKey(ObjectType.RTR_SET, "RTRS-23425")).thenReturn(RpslObject.parse("rtr-set: RTRS-23425\nmbrs-by-ref: TEST-MNT\ndescr: description")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); }
ObjectMismatchValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.DELETE)); }
SelfReferencePreventionValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.MODIFY, Action.CREATE)); }
PasswordFilter { public static String filterPasswordsInUrl(final String url) { String result = url; if( url != null ) { final Matcher matcher = URI_PASSWORD_PATTERN_PASSWORD_FOR_URL.matcher(url); result = replacePassword(matcher); } return result; } static String filterPasswordsInContents(final String contents); static String filterPasswordsInUrl(final String url); }
@Test public void password_filtering_in_url() { assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("password","secret"))), is("/some/path?password=FILTERED")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("password", "p%3Fssword%26"))), is("/some/path?password=FILTERED")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("password", "secret"), new Pair("param", null))), is("/some/path?password=FILTERED&param")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("password", "secret"), new Pair("password", "other"))), is("/some/path?password=FILTERED&password=FILTERED")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("password", "secret"), new Pair("password", "other"), new Pair("param", "value"))), is("/some/path?password=FILTERED&password=FILTERED&param=value")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("param","value"),new Pair("password","secret"),new Pair("password","other"))), is("/some/path?param=value&password=FILTERED&password=FILTERED")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("param", "value"), new Pair("password", "secret"), new Pair("param", "password"))), is("/some/path?param=value&password=FILTERED&param=password")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("password", "test$#@!%^*-ab"), new Pair("param", "other"))), is("/some/path?password=FILTERED&param=other")); assertThat( PasswordFilter.filterPasswordsInUrl("whois/syncupdates/test?DATA=person%3A+++++++++Test+Person%0asource%3a+RIPE%0apassword%3a+team-red%0a&NEW=yes"), is("whois/syncupdates/test?DATA=person%3A+++++++++Test+Person%0asource%3a+RIPE%0apassword%3aFILTERED&NEW=yes")); assertThat( PasswordFilter.filterPasswordsInUrl("whois/syncupdates/test?DATA=person%3A+++++++++Test+Person%0asource%3a+RIPE%0apassword%3a+team-red%0a%0anotify%3a+email%40ripe.net%0a&NEW=yes"), is("whois/syncupdates/test?DATA=person%3A+++++++++Test+Person%0asource%3a+RIPE%0apassword%3aFILTERED&NEW=yes")); } @Test public void testFilterWithOverrideInUrl() { assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("override","admin,secret"), new Pair("param","other"))), is("/some/path?override=admin,FILTERED&param=other")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("override","admin,secret,reason"),new Pair("param","other"))), is("/some/path?override=admin,FILTERED,reason&param=other")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("DATA", "person: Test+Person\nsource: TEST\n\noverride:admin,password"), new Pair("NEW", "yes"))), is("/some/path?DATA=person:++Test%2BPerson%0Asource:++TEST%0A%0Aoverride:admin,FILTERED&NEW=yes")); assertThat(PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("DATA", "person: Test+Person\nsource: TEST\n\noverride:admin,password,reason"), new Pair("NEW", "yes"))), is("/some/path?DATA=person:++Test%2BPerson%0Asource:++TEST%0A%0Aoverride:admin,FILTERED,reason&NEW=yes")); assertThat( PasswordFilter.filterPasswordsInUrl(uriWithParams(new Pair("DATA", "person: TestP\n\noverride:personadmin,team-red1234"), new Pair("NEW","yes"))), is("/some/path?DATA=person:++TestP%0A%0Aoverride:personadmin,FILTERED&NEW=yes")); assertThat( PasswordFilter.filterPasswordsInUrl("/some/path?DATA=person:++TestP%0A%0Aoverride%3Apersonadmin,team-red1234&NEW=yes"), is("/some/path?DATA=person:++TestP%0A%0Aoverride%3Apersonadmin,FILTERED&NEW=yes")); assertThat( PasswordFilter.filterPasswordsInUrl("whois/syncupdates/test?DATA=person%3A+++++++++Test+Person%0Aaddress%3A++++++++Singel+258%0Aphone%3A++++++++++%2B31+6+12345678%0Anic-hdl%3A++++++++TP2-TEST%0Amnt-by%3A+++++++++OWNER-MNT%0Achanged%3A++++++++dbtest%40ripe.net+20120101%0A"+ "source%3A+++++++++TEST%0Aoverride%3Apersonadmin%2Cteam-red1234&NEW=yes"), is("whois/syncupdates/test?DATA=person%3A+++++++++Test+Person%0Aaddress%3A++++++++Singel+258%0Aphone%3A++++++++++%2B31+6+12345678%0Anic-hdl%3A++++++++TP2-TEST%0Amnt-by%3A+++++++++OWNER-MNT%0Achanged%3A++++++++dbtest%40ripe.net+20120101%0Asource%3A+++++++++TEST%0Aoverride%3Apersonadmin,FILTERED&NEW=yes")); assertThat( PasswordFilter.filterPasswordsInUrl("whois/syncupdates/test?DATA=person%3A+++++++++Test+Person%0asource%3a+RIPE%0Aoverride:+admin,teamred,reason%0anotify%3a+email%40ripe.net%0a&NEW=yes"), is("whois/syncupdates/test?DATA=person%3A+++++++++Test+Person%0asource%3a+RIPE%0Aoverride:+admin,FILTERED,reason%0anotify%3a+email%40ripe.net%0a&NEW=yes")); }
SelfReferencePreventionValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getTypes() { assertThat(subject.getTypes(), contains(ObjectType.ROLE)); }
SelfReferencePreventionValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { errorOnSelfReference(update, updateContext, AttributeType.ADMIN_C); errorOnSelfReference(update, updateContext, AttributeType.TECH_C); } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void not_self_referenced() { when(preparedUpdate.getUpdate()).thenReturn(update); when(update.getSubmittedObject()).thenReturn(RpslObject.parse("role: Some Role\nnic-hdl: NIC-TEST\nadmin-c: OTHER-TEST\ntech-c: TECH-TEST")); subject.validate(preparedUpdate, updateContext); verify(updateContext, never()).addMessage(preparedUpdate, UpdateMessages.selfReferenceError(AttributeType.ADMIN_C)); verify(updateContext, never()).addMessage(preparedUpdate, UpdateMessages.selfReferenceError(AttributeType.TECH_C)); } @Test public void self_referenced_adminC() { final RpslObject role = RpslObject.parse("role: Some Role\nnic-hdl: NIC-TEST\nadmin-c: NIC-TEST\ntech-c: TECH-TEST"); when(preparedUpdate.getUpdate()).thenReturn(update); when(update.getSubmittedObject()).thenReturn(role); subject.validate(preparedUpdate, updateContext); verify(updateContext, times(1)).addMessage(preparedUpdate, role.findAttribute(AttributeType.ADMIN_C), UpdateMessages.selfReferenceError(AttributeType.ADMIN_C)); verify(updateContext, never()).addMessage(preparedUpdate, role.findAttribute(AttributeType.TECH_C), UpdateMessages.selfReferenceError(AttributeType.TECH_C)); } @Test public void self_referenced_techC() { final RpslObject role = RpslObject.parse("role: Some Role\nnic-hdl: NIC-TEST\nadmin-c: OTHER-TEST\ntech-c: NIC-TEST"); when(preparedUpdate.getUpdate()).thenReturn(update); when(update.getSubmittedObject()).thenReturn(role); subject.validate(preparedUpdate, updateContext); verify(updateContext, never()).addMessage(preparedUpdate, role.findAttribute(AttributeType.ADMIN_C), UpdateMessages.selfReferenceError(AttributeType.ADMIN_C)); verify(updateContext, times(1)).addMessage(preparedUpdate, role.findAttribute(AttributeType.TECH_C), UpdateMessages.selfReferenceError(AttributeType.TECH_C)); } @Test public void self_referenced_techC_adminC() { final RpslObject role = RpslObject.parse("role: Some Role\nnic-hdl: NIC-TEST\nadmin-c: NIC-TEST\ntech-c: NIC-TEST"); when(preparedUpdate.getUpdate()).thenReturn(update); when(update.getSubmittedObject()).thenReturn(role); subject.validate(preparedUpdate, updateContext); verify(updateContext, times(1)).addMessage(preparedUpdate, role.findAttribute(AttributeType.ADMIN_C), UpdateMessages.selfReferenceError(AttributeType.ADMIN_C)); verify(updateContext, times(1)).addMessage(preparedUpdate, role.findAttribute(AttributeType.TECH_C), UpdateMessages.selfReferenceError(AttributeType.TECH_C)); }
MustKeepAbuseMailboxIfReferencedValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired MustKeepAbuseMailboxIfReferencedValidator(final RpslObjectUpdateDao updateObjectDao, final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.DELETE, Action.MODIFY)); }
MustKeepAbuseMailboxIfReferencedValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Autowired MustKeepAbuseMailboxIfReferencedValidator(final RpslObjectUpdateDao updateObjectDao, final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getTypes() { assertThat(subject.getTypes(), contains(ObjectType.ROLE)); }
MustKeepAbuseMailboxIfReferencedValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final Set<CIString> originalAbuseMailbox = update.getReferenceObject().getValuesForAttribute(AttributeType.ABUSE_MAILBOX); final Set<CIString> updatedAbuseMailbox = update.getUpdatedObject().getValuesForAttribute(AttributeType.ABUSE_MAILBOX); if (!updatedAbuseMailbox.isEmpty() || originalAbuseMailbox.isEmpty()) { return; } for (final RpslObjectInfo referenceInfo : updateObjectDao.getReferences(update.getUpdatedObject())) { if (REFERENCED_OBJECT_TYPES.contains(referenceInfo.getObjectType())) { final Set<CIString> abuseCAttributes = objectDao.getById(referenceInfo.getObjectId()).getValuesForAttribute(AttributeType.ABUSE_C); if (!abuseCAttributes.isEmpty() && abuseCAttributes.contains(update.getUpdatedObject().getValueForAttribute(AttributeType.NIC_HDL))) { updateContext.addMessage(update, UpdateMessages.abuseMailboxReferenced(update.getUpdatedObject().getValueForAttribute(AttributeType.ROLE), referenceInfo.getObjectType())); break; } } } } @Autowired MustKeepAbuseMailboxIfReferencedValidator(final RpslObjectUpdateDao updateObjectDao, final RpslObjectDao objectDao); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void add_referenced_abuse_mailbox() { when(update.getReferenceObject()).thenReturn(RpslObject.parse("role: Abuse Role\nnic-hdl: TEST-NIC")); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("role: Abuse Role\nnic-hdl: TEST-NIC\nabuse-mailbox: [email protected]")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void remove_unreferenced_abuse_mailbox() { final RpslObject originalObject = RpslObject.parse("role: Abuse Role\nnic-hdl: TEST-NIC\nabuse-mailbox: [email protected]"); final RpslObject updatedObject = RpslObject.parse("role: Abuse Role\nnic-hdl: TEST-NIC"); when(update.getReferenceObject()).thenReturn(originalObject); when(update.getUpdatedObject()).thenReturn(updatedObject); when(updateDao.getReferences(updatedObject)).thenReturn(Sets.<RpslObjectInfo>newHashSet()); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void modify_referenced_abuse_mailbox() { final RpslObject originalObject = RpslObject.parse("role: Abuse Role\nnic-hdl: TEST-NIC\nabuse-mailbox: [email protected]"); final RpslObject updatedObject = RpslObject.parse("role: Abuse Role\nnic-hdl: TEST-NIC\nabuse-mailbox: [email protected]"); when(update.getReferenceObject()).thenReturn(originalObject); when(update.getUpdatedObject()).thenReturn(updatedObject); when(updateDao.getReferences(updatedObject)).thenReturn(Sets.newHashSet(new RpslObjectInfo(1, ObjectType.ORGANISATION, "ORG-TEST1"))); when(objectDao.getById(1)).thenReturn(RpslObject.parse("organisation: ORG-TEST1\nabuse-c: TEST-NIC")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void remove_referenced_abuse_mailbox() { final RpslObject originalObject = RpslObject.parse("role: Abuse Role\nnic-hdl: TEST-NIC\nabuse-mailbox: [email protected]"); final RpslObject updatedObject = RpslObject.parse("role: Abuse Role\nnic-hdl: TEST-NIC"); when(update.getReferenceObject()).thenReturn(originalObject); when(update.getUpdatedObject()).thenReturn(updatedObject); when(updateDao.getReferences(updatedObject)).thenReturn(Sets.newHashSet(new RpslObjectInfo(1, ObjectType.ORGANISATION, "ORG-TEST1"))); when(objectDao.getById(1)).thenReturn(RpslObject.parse("organisation: ORG-TEST1\nabuse-c: TEST-NIC")); subject.validate(update, updateContext); verify(updateContext).addMessage(update, UpdateMessages.abuseMailboxReferenced("Abuse Role", ObjectType.ORGANISATION)); }
KeycertValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired KeycertValidator(final KeyWrapperFactory keyWrapperFactory, final X509AutoKeyFactory x509AutoKeyFactory); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.CREATE)); }
KeycertValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Autowired KeycertValidator(final KeyWrapperFactory keyWrapperFactory, final X509AutoKeyFactory x509AutoKeyFactory); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getTypes() { assertThat(subject.getTypes(), containsInAnyOrder(ObjectType.KEY_CERT)); }
KeycertValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject updatedObject = update.getUpdatedObject(); if (x509AutoKeyFactory.isKeyPlaceHolder(updatedObject.getKey().toString())) { final KeyWrapper keyWrapper = keyWrapperFactory.createKeyWrapper(updatedObject, update, updateContext); if (keyWrapper instanceof PgpPublicKeyWrapper) { updateContext.addMessage(update, update.getUpdatedObject().getTypeAttribute(), UpdateMessages.autokeyForX509KeyCertsOnly()); } } } @Autowired KeycertValidator(final KeyWrapperFactory keyWrapperFactory, final X509AutoKeyFactory x509AutoKeyFactory); @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void auto_1_with_x509() throws Exception { RpslObject object = RpslObject.parse(getResource("keycerts/AUTO-1-X509.TXT")); when(update.getAction()).thenReturn(Action.CREATE); when(update.getUpdatedObject()).thenReturn(object); when(keyWrapperFactory.createKeyWrapper(object, update, updateContext)).thenReturn(X509CertificateWrapper.parse(object)); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void auto_3_with_pgp() throws Exception { RpslObject object = RpslObject.parse("" + "key-cert: AUTO-3\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.11 (Darwin)\n" + "certif:\n" + "certif: mQENBE841dMBCAC80IDqJpJC7ch16NEaWvLDM8CslkhiqYk9fgXgUdMNuBsJJ/KV\n" + "certif: 4oUwzrX+3lNvMPSoW7yRfiokFQ48IhYVZuGlH7DzwsyfS3MniXmw6/vT6JaYPuIF\n" + "certif: 7TmMHIIxQbzJe+SUrauzJ2J0xQbnKhcfuLkmNO7jiOoKGJWIrO5wUZfd0/4nOoaz\n" + "certif: RMokk0Paj6r52ZMni44vV4R0QnuUJRNIIesPDYDkOZGXX1lD9fprTc2DJe8tjAu0\n" + "certif: VJz5PpCHwvS9ge22CRTUBSgmf2NBHJwDF+dnvijLuoDFyTuOrSkq0nAt0B9kTUxt\n" + "certif: Bsb7mNxlARduo5419hBp08P07LJb4upuVsMPABEBAAG0HkVkIFNocnlhbmUgPGVz\n" + "certif: aHJ5YW5lQHJpcGUubmV0PokBOAQTAQIAIgUCTzjV0wIbAwYLCQgHAwIGFQgCCQoL\n" + "certif: BBYCAwECHgECF4AACgkQ7pke4ij2zWyUKAf+MmDQnBUUSjDeFvCnNN4JTraMXFUi\n" + "certif: Ke2HzVnLvT/Z/XN5W6TIje7u1luTJk/siJJyKYa1ZWQoVOCXruTSge+vP6LxENOX\n" + "certif: /sOJ1YxWHJUr3OVOfW2NoKBaUkBBCxi/CSaPti7YPHF0D6rn3GJtoJTnLL4KPnWV\n" + "certif: gtja4FtpsgwhiPF/jVmx6/d5Zc/dndDLZZt2sMjh0KDVf7F03hsF/EAauBbxMLvK\n" + "certif: yEHMdw7ab5CxeorgWEDaLrR1YwHWHy9cbYC00Mgp1zQR1ok2wN/XZVL7BZYPS/UC\n" + "certif: H03bFi3AcN1Vm55QpbU0QJ4qPN8uwYc5VBFSSYRITUCwbB5qBO5kIIBLP7kBDQRP\n" + "certif: ONXTAQgA16kMTcjxOtkU8v3sLAIpr2xWwG91BdB2fLV0aUgaZWfexKMnWDu8xpm1\n" + "certif: qY+viF+/emdXBc/C7QbFUmhmXCslX5kfD10hkYFTIqc1Axk5Ya8FZtwHFpo0TVTl\n" + "certif: sGodZ2gy8334rT9yMH+bZNSlZ+07Fxa7maC1ycxPPL/68+LSBy6wWlAFCwwr7XwN\n" + "certif: LGnrBbELgvoi04yMu1EpqAvxZLH1TBgzrFcWzXJjj1JKIB1RGapoDc3m7dvHa3+e\n" + "certif: 27aQosQnNVNWrHiS67zqWoC963aNuHZBY174yfKPRaN6s5GppC2hMPYGnJV07yah\n" + "certif: P0mwRcp4e3AaJIg2SP9CUQJKGPY+mQARAQABiQEfBBgBAgAJBQJPONXTAhsMAAoJ\n" + "certif: EO6ZHuIo9s1souEH/ieP9J69j59zfVcN6FimT86JF9CVyB86PGv+naHEyzOrBjml\n" + "certif: xBn2TPCNSE5KH8+gENyvYaQ6Wxv4Aki2HnJj5H43LfXPZZ6HNME4FPowoIkumc9q\n" + "certif: mndn6WXsgjwT9lc2HQmUgolQObg3JMBRe0rYzVf5N9+eXkc5lR/PpTOHdesP17uM\n" + "certif: QqtJs2hKdZKXgKNufSypfQBLXxkhez0KvoZ4PvrLItZTZUjrnRXdObNUgvz5/SVh\n" + "certif: 4Oqesj+Z36YNFrsYobghzIqOiP4hINsm9mQoshz8YLZe0z7InwcFYHp7HvQWEOyj\n" + "certif: kSYadR4aN+CVhYHOsn5nxbiKSFNAWh40q7tDP7I=\n" + "certif: =XRho\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "notify: [email protected]\n" + "source: TEST\n"); when(update.getAction()).thenReturn(Action.CREATE); when(update.getUpdatedObject()).thenReturn(object); when(x509AutoKeyFactory.isKeyPlaceHolder("AUTO-3")).thenReturn(true); when(keyWrapperFactory.createKeyWrapper(object, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(object)); subject.validate(update, updateContext); verify(updateContext).addMessage(update, object.getAttributes().get(0), UpdateMessages.autokeyForX509KeyCertsOnly()); } @Test public void one_public_key_with_multiple_sub_keys() throws Exception { RpslObject object = RpslObject.parse(getResource("keycerts/PGPKEY-MULTIPLE-SUBKEYS.TXT")); when(update.getUpdatedObject()).thenReturn(object); when(keyWrapperFactory.createKeyWrapper(object, update, updateContext)).thenReturn(PgpPublicKeyWrapper.parse(object)); subject.validate(update, updateContext); assertThat(messages.size(), is(0)); }
IpDomainUniqueHierarchyValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Autowired IpDomainUniqueHierarchyValidator(final Ipv4DomainTree ipv4DomainTree, final Ipv6DomainTree ipv6DomainTree); @SuppressWarnings("unchecked") @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.CREATE)); }
IpDomainUniqueHierarchyValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Autowired IpDomainUniqueHierarchyValidator(final Ipv4DomainTree ipv4DomainTree, final Ipv6DomainTree ipv6DomainTree); @SuppressWarnings("unchecked") @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getTypes() { assertThat(subject.getTypes(), containsInAnyOrder(ObjectType.DOMAIN)); }
IpDomainUniqueHierarchyValidator implements BusinessRuleValidator { @SuppressWarnings("unchecked") @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final Domain domain = Domain.parse(update.getUpdatedObject().getKey()); if (domain.getType() == Domain.Type.E164) { return; } final IpInterval reverseIp = domain.getReverseIp(); final IpTree ipTree = getIpTree(reverseIp); final List<IpEntry> lessSpecific = ipTree.findFirstLessSpecific(reverseIp); if (!lessSpecific.isEmpty()) { updateContext.addMessage(update, UpdateMessages.lessSpecificDomainFound(lessSpecific.get(0).getKey().toString())); return; } final List<IpEntry> moreSpecific = ipTree.findFirstMoreSpecific(reverseIp); if (!moreSpecific.isEmpty()) { updateContext.addMessage(update, UpdateMessages.moreSpecificDomainFound(moreSpecific.get(0).getKey().toString())); } } @Autowired IpDomainUniqueHierarchyValidator(final Ipv4DomainTree ipv4DomainTree, final Ipv6DomainTree ipv6DomainTree); @SuppressWarnings("unchecked") @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void validate_enum() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 2.1.2.1.5.5.5.2.0.2.1.e164.arpa")); subject.validate(update, updateContext); verifyZeroInteractions(ipv4DomainTree, ipv6DomainTree); } @Test public void validate_ipv4_domain_success() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 200.193.193.in-addr.arpa")); subject.validate(update, updateContext); verify(ipv4DomainTree).findFirstLessSpecific(Ipv4Resource.parse("193.193.200.0/24")); verify(ipv4DomainTree).findFirstMoreSpecific(Ipv4Resource.parse("193.193.200.0/24")); verifyZeroInteractions(ipv6DomainTree); } @Test public void validate_ipv6_domain_success() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 0.0.0.0.8.f.7.0.1.0.0.2.ip6.arpa")); subject.validate(update, updateContext); verify(ipv6DomainTree).findFirstLessSpecific(Ipv6Resource.parse("2001:7f8::/48")); verify(ipv6DomainTree).findFirstMoreSpecific(Ipv6Resource.parse("2001:7f8::/48")); verifyZeroInteractions(ipv4DomainTree); } @Test public void validate_ipv4_domain_less_specific() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 200.193.193.in-addr.arpa")); final Ipv4Resource lessSpecific = Ipv4Resource.parse("193/8"); when(ipv4DomainTree.findFirstLessSpecific(Ipv4Resource.parse("193.193.200.0/24"))).thenReturn(Lists.newArrayList(new Ipv4Entry(lessSpecific, 1))); subject.validate(update, updateContext); verify(updateContext).addMessage(update, UpdateMessages.lessSpecificDomainFound(lessSpecific.toString())); verifyZeroInteractions(ipv6DomainTree); } @Test public void validate_ipv4_domain_more_specific() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 200.193.193.in-addr.arpa")); final Ipv4Resource moreSpecific = Ipv4Resource.parse("193.193.200.0/32"); when(ipv4DomainTree.findFirstMoreSpecific(Ipv4Resource.parse("193.193.200.0/24"))).thenReturn(Lists.newArrayList(new Ipv4Entry(moreSpecific, 1))); subject.validate(update, updateContext); verify(updateContext).addMessage(update, UpdateMessages.moreSpecificDomainFound(moreSpecific.toString())); verifyZeroInteractions(ipv6DomainTree); }
ChannelUtil { public static InetAddress getRemoteAddress(final Channel channel) { final InetAddress inetAddress = ((InetSocketAddress) channel.getRemoteAddress()).getAddress(); if (inetAddress instanceof Inet6Address) { try { return InetAddress.getByAddress(inetAddress.getAddress()); } catch (UnknownHostException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } } return inetAddress; } private ChannelUtil(); static InetAddress getRemoteAddress(final Channel channel); static final Charset BYTE_ENCODING; }
@Test public void shouldGetRemoteAddressFromChannel() { InetAddress remoteAddress = ChannelUtil.getRemoteAddress(new StubbedChannel("192.168.0.1")); assertThat(remoteAddress.getHostAddress(), is("192.168.0.1")); } @Test public void shouldGetRemoteAddressFromIpv6AddressChannel() { InetAddress remoteAddress = ChannelUtil.getRemoteAddress(new StubbedChannel("2001:67c:2e8:13:1146:e6f4:bfd7:c324")); assertThat(remoteAddress.getHostAddress(), is("2001:67c:2e8:13:1146:e6f4:bfd7:c324")); } @Test public void shouldGetRemoteAddressFromIpv6WithoutInterface() { InetAddress remoteAddress = ChannelUtil.getRemoteAddress(new StubbedChannel("2001:67c:2e8:13:1146:e6f4:bfd7:c324", true)); assertThat(remoteAddress.getHostAddress(), is("2001:67c:2e8:13:1146:e6f4:bfd7:c324")); }
DatabaseTextExport implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "DatabaseTextExport") public void run() { rpslObjectsExporter.export(); } @Autowired DatabaseTextExport(final RpslObjectsExporter rpslObjectsExporter); @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "DatabaseTextExport") void run(); }
@Test public void run() { subject.run(); verify(rpslObjectsExporter).export(); }
EnumDomainAuthorisationValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.CREATE)); }
EnumDomainAuthorisationValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getTypes() { assertThat(subject.getTypes(), containsInAnyOrder(ObjectType.DOMAIN)); }
EnumDomainAuthorisationValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final Subject subject = updateContext.getSubject(update); if (subject.hasPrincipal(Principal.OVERRIDE_MAINTAINER)) { return; } final RpslObject rpslObject = update.getUpdatedObject(); final CIString domainString = rpslObject.getKey(); final Domain domain = Domain.parse(domainString); if (domain.getType() == Domain.Type.E164) { if (!subject.hasPrincipal(Principal.ENUM_MAINTAINER)) { updateContext.addMessage(update, UpdateMessages.authorisationRequiredForEnumDomain()); } } } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void validate_non_enum() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 200.193.193.in-addr.arpa")); subject.validate(update, updateContext); verify(updateContext).getSubject(any(UpdateContainer.class)); verifyNoMoreInteractions(updateContext); } @Test public void validate_override() { when(authSubject.hasPrincipal(Principal.OVERRIDE_MAINTAINER)).thenReturn(true); when(update.getUpdatedObject()).thenReturn(RpslObject.parse("domain: 2.1.2.1.5.5.5.2.0.2.1.e164.arpa")); when(authSubject.hasPrincipal(Principal.ENUM_MAINTAINER)).thenReturn(false); subject.validate(update, updateContext); verify(updateContext).getSubject(any(UpdateContainer.class)); verifyNoMoreInteractions(updateContext); } @Test public void validate_enum_no_enum_maintainer() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 2.1.2.1.5.5.5.2.0.2.1.e164.arpa")); when(authSubject.hasPrincipal(Principal.ENUM_MAINTAINER)).thenReturn(false); subject.validate(update, updateContext); verify(authSubject).hasPrincipal(Principal.ENUM_MAINTAINER); verify(updateContext).addMessage(update, UpdateMessages.authorisationRequiredForEnumDomain()); } @Test public void validate_enum_with_enum_maintainer() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 2.1.2.1.5.5.5.2.0.2.1.e164.arpa")); when(authSubject.hasPrincipal(Principal.ENUM_MAINTAINER)).thenReturn(true); subject.validate(update, updateContext); verify(authSubject).hasPrincipal(Principal.ENUM_MAINTAINER); verify(updateContext, never()).addMessage(update, UpdateMessages.authorisationRequiredForEnumDomain()); }
NServerValidator implements BusinessRuleValidator { @Override public ImmutableList<Action> getActions() { return ACTIONS; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getActions() { assertThat(subject.getActions(), containsInAnyOrder(Action.CREATE, Action.MODIFY)); }
NServerValidator implements BusinessRuleValidator { @Override public ImmutableList<ObjectType> getTypes() { return TYPES; } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void getTypes() { assertThat(subject.getTypes(), containsInAnyOrder(ObjectType.DOMAIN)); }
NServerValidator implements BusinessRuleValidator { @Override public void validate(final PreparedUpdate update, final UpdateContext updateContext) { final RpslObject updatedObject = update.getUpdatedObject(); final Domain domain = Domain.parse(updatedObject.getKey()); for (final RpslAttribute nServerAttribute : updatedObject.findAttributes(AttributeType.NSERVER)) { final NServer nServer = NServer.parse(nServerAttribute.getCleanValue()); switch (domain.getType()) { case E164: { final boolean endsWithDomain = domain.endsWithDomain(nServer.getHostname()); if (endsWithDomain && nServer.getIpInterval() == null) { updateContext.addMessage(update, nServerAttribute, UpdateMessages.glueRecordMandatory(domain.getValue())); } else if (!endsWithDomain && nServer.getIpInterval() != null) { updateContext.addMessage(update, nServerAttribute, UpdateMessages.invalidGlueForEnumDomain(nServer.getIpInterval().toString())); } break; } case INADDR: case IP6: { final boolean endsWithDomain = domain.endsWithDomain(nServer.getHostname()); if (endsWithDomain && nServer.getIpInterval() == null) { updateContext.addMessage(update, nServerAttribute, UpdateMessages.glueRecordMandatory(domain.getValue())); } else if (!endsWithDomain && nServer.getIpInterval() != null) { updateContext.addMessage(update, nServerAttribute, UpdateMessages.hostNameMustEndWith(domain.getValue())); } break; } } } } @Override void validate(final PreparedUpdate update, final UpdateContext updateContext); @Override ImmutableList<Action> getActions(); @Override ImmutableList<ObjectType> getTypes(); }
@Test public void enum_domain_mandatory_nserver_glue_present() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse( "domain: 8.8.8.e164.arpa\n" + "nserver: ns1.8.8.8.e164.arpa 192.0.2.1")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void enum_domain_mandatory_nserver_glue_not_present() { final RpslObject rpslObject = RpslObject.parse( "domain: 8.8.8.e164.arpa\n" + "nserver: ns1.8.8.8.e164.arpa"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verify(updateContext).addMessage(update, rpslObject.findAttribute(AttributeType.NSERVER), UpdateMessages.glueRecordMandatory("8.8.8.e164.arpa")); } @Test public void enum_domain_nserver_glue_not_mandatory_not_present() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse( "domain: 8.8.8.e164.arpa\n" + "nserver: ns1.example.net")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void enum_domain_nserver_glue_is_present() { final RpslObject rpslObject = RpslObject.parse( "domain: 8.8.8.e164.arpa\n" + "nserver: ns1.example.net 192.0.2.1"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verify(updateContext).addMessage(update, rpslObject.findAttribute(AttributeType.NSERVER), UpdateMessages.invalidGlueForEnumDomain("192.0.2.1/32")); } @Test public void validate_enum_missing_glue() { final RpslObject rpslObject = RpslObject.parse( "domain: 2.1.2.1.5.5.5.2.0.2.1.e164.arpa\n" + "nserver: a.ns.2.1.2.1.5.5.5.2.0.2.1.e164.arpa\n"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verify(updateContext).addMessage(update, rpslObject.findAttribute(AttributeType.NSERVER), UpdateMessages.glueRecordMandatory("2.1.2.1.5.5.5.2.0.2.1.e164.arpa")); } @Test public void validate_enum_nserver_does_not_end_with_domain() { final RpslObject rpslObject = RpslObject.parse("" + "domain: 1.e164.arpa\n" + "nserver: a.ns.e164.arpa\n"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void validate_enum_nserver_with_glue() { final RpslObject rpslObject = RpslObject.parse("" + "domain: 1.e164.arpa\n" + "nserver: a.ns.1.e164.arpa 193.46.210.1\n"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void validate_in_addr_success() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 144.102.5.in-addr.arpa\n" + "nserver: 144.102.5.in-addr.arpa 81.20.133.177\n")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void validate_in_addr_success_ipv4_ipv6() { when(update.getUpdatedObject()).thenReturn(RpslObject.parse("" + "domain: 64.67.217.in-addr.arpa\n" + "nserver: a.ns.64.67.217.in-addr.arpa 193.46.210.1\n" + "nserver: ns1.64.67.217.in-addr.arpa 2001:db8::1\n")); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); } @Test public void validate_in_addr_invalid() { final RpslObject rpslObject = RpslObject.parse("" + "domain: 144.102.5.in-addr.arpa\n" + "nserver: ns1.internetprovider.ch 81.20.133.177\n"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verify(updateContext).addMessage(update, rpslObject.findAttribute(AttributeType.NSERVER), UpdateMessages.hostNameMustEndWith("144.102.5.in-addr.arpa")); } @Test public void validate_glue_record_mandatory() { final RpslObject rpslObject = RpslObject.parse("" + "domain: 144.102.5.in-addr.arpa\n" + "nserver: ns1.144.102.5.in-addr.arpa\n"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verify(updateContext).addMessage(update, rpslObject.findAttribute(AttributeType.NSERVER), UpdateMessages.glueRecordMandatory("144.102.5.in-addr.arpa")); } @Test public void validate_in_addr_valid() { final RpslObject rpslObject = RpslObject.parse("" + "domain: 144.102.5.in-addr.arpa\n" + "nserver: ns1.144.102.5.in-addr.arpa 81.20.133.177\n"); when(update.getUpdatedObject()).thenReturn(rpslObject); subject.validate(update, updateContext); verifyZeroInteractions(updateContext); }
UpdateRequestHandler { public UpdateResponse handle(final UpdateRequest updateRequest, final UpdateContext updateContext) { UpdateResponse updateResponse; try { updateResponse = handleUpdateRequest(updateRequest, updateContext); } catch (RuntimeException e) { LOGGER.error("Handling update request", e); updateResponse = new UpdateResponse(UpdateStatus.EXCEPTION, responseFactory.createExceptionResponse(updateContext, updateRequest.getOrigin())); } return updateResponse; } @Autowired UpdateRequestHandler(final SourceContext sourceContext, final ResponseFactory responseFactory, final SingleUpdateHandler singleUpdateHandler, final MultipleUpdateHandler multipleUpdateHandler, final LoggerContext loggerContext, final DnsChecker dnsChecker, final SsoTranslator ssoTranslator, final UpdateNotifier updateNotifier, final UpdateLog updateLog); UpdateResponse handle(final UpdateRequest updateRequest, final UpdateContext updateContext); }
@Test public void mntner() { when(updateRequest.getUpdates()).thenReturn(Lists.newArrayList(update)); when(ack.getUpdateStatus()).thenReturn(UpdateStatus.SUCCESS); when(responseFactory.createAckResponse(updateContext, origin, ack)).thenReturn("ACK"); final RpslObject maintainer = RpslObject.parse("mntner: DEV-ROOT-MNT"); when(update.getSubmittedObject()).thenReturn(maintainer); when(updateContext.getStatus(any(PreparedUpdate.class))).thenReturn(UpdateStatus.SUCCESS); subject.handle(updateRequest, updateContext); verify(sourceContext).setCurrentSourceToWhoisMaster(); verify(sourceContext).removeCurrentSource(); verify(dnsChecker).checkAll(updateRequest, updateContext); verify(singleUpdateHandler).handle(origin, Keyword.NONE, update, updateContext); verify(updateNotifier).sendNotifications(updateRequest, updateContext); } @Test public void domain() { when(updateRequest.getUpdates()).thenReturn(Lists.newArrayList(update)); when(ack.getUpdateStatus()).thenReturn(UpdateStatus.SUCCESS); when(responseFactory.createAckResponse(updateContext, origin, ack)).thenReturn("ACK"); final RpslObject domain = RpslObject.parse("domain: 36.84.80.in-addr.arpa"); when(update.getType()).thenReturn(ObjectType.DOMAIN); when(update.getSubmittedObject()).thenReturn(domain); when(updateContext.getStatus(any(PreparedUpdate.class))).thenReturn(UpdateStatus.SUCCESS); subject.handle(updateRequest, updateContext); verify(sourceContext).setCurrentSourceToWhoisMaster(); verify(sourceContext).removeCurrentSource(); verify(dnsChecker).checkAll(updateRequest, updateContext); verify(singleUpdateHandler).handle(origin, Keyword.NONE, update, updateContext); } @Test public void domain_delete() { when(updateRequest.getUpdates()).thenReturn(Lists.newArrayList(update)); when(ack.getUpdateStatus()).thenReturn(UpdateStatus.SUCCESS); when(responseFactory.createAckResponse(updateContext, origin, ack)).thenReturn("ACK"); final RpslObject domain = RpslObject.parse("domain: 36.84.80.in-addr.arpa"); when(update.getType()).thenReturn(ObjectType.DOMAIN); when(update.getSubmittedObject()).thenReturn(domain); when(update.getOperation()).thenReturn(Operation.DELETE); when(updateContext.getStatus(any(PreparedUpdate.class))).thenReturn(UpdateStatus.SUCCESS); subject.handle(updateRequest, updateContext); verify(sourceContext).setCurrentSourceToWhoisMaster(); verify(sourceContext).removeCurrentSource(); verify(dnsChecker).checkAll(updateRequest, updateContext); verify(singleUpdateHandler).handle(origin, Keyword.NONE, update, updateContext); } @Test public void help() { when(responseFactory.createHelpResponse(updateContext, origin)).thenReturn("help"); final UpdateRequest updateRequest = new UpdateRequest(origin, Keyword.HELP, Collections.<Update>emptyList()); final UpdateResponse response = subject.handle(updateRequest, updateContext); assertThat(response.getStatus(), is(UpdateStatus.SUCCESS)); assertThat(response.getResponse(), is("help")); verify(sourceContext, never()).setCurrentSourceToWhoisMaster(); verify(sourceContext, never()).removeCurrentSource(); }
UpdateNotifier { public void sendNotifications(final UpdateRequest updateRequest, final UpdateContext updateContext) { if (updateContext.isDryRun()) { return; } final Map<CIString, Notification> notifications = Maps.newHashMap(); for (final Update update : updateRequest.getUpdates()) { final PreparedUpdate preparedUpdate = updateContext.getPreparedUpdate(update); if (preparedUpdate != null && !notificationsDisabledByOverride(preparedUpdate)) { addNotifications(notifications, preparedUpdate, updateContext); } } for (final Notification notification : notifications.values()) { final ResponseMessage responseMessage = responseFactory.createNotification(updateContext, updateRequest.getOrigin(), notification); try { new InternetAddress(notification.getEmail(), true); mailGateway.sendEmail(notification.getEmail(), responseMessage); } catch (final AddressException e) { LOGGER.info("Failed to send notification to '{}' because it's an invalid email address", notification.getEmail()); } } } @Autowired UpdateNotifier(final RpslObjectDao rpslObjectDao, final ResponseFactory responseFactory, final MailGateway mailGateway, final VersionDao versionDao, final Maintainers maintainers); void sendNotifications(final UpdateRequest updateRequest, final UpdateContext updateContext); }
@Test public void sendNotifications_empty() { when(updateRequest.getUpdates()).thenReturn(Lists.<Update>newArrayList()); subject.sendNotifications(updateRequest, updateContext); verifyZeroInteractions(responseFactory, mailGateway); } @Test public void sendNotifications_noPreparedUpdate() { final Update update = mock(Update.class); when(updateRequest.getUpdates()).thenReturn(Lists.newArrayList(update)); subject.sendNotifications(updateRequest, updateContext); verifyZeroInteractions(responseFactory, mailGateway); } @Test public void sendNotifications_single_no_notifications() { final Update update = mock(Update.class); final RpslObject rpslObject = RpslObject.parse( "mntner: UPD-MNT\n" + "descr: description\n" + "admin-c: TEST-RIPE\n" + "mnt-by: UPD-MNT\n" + "mnt-nfy: [email protected]\n" + "mnt-nfy: [email protected]\n" + "notify: [email protected]\n" + "notify: [email protected]\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$fU9ZMQN9$QQtm3kRqZXWAuLpeOiLN7. # update\n" + "source: TEST\n"); final PreparedUpdate preparedUpdate = new PreparedUpdate(update, null, rpslObject, Action.CREATE); when(updateRequest.getUpdates()).thenReturn(Lists.newArrayList(update)); when(updateContext.getPreparedUpdate(update)).thenReturn(preparedUpdate); when(updateContext.getStatus(preparedUpdate)).thenReturn(UpdateStatus.SUCCESS); ResponseMessage responseMessage = new ResponseMessage("Notification of RIPE Database changes", "message"); when(responseFactory.createNotification(any(UpdateContext.class), any(Origin.class), any(Notification.class))).thenReturn(responseMessage); subject.sendNotifications(updateRequest, updateContext); verify(mailGateway).sendEmail(eq("[email protected]"), eq(responseMessage)); verify(mailGateway).sendEmail(eq("[email protected]"), eq(responseMessage)); } @Test public void sendNotifications_sanitized_email() { final Update update = mock(Update.class); final RpslObject rpslObject = RpslObject.parse( "mntner: UPD-MNT\n" + "descr: description\n" + "admin-c: TEST-RIPE\n" + "mnt-by: UPD-MNT\n" + "mnt-nfy: [email protected]\n" + "mnt-nfy: [email protected]\n" + "notify: notifies us <mailto:[email protected]>\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$fU9ZMQN9$QQtm3kRqZXWAuLpeOiLN7. # update\n" + "source: TEST\n"); final PreparedUpdate preparedUpdate = new PreparedUpdate(update, null, rpslObject, Action.CREATE); when(updateRequest.getUpdates()).thenReturn(Lists.newArrayList(update)); when(updateContext.getPreparedUpdate(update)).thenReturn(preparedUpdate); when(updateContext.getStatus(preparedUpdate)).thenReturn(UpdateStatus.SUCCESS); when(responseFactory.createNotification(eq(updateContext), any(Origin.class), any(Notification.class))).thenReturn(responseMessage); subject.sendNotifications(updateRequest, updateContext); verify(mailGateway, never()).sendEmail("notifies us <mailto:[email protected]>", responseMessage); }
MaintenanceModeJmx extends JmxBase { @ManagedOperation(description = "Sets maintenance mode") @ManagedOperationParameters({ @ManagedOperationParameter(name = "mode", description = "Access rights for 'world,trusted' (values: FULL/READONLY/NONE) (e.g. 'none,full')"), }) public void setMaintenanceMode(final String mode) { invokeOperation("Set maintenance mode", mode, new Callable<Void>() { @Override public Void call() throws Exception { maintenanceMode.set(mode); return null; } }); } @Autowired MaintenanceModeJmx(final MaintenanceMode maintenanceMode, IpRanges ipRanges); @ManagedOperation(description = "Sets maintenance mode") @ManagedOperationParameters({ @ManagedOperationParameter(name = "mode", description = "Access rights for 'world,trusted' (values: FULL/READONLY/NONE) (e.g. 'none,full')"), }) void setMaintenanceMode(final String mode); @ManagedOperation(description = "Sets trusted range (ipranges.trusted)") @ManagedOperationParameters({ @ManagedOperationParameter(name = "ranges", description = "Comma-separated list of IP prefixes/ranges (e.g. '10/8,::1/64)"), }) void setTrustedIpRanges(final String ranges); }
@Test public void maintenance_mode_set() { subject.setMaintenanceMode("FULL, FULL"); verify(maintenanceMode, times(1)).set(anyString()); }
CountryCodeRepository { public Set<CIString> getCountryCodes() { return countryCodes; } @Autowired CountryCodeRepository(@Value("${whois.countrycodes}") final String[] countryCodes); Set<CIString> getCountryCodes(); }
@Test public void getCountryCodes() { assertThat(subject.getCountryCodes(), containsInAnyOrder(ciString("NL"), ciString("EN"))); } @Test(expected = UnsupportedOperationException.class) public void getCountryCodes_immutable() { subject.getCountryCodes().add(ciString("DE")); }
X509AutoKeyFactory implements AutoKeyFactory<X509KeycertId> { @Override public AttributeType getAttributeType() { return AttributeType.KEY_CERT; } @Autowired X509AutoKeyFactory(final X509Repository repository, @Value("${whois.source}") String source); @Override AttributeType getAttributeType(); @Override boolean isKeyPlaceHolder(final CharSequence s); @Override CIString getKeyPlaceholder(final CharSequence s); @Override X509KeycertId claim(final String key); @Override X509KeycertId generate(final String keyPlaceHolder, final RpslObject object); @Override boolean isApplicableFor(final RpslObject object); }
@Test public void attributeType() { assertThat(subject.getAttributeType(), is(AttributeType.KEY_CERT)); }
X509AutoKeyFactory implements AutoKeyFactory<X509KeycertId> { @Override public boolean isKeyPlaceHolder(final CharSequence s) { return AUTO_PATTERN.matcher(s).matches(); } @Autowired X509AutoKeyFactory(final X509Repository repository, @Value("${whois.source}") String source); @Override AttributeType getAttributeType(); @Override boolean isKeyPlaceHolder(final CharSequence s); @Override CIString getKeyPlaceholder(final CharSequence s); @Override X509KeycertId claim(final String key); @Override X509KeycertId generate(final String keyPlaceHolder, final RpslObject object); @Override boolean isApplicableFor(final RpslObject object); }
@Test public void correct_keyPlaceHolder() { assertThat(subject.isKeyPlaceHolder("AUTO-100"), is(true)); } @Test public void incorrect_keyPlaceHolder() { assertThat(subject.isKeyPlaceHolder("AUTO-100NL"), is(false)); assertThat(subject.isKeyPlaceHolder("AUTO-"), is(false)); assertThat(subject.isKeyPlaceHolder("AUTO"), is(false)); assertThat(subject.isKeyPlaceHolder("AUTO-100-NL"), is(false)); }
X509AutoKeyFactory implements AutoKeyFactory<X509KeycertId> { @Override public X509KeycertId claim(final String key) throws ClaimException { throw new ClaimException(ValidationMessages.syntaxError(key, "must be AUTO-nnn for create")); } @Autowired X509AutoKeyFactory(final X509Repository repository, @Value("${whois.source}") String source); @Override AttributeType getAttributeType(); @Override boolean isKeyPlaceHolder(final CharSequence s); @Override CIString getKeyPlaceholder(final CharSequence s); @Override X509KeycertId claim(final String key); @Override X509KeycertId generate(final String keyPlaceHolder, final RpslObject object); @Override boolean isApplicableFor(final RpslObject object); }
@Test(expected = ClaimException.class) public void claim_not_supported() throws ClaimException { subject.claim("irrelevant here"); }
X509AutoKeyFactory implements AutoKeyFactory<X509KeycertId> { @Override public X509KeycertId generate(final String keyPlaceHolder, final RpslObject object) { Validate.notEmpty(object.getValueForAttribute(AttributeType.KEY_CERT).toString(), "Name must not be empty"); final Matcher matcher = AUTO_PATTERN.matcher(keyPlaceHolder); if (!matcher.matches()) { throw new IllegalArgumentException("Invalid key request: " + keyPlaceHolder); } return repository.claimNextAvailableIndex(SPACE, source.toString()); } @Autowired X509AutoKeyFactory(final X509Repository repository, @Value("${whois.source}") String source); @Override AttributeType getAttributeType(); @Override boolean isKeyPlaceHolder(final CharSequence s); @Override CIString getKeyPlaceholder(final CharSequence s); @Override X509KeycertId claim(final String key); @Override X509KeycertId generate(final String keyPlaceHolder, final RpslObject object); @Override boolean isApplicableFor(final RpslObject object); }
@Test(expected = IllegalArgumentException.class) public void generate_invalid_placeHolder() { subject.generate("AUTO", RpslObject.parse("key-cert: AUTO")); } @Test public void generate_correct() { when(x509Repository.claimNextAvailableIndex("X509", "TEST")).thenReturn(new X509KeycertId("X509", 2, "TEST")); final X509KeycertId generated = subject.generate("AuTO-1", RpslObject.parse("kEy-Cert: auto\nremarks: optional")); assertThat(generated.toString(), is("X509-2")); }
AutoKeyResolver { public RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action) { final Map<RpslAttribute, RpslAttribute> attributesToReplace = Maps.newHashMap(); if (Action.CREATE.equals(action)) { claimOrGenerateAutoKeys(update, object, updateContext, attributesToReplace); } resolveAutoKeyReferences(update, object, updateContext, attributesToReplace); if (attributesToReplace.isEmpty()) { return object; } return new RpslObjectBuilder(object).replaceAttributes(attributesToReplace).get(); } @Autowired AutoKeyResolver(final AutoKeyFactory... autoKeyFactories); RpslObject resolveAutoKeys(final RpslObject object, final Update update, final UpdateContext updateContext, final Action action); }
@Test public void resolveAutoKeys_key_create_auto() { RpslObject object = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: AUTO-1\n"); final RpslObject rpslObject = subject.resolveAutoKeys(object, update, updateContext, Action.CREATE); assertThat(rpslObject.toString(), is("" + "person: John Doe\n" + "nic-hdl: J1-RIPE\n")); verify(autoKeyFactory, times(1)).generate(anyString(), any(RpslObject.class)); } @Test public void resolveAutoKeys_reference_auto() { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: AUTO-1\n"); subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); RpslObject mntner = RpslObject.parse("" + "mntner: TST-MNT\n" + "admin-c: AUTO-1\n"); final RpslObject rpslObject = subject.resolveAutoKeys(mntner, update, updateContext, Action.CREATE); assertThat(rpslObject.toString(), is("" + "mntner: TST-MNT\n" + "admin-c: J1-RIPE\n")); verify(autoKeyFactory, times(1)).generate(anyString(), any(RpslObject.class)); } @Test public void resolveAutoKeys_self_reference() { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: AUTO-1\n" + "tech-c: AUTO-1\n" + "remarks: AUTO-1"); final RpslObject rpslObject = subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); assertThat(rpslObject.toString(), is("" + "person: John Doe\n" + "nic-hdl: J1-RIPE\n" + "tech-c: J1-RIPE\n" + "remarks: AUTO-1\n")); verify(autoKeyFactory, times(1)).generate(anyString(), any(RpslObject.class)); } @Test public void resolveAutoKeys_modify() throws Exception { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: JD1-RIPE\n"); subject.resolveAutoKeys(person, update, updateContext, Action.MODIFY); verify(autoKeyFactory, never()).claim(anyString()); verify(autoKeyFactory, never()).generate(anyString(), any(RpslObject.class)); } @Test public void resolveAutoKeys_key_specified_available_create() throws Exception { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: JD1-RIPE\n"); when(autoKeyFactory.claim(anyString())).thenReturn(new NicHandle("JD", 1, "RIPE")); final RpslObject rpslObject = subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); assertThat(rpslObject, is(person)); verify(autoKeyFactory).claim("JD1-RIPE"); verify(autoKeyFactory, never()).generate(anyString(), any(RpslObject.class)); } @Test public void resolveAutoKeys_key_specified_invalid() throws Exception { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: INVALID_NIC_HANDLE\n"); when(autoKeyFactory.claim(anyString())).thenThrow(new ClaimException(ValidationMessages.syntaxError("INVALID_NIC_HANDLE", ""))); final RpslObject rpslObject = subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); assertThat(rpslObject, is(person)); verify(autoKeyFactory).claim("INVALID_NIC_HANDLE"); verify(autoKeyFactory, never()).generate(anyString(), any(RpslObject.class)); assertThat(updateContext.getMessages(update).getMessages(person.getAttributes().get(1)).getAllMessages(), contains(ValidationMessages.syntaxError("INVALID_NIC_HANDLE", ""))); } @Test public void resolveAutoKeys_key_specified_not_available_create() throws Exception { RpslObject person = RpslObject.parse("" + "person: John Doe\n" + "nic-hdl: JD1-RIPE\n"); when(autoKeyFactory.claim(anyString())).thenThrow(new ClaimException(UpdateMessages.nicHandleNotAvailable("JD1-RIPE"))); final RpslObject rpslObject = subject.resolveAutoKeys(person, update, updateContext, Action.CREATE); assertThat(rpslObject, is(person)); verify(autoKeyFactory).claim("JD1-RIPE"); verify(autoKeyFactory, never()).generate(anyString(), any(RpslObject.class)); assertThat(updateContext.getMessages(update).hasErrors(), is(true)); assertThat(updateContext.getMessages(update).getMessages(person.getAttributes().get(1)).getAllMessages(), contains(UpdateMessages.nicHandleNotAvailable("JD1-RIPE"))); } @Test public void resolveAutoKeys_reference_not_found() { when(autoKeyFactory.getKeyPlaceholder(anyString())).thenReturn(ciString("AUTO-1")); RpslObject mntner = RpslObject.parse("" + "mntner: TST-MNT\n" + "admin-c: AUTO-1\n"); final RpslObject rpslObject = subject.resolveAutoKeys(mntner, update, updateContext, Action.MODIFY); assertThat(rpslObject.toString(), is("" + "mntner: TST-MNT\n" + "admin-c: AUTO-1\n")); assertThat(updateContext.getMessages(update).hasErrors(), is(true)); assertThat(updateContext.getMessages(update).getMessages(mntner.getAttributes().get(1)).getAllMessages(), contains(UpdateMessages.referenceNotFound("AUTO-1"))); }
FormatHelper { public static String dateToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); }
@Test public void testDateToString_null() { assertNull(FormatHelper.dateToString(null)); } @Test public void testDateToString_date() { assertThat(FormatHelper.dateToString(LocalDate.of(2001, 10, 1)), is("2001-10-01")); } @Test public void testDateToString_dateTime() throws Exception { assertThat(FormatHelper.dateToString(LocalDateTime.of(2001, 10, 1, 12, 0, 0)), is("2001-10-01")); }
NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getTypeAttribute().getCleanValue().toString()); } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); }
@Test(expected = IllegalArgumentException.class) public void generate_invalid_placeHolder() { subject.generate("AUTO", RpslObject.parse("person: name")); } @Test public void generate_specified_space() { when(nicHandleRepository.claimNextAvailableIndex("DW", SOURCE)).thenReturn(new NicHandle("DW", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-1234567DW", RpslObject.parse("person: name\nnic-hdl: AUTO-1234567DW")); assertThat(nicHandle.toString(), is("DW10-RIPE")); } @Test public void generate_unspecified_space() { when(nicHandleRepository.claimNextAvailableIndex("JAS", SOURCE)).thenReturn(new NicHandle("JAS", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-111", RpslObject.parse("person: John Archibald Smith\nnic-hdl: AUTO-111")); assertThat(nicHandle.toString(), is("JAS10-RIPE")); } @Test public void generate_unspecified_lower() { when(nicHandleRepository.claimNextAvailableIndex("SN", SOURCE)).thenReturn(new NicHandle("SN", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-111", RpslObject.parse("person: some name\nnic-hdl: AUTO-111")); assertThat(nicHandle.toString(), is("SN10-RIPE")); } @Test public void generate_unspecified_long() { when(nicHandleRepository.claimNextAvailableIndex("SATG", SOURCE)).thenReturn(new NicHandle("SATG", 10, SOURCE)); final NicHandle nicHandle = subject.generate("AUTO-1234567", RpslObject.parse("person: Satellite advisory Technologies Group Ltd\nnic-hdl: AUTO-1234567")); assertThat(nicHandle.toString(), is("SATG10-RIPE")); }
NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public AttributeType getAttributeType() { return AttributeType.NIC_HDL; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); }
@Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(AttributeType.NIC_HDL)); }
NicHandleFactory extends AbstractAutoKeyFactory<NicHandle> { @Override public NicHandle claim(final String key) throws ClaimException { final NicHandle nicHandle = parseNicHandle(key); if (!nicHandleRepository.claimSpecified(nicHandle)) { throw new ClaimException(UpdateMessages.nicHandleNotAvailable(nicHandle.toString())); } return nicHandle; } @Autowired NicHandleFactory(final NicHandleRepository nicHandleRepository, final CountryCodeRepository countryCodeRepository); @Override AttributeType getAttributeType(); @Override NicHandle generate(final String keyPlaceHolder, final RpslObject object); @Override NicHandle claim(final String key); boolean isAvailable(final String key); }
@Test public void claim() throws Exception { final NicHandle nicHandle = new NicHandle("DW", 10, "RIPE"); when(nicHandleRepository.claimSpecified(nicHandle)).thenReturn(true); assertThat(subject.claim("DW10-RIPE"), is(nicHandle)); } @Test public void claim_not_available() { when(nicHandleRepository.claimSpecified(new NicHandle("DW", 10, "RIPE"))).thenReturn(false); try { subject.claim("DW10-RIPE"); fail("Claim succeeded?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(UpdateMessages.nicHandleNotAvailable("DW10-RIPE"))); } } @Test public void claim_invalid_handle() { try { subject.claim("INVALID_HANDLE"); fail("Claim succeeded?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(ValidationMessages.syntaxError("INVALID_HANDLE"))); } }
OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId generate(final String keyPlaceHolder, final RpslObject object) { return generateForName(keyPlaceHolder, object.getValueForAttribute(AttributeType.ORG_NAME).toString()); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); }
@Test(expected = IllegalArgumentException.class) public void generate_invalid_placeHolder() { subject.generate("AUTO", RpslObject.parse("organisation: AUTO\norg-name: name")); } @Test public void generate_specified_space() { when(organisationIdRepository.claimNextAvailableIndex("DW", SOURCE)).thenReturn(new OrganisationId("DW", 10, SOURCE)); final OrganisationId organisationId = subject.generate("AUTO-1234567DW", RpslObject.parse("organisation: AUTO\norg-name: name")); assertThat(organisationId.toString(), is("ORG-DW10-RIPE")); } @Test public void generate_unspecified_space_single_word_name() { when(organisationIdRepository.claimNextAvailableIndex("TA", SOURCE)).thenReturn(new OrganisationId("TA", 1, SOURCE)); RpslObject orgObject = RpslObject.parse("organisation: AUTO-1\norg-name: Tesco"); final OrganisationId organisationId = subject.generate("AUTO-1", orgObject); assertThat(organisationId.toString(), is("ORG-TA1-RIPE")); } @Test public void generate_unspecified_space() { when(organisationIdRepository.claimNextAvailableIndex("SATG", SOURCE)).thenReturn(new OrganisationId("SATG", 10, SOURCE)); final OrganisationId organisationId = subject.generate("AUTO-111", RpslObject.parse("organisation: AUTO\norg-name: Satellite advisory Technologies Group Ltd")); assertThat(organisationId.toString(), is("ORG-SATG10-RIPE")); }
OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public AttributeType getAttributeType() { return AttributeType.ORGANISATION; } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); }
@Test public void getAttributeType() { assertThat(subject.getAttributeType(), is(AttributeType.ORGANISATION)); }
OrganisationIdFactory extends AbstractAutoKeyFactory<OrganisationId> { @Override public OrganisationId claim(final String key) throws ClaimException { throw new ClaimException(ValidationMessages.syntaxError(key, "must be AUTO-nnn for create")); } @Autowired OrganisationIdFactory(final OrganisationIdRepository organisationIdRepository); @Override AttributeType getAttributeType(); @Override OrganisationId generate(final String keyPlaceHolder, final RpslObject object); @Override OrganisationId claim(final String key); }
@Test public void claim() throws Exception { try { subject.claim("ORG-DW10-RIPE"); fail("claim() supported?"); } catch (ClaimException e) { assertThat(e.getErrorMessage(), is(ValidationMessages.syntaxError("ORG-DW10-RIPE (must be AUTO-nnn for create)"))); } }
X509CertificateWrapper implements KeyWrapper { static boolean looksLikeX509Key(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(X509_HEADER) != -1 && pgpKey.indexOf(X509_FOOTER) != -1; } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }
@Test public void isX509Key() throws IOException { assertThat(X509CertificateWrapper.looksLikeX509Key(x509Keycert), is(true)); assertThat(X509CertificateWrapper.looksLikeX509Key(pgpKeycert), is(false)); }
X509CertificateWrapper implements KeyWrapper { @Override public String getMethod() { return METHOD; } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }
@Test public void getMethod() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.getMethod(), is("X509")); }
X509CertificateWrapper implements KeyWrapper { @Override public String getFingerprint() { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] der = certificate.getEncoded(); md.update(der); byte[] digest = md.digest(); StringBuilder builder = new StringBuilder(); for (byte next : digest) { if (builder.length() > 0) { builder.append(':'); } builder.append(String.format("%02X", next)); } return builder.toString(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } catch (CertificateEncodingException e) { throw new IllegalArgumentException("Invalid X509 Certificate", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }
@Test public void getFingerprint() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.getFingerprint(), is("16:4F:B6:A4:D9:BC:0C:92:D4:48:13:FE:B6:EF:E2:82")); }
X509CertificateWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final LocalDateTime notAfter = DateUtil.fromDate(certificate.getNotAfter()); return notAfter.isBefore(dateTimeProvider.getCurrentDateTime()); } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }
@Test public void isExpired() { X509CertificateWrapper subject = X509CertificateWrapper.parse(x509Keycert); assertThat(subject.isExpired(dateTimeProvider), is(false)); when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.now().plusYears(100)); assertThat(subject.isExpired(dateTimeProvider), is(true)); }
X509CertificateWrapper implements KeyWrapper { public static X509CertificateWrapper parse(final RpslObject rpslObject) { if (!looksLikeX509Key(rpslObject)) { throw new IllegalArgumentException("The supplied object has no key"); } try { return parse(RpslObjectFilter.getCertificateFromKeyCert(rpslObject).getBytes(StandardCharsets.ISO_8859_1)); } catch (StreamParsingException e) { throw new IllegalArgumentException("Error parsing X509 certificate from key-cert object", e); } } private X509CertificateWrapper(final X509Certificate certificate); static X509CertificateWrapper parse(final RpslObject rpslObject); static X509CertificateWrapper parse(final byte[] certificate); @Override boolean equals(final Object o); @Override int hashCode(); X509Certificate getCertificate(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isNotYetValid(final DateTimeProvider dateTimeProvider); boolean isExpired(final DateTimeProvider dateTimeProvider); static final String X509_HEADER; static final String X509_FOOTER; }
@Test(expected = IllegalArgumentException.class) public void invalidCertificateBase64IsTruncated() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-3465\n" + "method: X509\n" + "owner: /description=570433-veZWA34E9nftz1i7/C=PL/ST=Foo/L=Bar/CN=Test/[email protected]\n" + "fingerpr: 07:AC:10:C0:22:64:84:E7:00:18:5A:29:F0:54:2C:F3\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: MIIHaTCCBlGgAwIBAgICGSowDQYJKoZIhvcNAQEFBQAwgYwxCzAJBgNVBAYTAklM\n" + "certif: UK1J2P3MpSIP8TFJp8fIJDlad3hoRsZeNxuV6D8=\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST"); X509CertificateWrapper.parse(keycert); } @Test(expected = IllegalArgumentException.class) public void invalidCertificateNoBase64Data() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-3465\n" + "method: X509\n" + "owner: /description=570433-veZWA34E9nftz1i7/C=PL/ST=Foo/L=Bar/CN=Test/[email protected]\n" + "fingerpr: 07:AC:10:C0:22:64:84:E7:00:18:5A:29:F0:54:2C:F3\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST"); X509CertificateWrapper.parse(keycert); } @Test(expected = IllegalArgumentException.class) public void invalidCertificateInvalidBase64Data() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-3465\n" + "method: X509\n" + "owner: /description=570433-veZWA34E9nftz1i7/C=PL/ST=Foo/L=Bar/CN=Test/[email protected]\n" + "fingerpr: 07:AC:10:C0:22:64:84:E7:00:18:5A:29:F0:54:2C:F3\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: xxx\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST"); X509CertificateWrapper.parse(keycert); } @Test(expected = IllegalArgumentException.class) public void invalidCertificateNoCertifLines() { final RpslObject keycert = RpslObject.parse( "key-cert: X509-3465\n" + "method: X509\n" + "owner: /description=570433-veZWA34E9nftz1i7/C=PL/ST=Foo/L=Bar/CN=Test/[email protected]\n" + "fingerpr: 07:AC:10:C0:22:64:84:E7:00:18:5A:29:F0:54:2C:F3\n" + "mnt-by: UPD-MNT\n" + "source: TEST"); X509CertificateWrapper.parse(keycert); }
FormatHelper { public static String dateTimeToString(final TemporalAccessor temporalAccessor) { if (temporalAccessor == null) { return null; } if (temporalAccessor.isSupported(ChronoField.HOUR_OF_DAY)) { return DATE_TIME_FORMAT.format(temporalAccessor); } return DATE_FORMAT.format(temporalAccessor); } private FormatHelper(); static String dateToString(final TemporalAccessor temporalAccessor); static String dateTimeToString(final TemporalAccessor temporalAccessor); static String dateTimeToUtcString(final TemporalAccessor temporalAccessor); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength); static String prettyPrint(final String prefix, final String value, final int indentation, final int maxLineLength, boolean repeatPrefix); }
@Test public void testDateTimeToString_null() { assertNull(FormatHelper.dateTimeToString(null)); } @Test public void testDateTimeToString_date() { assertThat(FormatHelper.dateTimeToString(LocalDate.of(2001, 10, 1)), is("2001-10-01")); } @Test public void testDateTimeToString_dateTime() throws Exception { assertThat(FormatHelper.dateTimeToString(LocalDateTime.of(2001, 10, 1, 12, 13, 14)), is("2001-10-01 12:13:14")); }
KeyWrapperFactory { @CheckForNull public KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext) { try { if (PgpPublicKeyWrapper.looksLikePgpKey(object)) { return PgpPublicKeyWrapper.parse(object); } else if (X509CertificateWrapper.looksLikeX509Key(object)) { return X509CertificateWrapper.parse(object); } else { updateContext.addMessage(updateContainer, new Message(Messages.Type.ERROR, "The supplied object has no key")); } } catch (IllegalArgumentException e) { final Message errorMessage = new Message(Messages.Type.ERROR, e.getMessage()); final List<RpslAttribute> attributes = object.findAttributes(AttributeType.CERTIF); if (attributes.isEmpty()) { updateContext.addMessage(updateContainer, errorMessage); } else { updateContext.addMessage(updateContainer, attributes.get(attributes.size() - 1), errorMessage); } } return null; } @CheckForNull KeyWrapper createKeyWrapper(final RpslObject object, final UpdateContainer updateContainer, final UpdateContext updateContext); }
@Test public void createKeyWrapper_invalid_pgp_key() { final RpslObject rpslObject = RpslObject.parse("" + "key-cert: PGPKEY-28F6CD6C\n" + "method: PGP\n" + "owner: DFN-CERT (2003), ENCRYPTION Key\n" + "fingerpr: 1C40 500A 1DC4 A8D8 D3EA ABF9 EE99 1EE2 28F6 CD6C\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.11 (Darwin)\n" + "certif:\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "notify: [email protected]\n" + "source: TEST\n" ); final KeyWrapper keyWrapper = subject.createKeyWrapper(rpslObject, updateContainer, updateContext); assertNull(keyWrapper); } @Test public void createKeyWrapper_invalid_x509_key() { final RpslObject rpslObject = RpslObject.parse("" + "key-cert: AUTO-1\n" + "method: X509\n" + "owner: /CN=4a96eecf-9d1c-4e12-8add-5ea5522976d8\n" + "fingerpr: 82:7C:C5:40:D1:DB:AE:6A:FA:F8:40:3E:3C:9C:27:7C\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "remarks: remark\n" + "source: TEST\n" ); final KeyWrapper keyWrapper = subject.createKeyWrapper(rpslObject, updateContainer, updateContext); assertNull(keyWrapper); } @Test public void createKeyWrapper_pgp_key() { final RpslObject rpslObject = RpslObject.parse("" + "key-cert: X509-1\n" + "method: X509\n" + "owner: /C=NL/O=RIPE NCC/OU=Members/CN=zz.example.denis/[email protected]\n" + "fingerpr: E7:0F:3B:D4:2F:DD:F5:84:3F:4C:D2:98:78:F3:10:3D\n" + "certif: -----BEGIN CERTIFICATE-----\n" + "certif: MIIC8DCCAlmgAwIBAgICBIQwDQYJKoZIhvcNAQEEBQAwXjELMAkGA1UEBhMCTkwx\n" + "certif: ETAPBgNVBAoTCFJJUEUgTkNDMR0wGwYDVQQLExRSSVBFIE5DQyBMSVIgTmV0d29y\n" + "certif: azEdMBsGA1UEAxMUUklQRSBOQ0MgTElSIFJvb3QgQ0EwHhcNMDQwOTI3MTI1NDAx\n" + "certif: WhcNMDUwOTI3MTI1NDAxWjBsMQswCQYDVQQGEwJOTDERMA8GA1UEChMIUklQRSBO\n" + "certif: Q0MxEDAOBgNVBAsTB01lbWJlcnMxGTAXBgNVBAMTEHp6LmV4YW1wbGUuZGVuaXMx\n" + "certif: HTAbBgkqhkiG9w0BCQEWDmRlbmlzQHJpcGUubmV0MFwwDQYJKoZIhvcNAQEBBQAD\n" + "certif: SwAwSAJBAKdZEYY0pCb5updB808+y8CjNsnraQ/3sBL3/184TqD4AE/TSOdZJ2oU\n" + "certif: HmEpfm6ECkbHOJ1NtMwRjAbkk/rWiBMCAwEAAaOB8jCB7zAJBgNVHRMEAjAAMBEG\n" + "certif: CWCGSAGG+EIBAQQEAwIFoDALBgNVHQ8EBAMCBeAwGgYJYIZIAYb4QgENBA0WC1JJ\n" + "certif: UEUgTkNDIENBMB0GA1UdDgQWBBQk0+qAmXPImzyVTOGARwNPHAX0GTCBhgYDVR0j\n" + "certif: BH8wfYAUI8r2d8CnSt174cfhUw2KNga3Px6hYqRgMF4xCzAJBgNVBAYTAk5MMREw\n" + "certif: DwYDVQQKEwhSSVBFIE5DQzEdMBsGA1UECxMUUklQRSBOQ0MgTElSIE5ldHdvcmsx\n" + "certif: HTAbBgNVBAMTFFJJUEUgTkNDIExJUiBSb290IENBggEAMA0GCSqGSIb3DQEBBAUA\n" + "certif: A4GBAAxojauJHRm3XtPfOCe4B5iz8uVt/EeKhM4gjHGJrUbkAlftLJYUe2Vx8HcH\n" + "certif: O4b+9E098Rt6MfFF+1dYNz7/NgiIpR7BlmdWzPCyhfgxJxTM9m9B7B/6noDU+aaf\n" + "certif: w0L5DyjKGe0dbjMKtaDdgQhxj8aBHNnQVbS9Oqhvmc65XgNi\n" + "certif: -----END CERTIFICATE-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n" ); final KeyWrapper keyWrapper = subject.createKeyWrapper(rpslObject, updateContainer, updateContext); assertTrue(keyWrapper instanceof X509CertificateWrapper); } @Test public void createKeyWrapper_x509_key() { final RpslObject rpslObject = RpslObject.parse("" + "key-cert: PGPKEY-81CCF97D\n" + "method: PGP\n" + "owner: Unknown <[email protected]>\n" + "fingerpr: EDDF 375A B830 D1BB 26E5 ED3B 76CA 91EF 81CC F97D\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "certif: Comment: GPGTools - http: "certif:\n" + "certif: mQENBFC0yvUBCACn2JKwa5e8Sj3QknEnD5ypvmzNWwYbDhLjmD06wuZxt7Wpgm4+\n" + "certif: yO68swuow09jsrh2DAl2nKQ7YaODEipis0d4H2i0mSswlsC7xbmpx3dRP/yOu4WH\n" + "certif: 2kZciQYxC1NY9J3CNIZxgw6zcghJhtm+LT7OzPS8s3qp+w5nj+vKY09A+BK8yHBN\n" + "certif: E+VPeLOAi+D97s+Da/UZWkZxFJHdV+cAzQ05ARqXKXeadfFdbkx0Eq2R0RZm9R+L\n" + "certif: A9tPUhtw5wk1gFMsN7c5NKwTUQ/0HTTgA5eyKMnTKAdwhIY5/VDxUd1YprnK+Ebd\n" + "certif: YNZh+L39kqoUL6lqeu0dUzYp2Ll7R2IURaXNABEBAAG0I25vcmVwbHlAcmlwZS5u\n" + "certif: ZXQgPG5vcmVwbHlAcmlwZS5uZXQ+iQE4BBMBAgAiBQJQtMr1AhsDBgsJCAcDAgYV\n" + "certif: CAIJCgsEFgIDAQIeAQIXgAAKCRC7zLstV2OVDdjSCACYAyyWr83Df/zzOWGP+qMF\n" + "certif: Vukj8xhaM5f5MGb9FjMKClo6ezT4hLjQ8hfxAAZxndwAXoz46RbDUsAe/aBwdwKB\n" + "certif: 0owcacoaxUd0i+gVEn7CBHPVUfNIuNemcrf1N7aqBkpBLf+NINZ2+3c3t14k1BGe\n" + "certif: xCInxEqHnq4zbUmunCNYjHoKbUj6Aq7janyC7W1MIIAcOY9/PvWQyf3VnERQImgt\n" + "certif: 0fhiekCr6tRbANJ4qFoJQSM/ACoVkpDvb5PHZuZXf/v+XB1DV7gZHjJeZA+Jto5Z\n" + "certif: xrmS5E+HEHVBO8RsBOWDlmWCcZ4k9olxp7/z++mADXPprmLaK8vjQmiC2q/KOTVA\n" + "certif: uQENBFC0yvUBCADTYI6i4baHAkeY2lR2rebpTu1nRHbIET20II8/ZmZDK8E2Lwyv\n" + "certif: eWold6pAWDq9E23J9xAWL4QUQRQ4V+28+lknMySXbU3uFLXGAs6W9PrZXGcmy/12\n" + "certif: pZ+82hHckh+jN9xUTtF89NK/wHh09SAxDa/ST/z/Dj0k3pQWzgBdi36jwEFtHhck\n" + "certif: xFwGst5Cv8SLvA9/DaP75m9VDJsmsSwh/6JqMUb+hY71Dr7oxlIFLdsREsFVzVec\n" + "certif: YHsKINlZKh60dA/Br+CC7fClBycEsR4Z7akw9cPLWIGnjvw2+nq9miE005QLqRy4\n" + "certif: dsrwydbMGplaE/mZc0d2WnNyiCBXAHB5UhmZABEBAAGJAR8EGAECAAkFAlC0yvUC\n" + "certif: GwwACgkQu8y7LVdjlQ1GMAgAgUohj4q3mAJPR6d5pJ8Ig5E3QK87z3lIpgxHbYR4\n" + "certif: HNaR0NIV/GAt/uca11DtIdj3kBAj69QSPqNVRqaZja3NyhNWQM4OPDWKIUZfolF3\n" + "certif: eY2q58kEhxhz3JKJt4z45TnFY2GFGqYwFPQ94z1S9FOJCifL/dLpwPBSKucCac9y\n" + "certif: 6KiKfjEehZ4VqmtM/SvN23GiI/OOdlHL/xnU4NgZ90GHmmQFfdUiX36jWK99LBqC\n" + "certif: RNW8V2MV+rElPVRHev+nw7vgCM0ewXZwQB/bBLbBrayx8LzGtMvAo4kDJ1kpQpip\n" + "certif: a/bmKCK6E+Z9aph5uoke8bKoybIoQ2K3OQ4Mh8yiI+AjiQ==\n" + "certif: =HQmg\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "notify: [email protected]\n" + "source: TEST\n" ); final KeyWrapper keyWrapper = subject.createKeyWrapper(rpslObject, updateContainer, updateContext); assertTrue(keyWrapper instanceof PgpPublicKeyWrapper); }
PgpPublicKeyWrapper implements KeyWrapper { static boolean looksLikePgpKey(final RpslObject rpslObject) { final String pgpKey = RpslObjectFilter.getCertificateFromKeyCert(rpslObject); return pgpKey.indexOf(PGP_HEADER) != -1 && pgpKey.indexOf(PGP_FOOTER) != -1; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void isPgpKey() { assertThat(PgpPublicKeyWrapper.looksLikePgpKey(pgpKeycert), is(true)); assertThat(PgpPublicKeyWrapper.looksLikePgpKey(x509Keycert), is(false)); }
PgpPublicKeyWrapper implements KeyWrapper { public static PgpPublicKeyWrapper parse(final RpslObject object) { if (!looksLikePgpKey(object)) { throw new IllegalArgumentException("The supplied object has no key"); } try { final byte[] bytes = RpslObjectFilter.getCertificateFromKeyCert(object).getBytes(StandardCharsets.ISO_8859_1); final ArmoredInputStream armoredInputStream = (ArmoredInputStream) PGPUtil.getDecoderStream(new ByteArrayInputStream(bytes)); PGPPublicKey masterKey = null; List<PGPPublicKey> subKeys = Lists.newArrayList(); @SuppressWarnings("unchecked") final Iterator<PGPPublicKeyRing> keyRingsIterator = new BcPGPPublicKeyRingCollection(armoredInputStream).getKeyRings(); while (keyRingsIterator.hasNext()) { @SuppressWarnings("unchecked") final Iterator<PGPPublicKey> keyIterator = keyRingsIterator.next().getPublicKeys(); while (keyIterator.hasNext()) { final PGPPublicKey key = keyIterator.next(); if (key.isMasterKey()) { if (masterKey == null) { masterKey = key; } else { throw new IllegalArgumentException("The supplied object has multiple keys"); } } else { if (masterKey == null) { continue; } final Iterator<PGPSignature> signatureIterator = key.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); while (signatureIterator.hasNext()) { final PGPSignature signature = signatureIterator.next(); if (!hasFlag(signature, PGPKeyFlags.CAN_SIGN)) { continue; } JcaPGPContentVerifierBuilderProvider provider = new JcaPGPContentVerifierBuilderProvider().setProvider(PROVIDER); signature.init(provider, masterKey); try { if (signature.verifyCertification(masterKey, key)) { subKeys.add(key); } } catch (PGPException e) { throw new IllegalStateException(e); } } } } } if (masterKey == null) { throw new IllegalArgumentException("The supplied object has no key"); } return new PgpPublicKeyWrapper(masterKey, subKeys); } catch (IOException | PGPException e) { throw new IllegalArgumentException("The supplied object has no key"); } catch (IllegalArgumentException e) { throw e; } catch (Exception e) { LOGGER.warn("Unexpected error, throwing no key by default", e); throw new IllegalArgumentException("The supplied object has no key"); } } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void multiplePublicKeys() throws Exception { try { PgpPublicKeyWrapper.parse(RpslObject.parse(getResource("keycerts/PGPKEY-MULTIPLE-PUBLIC-KEYS.TXT"))); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("The supplied object has multiple keys")); } } @Test public void parsePrivateKey() throws Exception { try { PgpPublicKeyWrapper.parse(RpslObject.parse(getResource("keycerts/PGPKEY-PRIVATE-KEY.TXT"))); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("The supplied object has no key")); } } @Test public void unreadableKeyring() { try { PgpPublicKeyWrapper.parse( RpslObject.parse( "key-cert: PGPKEY-2424420B\n" + "method: PGP\n" + "owner: Test User <[email protected]>\n" + "fingerpr: 3F0D 878A 9352 5F7C 4BED F475 A72E FF2A 2424 420B\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Comment: GPGTools - http: "certif:=20\n" + "certif: mDMEXDSFIBYJKwYBBAHaRw8BAQdAApW0Ud7TmlaWDeMN6nfxRSRbC5sE8U+oKc8Y\n" + "certif: 4nQWT7C0HFRlc3QgVXNlciA8bm9yZXBseUByaXBlLm5ldD6IkAQTFggAOBYhBD8N\n" + "certif: h4qTUl98S+30dacu/yokJEILBQJcNIUgAhsDBQsJCAcCBhUKCQgLAgQWAgMBAh4B\n" + "certif: AheAAAoJEKcu/yokJEIL4cwA/2jOgBV0OHylbE5iDx1VIoMnIJCS12JODgwqwMms\n" + "certif: rbVfAP9RAtdxNqdt/Bwu5mX6fTSGSff6yicqzGretWlkRh8aBbg4BFw0hSASCisG\n" + "certif: AQQBl1UBBQEBB0Dx8kHIOKw/klxcIYcYhY28leG80qnPMgP4wgRK5JpefQMBCAeI\n" + "certif: eAQYFggAIBYhBD8Nh4qTUl98S+30dacu/yokJEILBQJcNIUgAhsMAAoJEKcu/yok\n" + "certif: JEILEp4BAJLGZuQ5qJkl8eqGKb6BCVmoynaFTutYbm2IIed6pmDJAQCa7CqeUY1V\n" + "certif: duNXCkPvStUGG6dIRgtWlW7vwSVwgnd3BA==\n" + "certif: =GGwH\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "admin-c: AA1-RIPE\n" + "tech-c: AA1-RIPE\n" + "mnt-by: UPD-MNT\n" + "source: TEST")); fail(); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("The supplied object has no key")); } }
PgpPublicKeyWrapper implements KeyWrapper { public boolean isExpired(final DateTimeProvider dateTimeProvider) { final long validSeconds = masterKey.getValidSeconds(); if (validSeconds > 0) { final int days = Long.valueOf(Long.divideUnsigned(validSeconds, SECONDS_IN_ONE_DAY)).intValue(); final LocalDateTime expired = (DateUtil.fromDate(masterKey.getCreationTime())).plusDays(days); return expired.isBefore(dateTimeProvider.getCurrentDateTime()); } return false; } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void isExpired() { final PgpPublicKeyWrapper subject = PgpPublicKeyWrapper.parse( RpslObject.parse( "key-cert: PGPKEY-C88CA438\n" + "method: PGP\n" + "owner: Expired <[email protected]>\n" + "fingerpr: 610A 2457 2BA3 A575 5F85 4DD8 5E62 6C72 C88C A438\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "certif: Comment: GPGTools - http: "certif:\n" + "certif: mI0EUOoKSgEEAMvJBJzUBKDA8BGK+KpJMuGSOXnQgvymxgyOUOBVkLpeOcPQMy1A\n" + "certif: 4fffXJ4V0xdlqtikDATCnSIBS17ihi7xD8fUvKF4dJrq+rmaVULoy06B68IcfYKQ\n" + "certif: yoRJqGii/1Z47FuudeJp1axQs1JER3OJ64IHuLblFIT7oS+YWBLopc1JABEBAAG0\n" + "certif: GkV4cGlyZWQgPGV4cGlyZWRAcmlwZS5uZXQ+iL4EEwECACgFAlDqCkoCGwMFCQAB\n" + "certif: UYAGCwkIBwMCBhUIAgkKCwQWAgMBAh4BAheAAAoJEF5ibHLIjKQ4tEMD/j8VYxdY\n" + "certif: V6JM8rDokg+zNE4Ifc7nGaUrsrF2YRmcIg6OXVhPGLIqfQB2IsKub595sA1vgwNs\n" + "certif: +Cg0tzaQfzWh2Nz5NxFGnDHm5tPfOfiADwpMuLtZby390Wpbwk7VGZMqfcDXt3uy\n" + "certif: Ch4rvayDTtzQqDVqo1kLgK5dIc/UIlX3jaxWuI0EUOoKSgEEANYcEMxrEGD4LSgk\n" + "certif: vHVECSOB0q32CN/wSrvVzL6hP8RuO0gwwVQH1V8KCYiY6kDEk33Qb4f1bTo+Wbi6\n" + "certif: 9yFvn1OvLh3/idb3U1qSq2+Y6Snl/kvgoVJQuS9x1NePtCYL2kheTAGiswg6CxTF\n" + "certif: RZ3c7CaNHsCbUdIpQmNUxfcWBH3PABEBAAGIpQQYAQIADwUCUOoKSgIbDAUJAAFR\n" + "certif: gAAKCRBeYmxyyIykON13BACeqmXZNe9H/SK2AMiFLIx2Zfyw/P0cKabn3Iaan7iF\n" + "certif: kSwrZQhF4571MBxb9U41Giiyza/t7vLQH1S+FYFUqfWCa8p1VQDRavi4wDgy2PDp\n" + "certif: ouhDqH+Mfkqb7yv40kYOUJ02eKkdgSgwTEcpfwq9GU4kJLVO5O3Y3nOEAx736gPQ\n" + "certif: xw==\n" + "certif: =XcVO\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST")); assertThat(subject.isExpired(dateTimeProvider), is(true)); }
PgpPublicKeyWrapper implements KeyWrapper { public boolean isRevoked() { return masterKey.hasRevocation(); } PgpPublicKeyWrapper(final PGPPublicKey masterKey, final List<PGPPublicKey> subKeys); static PgpPublicKeyWrapper parse(final RpslObject object); PGPPublicKey getPublicKey(); List<PGPPublicKey> getSubKeys(); @Override String getMethod(); @Override List<String> getOwners(); @Override String getFingerprint(); boolean isExpired(final DateTimeProvider dateTimeProvider); boolean isRevoked(); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void isRevoked() { final PgpPublicKeyWrapper subject = PgpPublicKeyWrapper.parse( RpslObject.parse( "key-cert: PGPKEY-A48E76B2\n" + "method: PGP\n" + "owner: Revoked <[email protected]>\n" + "fingerpr: D9A8 D291 0E72 DE20 FE50 C8FD FC24 50DF A48E 76B2\n" + "certif: -----BEGIN PGP PUBLIC KEY BLOCK-----\n" + "certif: Version: GnuPG v1.4.12 (Darwin)\n" + "certif: Comment: GPGTools - http: "certif: \n" + "certif: mI0EUOtGSgEEALdT44Ijp/M+KUvuSjLR "certif: 4gdXcsgpHjbcqe1KO00obtB74scD50l4sm9XPPr6tMK9I7MgwRlgRoJDWmw3lTFG\n" + "certif: 7H1MSqI+RY9EcXTxbtfflfkoexvwIhheHge9OUNsdbgX4Su/Tv6KCVYxABEBAAGI\n" + "certif: nwQgAQIACQUCUOtIJwIdAgAKCRD8JFDfpI52spqaBACUfqolAt+ubV5+9hlF9RuD\n" + "certif: oE0B/OBmB/YwdNIs90s/zBwdiC8F6fB0dMJS0prFfOIJHCoMP6cSLUX83LjimNUk\n" + "certif: b6yYrNaFwAacWQaIA4lgw6GEsvo9tT0ZKZ7/tmcAl0uE3xJ5SyLMaJ5+2ayZ4U6O\n" + "certif: 6r/ZepAn4V0+zJAecy8BabQaUmV2b2tlZCA8cmV2b2tlZEByaXBlLm5ldD6IuAQT\n" + "certif: AQIAIgUCUOtGSgIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQ/CRQ36SO\n" + "certif: drJJnwP+KU0nu8SfDb60Vvmhv2NceH5kPeAHJY3h4p6JSvo5b+RwjhxVQ2j7j4t2\n" + "certif: du9ozj+DrCpaQ4WfOttwg+wgFOSxhcV6y/o60BZMXCYf3DSP0wQiIC/w4vAQq1+U\n" + "certif: bNfDnGKhvJp7zob2BLTlpTi16APghTjnIXMVuUFfjFqURaemVT+4jQRQ60ZKAQQA\n" + "certif: 1lvszl35cbExUezs+Uf2IoXrbqGNw4S7fIJogZigxeUkcgd+uK3aoL+zMlGOJuv1\n" + "certif: OyTh4rQfi+U99aVHQazRO4KSFsB1JjmlizRBkHtRJ5/4u5v8gzUa92Jj1MXHs0gS\n" + "certif: qQ0cCdRUMnZxcgg+4mYslUp2pC/vzk0II2HEnSQa/UsAEQEAAYifBBgBAgAJBQJQ\n" + "certif: 60ZKAhsMAAoJEPwkUN+kjnay+jwEAJWGJFkFX1XdvGtbs7bPCdcMcJ3c/rj1vO91\n" + "certif: gNAjK/onsAzsBzsOSOx2eCEb4ftDASLmvnuK2h+lYLn5GOy0QpmCsZ37E3RcnhZq\n" + "certif: uKUMNY9A83YE8MV8MZXzds4p6XG1+YR7bP9nmgKqsLG9stCPAugVQqxVBbcQRsRV\n" + "certif: dnTzEonl\n" + "certif: =fnvN\n" + "certif: -----END PGP PUBLIC KEY BLOCK-----\n" + "mnt-by: UPD-MNT\n" + "source: TEST")); assertThat(subject.isRevoked(), is(true)); }
X509SignedMessage { public boolean verify(final X509Certificate certificate) { try { CMSProcessable cmsProcessable = new CMSProcessableByteArray(signedData.getBytes()); CMSSignedData signedData = new CMSSignedData(cmsProcessable, Base64.decode(signature)); Iterator signersIterator = signedData.getSignerInfos().getSigners().iterator(); if (signersIterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) signersIterator.next(); LOGGER.debug("Message is signed by certificate: {}", getFingerprint(signerInformation, signedData.getCertificates())); JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder(); verifierBuilder.setProvider(PROVIDER); return signerInformation.verify(verifierBuilder.build(certificate.getPublicKey())); } } catch (CMSSignerDigestMismatchException e) { throw new IllegalArgumentException("message-digest attribute value does not match calculated value", e); } catch (CMSException e) { throw new IllegalArgumentException("general exception verifying signed message", e); } catch (OperatorCreationException e) { throw new IllegalArgumentException("error creating verifier", e); } catch (Exception e) { throw new IllegalArgumentException(e); } return false; } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void verify_smime_plaintext() throws Exception { final String signedData = ( "Content-Transfer-Encoding: 7bit\n" + "Content-Type: text/plain;\n" + "\tcharset=us-ascii\n" + "\n" + "person: First Person\n" + "address: St James Street\n" + "address: Burnley\n" + "address: UK\n" + "phone: +44 282 420469\n" + "nic-hdl: FP1-TEST\n" + "mnt-by: OWNER-MNT\n" + "changed: [email protected] 20121016\n" + "source: TEST\n\n").replaceAll("\\n", "\r\n"); final String signature = "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIDtTCCA7Ew\n" + "ggMaoAMCAQICAgF8MA0GCSqGSIb3DQEBBAUAMIGFMQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9v\n" + "cmQtSG9sbGFuZDESMBAGA1UEBxMJQW1zdGVyZGFtMREwDwYDVQQKEwhSSVBFIE5DQzEMMAoGA1UE\n" + "CxMDT1BTMQwwCgYDVQQDEwNDQTIxGzAZBgkqhkiG9w0BCQEWDG9wc0ByaXBlLm5ldDAeFw0xMTEy\n" + "MDExMjM3MjNaFw0yMTExMjgxMjM3MjNaMIGAMQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9vcmQt\n" + "SG9sbGFuZDERMA8GA1UEChMIUklQRSBOQ0MxCzAJBgNVBAsTAkRCMRcwFQYDVQQDEw5FZHdhcmQg\n" + "U2hyeWFuZTEgMB4GCSqGSIb3DQEJARYRZXNocnlhbmVAcmlwZS5uZXQwgZ8wDQYJKoZIhvcNAQEB\n" + "BQADgY0AMIGJAoGBAMNs8uEHIiGdYms93PWA4bysV3IUwsabb+fwP6ACS9Jc8OaRQkT+1oK1sfw+\n" + "yX0YloCwJXtnAYDeKHoaPNiJ+dro3GN6BiijjV72KyKThHxWmZwXeqOKVCReREVNNlkuJTvziani\n" + "cZhlr9+bxhwRho1mkEvBmxEzPZTYKl0vQpd1AgMBAAGjggExMIIBLTAJBgNVHRMEAjAAMCwGCWCG\n" + "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUwSiXle3q\n" + "9cufhKDVUCxrEPhj/9cwgbIGA1UdIwSBqjCBp4AUviRV1EFXFxVsA8ildF9OwyDKY9ihgYukgYgw\n" + "gYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJk\n" + "YW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkGCSqG\n" + "SIb3DQEJARYMb3BzQHJpcGUubmV0ggEAMB4GA1UdEQQXMBWCE2UzLTIuc2luZ3cucmlwZS5uZXQw\n" + "DQYJKoZIhvcNAQEEBQADgYEAU5D2f5WK8AO5keVVf1/kj+wY/mRis9C7nXyhmQgrNcxzxqq+0Q7Q\n" + "mAYsNWMKDLZRemks4FfTGTmVT2SosQntXQBUoR1FGD3LQYLDZ2p1d7A6falUNu0PR8yAqJpT2Q2E\n" + "acKOic/UwHXhVorC1gbKZ5fN0dbUHqSk1zm41VQpobAxggLWMIIC0gIBATCBjDCBhTELMAkGA1UE\n" + "BhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQxEjAQBgNVBAcTCUFtc3RlcmRhbTERMA8GA1UE\n" + "ChMIUklQRSBOQ0MxDDAKBgNVBAsTA09QUzEMMAoGA1UEAxMDQ0EyMRswGQYJKoZIhvcNAQkBFgxv\n" + "cHNAcmlwZS5uZXQCAgF8MAkGBSsOAwIaBQCgggGfMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEw\n" + "HAYJKoZIhvcNAQkFMQ8XDTEzMDEwMzA4MzM0NFowIwYJKoZIhvcNAQkEMRYEFF8/6nTWJD4Fl2J0\n" + "sgOOpFsmJg/DMIGdBgkrBgEEAYI3EAQxgY8wgYwwgYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1O\n" + "b29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYD\n" + "VQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkGCSqGSIb3DQEJARYMb3BzQHJpcGUubmV0AgIBfDCB\n" + "nwYLKoZIhvcNAQkQAgsxgY+ggYwwgYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xs\n" + "YW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMx\n" + "DDAKBgNVBAMTA0NBMjEbMBkGCSqGSIb3DQEJARYMb3BzQHJpcGUubmV0AgIBfDANBgkqhkiG9w0B\n" + "AQEFAASBgJOTl3PkpLoOo5MRWaPs/2OHXOzg+Oj9OsNEB326bvl0e7ULuWq2SqVY44LKb6JM5nm9\n" + "6lHk5PJqv6xZq+m1pUYlCqJKFQTPsbnoA3zjrRCDghWc8CZdsK2F7OajTZ6WV98gPeoCdRhvgiU3\n" + "1jpwXyycrnAxekeLNqiX0/hldjkhAAAAAAAA\n"; final X509Certificate certificate = getCertificate( "-----BEGIN CERTIFICATE-----\n" + "MIIDsTCCAxqgAwIBAgICAXwwDQYJKoZIhvcNAQEEBQAwgYUxCzAJBgNVBAYTAk5M\n" + "MRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAP\n" + "BgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkG\n" + "CSqGSIb3DQEJARYMb3BzQHJpcGUubmV0MB4XDTExMTIwMTEyMzcyM1oXDTIxMTEy\n" + "ODEyMzcyM1owgYAxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5k\n" + "MREwDwYDVQQKEwhSSVBFIE5DQzELMAkGA1UECxMCREIxFzAVBgNVBAMTDkVkd2Fy\n" + "ZCBTaHJ5YW5lMSAwHgYJKoZIhvcNAQkBFhFlc2hyeWFuZUByaXBlLm5ldDCBnzAN\n" + "BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw2zy4QciIZ1iaz3c9YDhvKxXchTCxptv\n" + "5/A/oAJL0lzw5pFCRP7WgrWx/D7JfRiWgLAle2cBgN4oeho82In52ujcY3oGKKON\n" + "XvYrIpOEfFaZnBd6o4pUJF5ERU02WS4lO/OJqeJxmGWv35vGHBGGjWaQS8GbETM9\n" + "lNgqXS9Cl3UCAwEAAaOCATEwggEtMAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8W\n" + "HU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBTBKJeV7er1\n" + "y5+EoNVQLGsQ+GP/1zCBsgYDVR0jBIGqMIGngBS+JFXUQVcXFWwDyKV0X07DIMpj\n" + "2KGBi6SBiDCBhTELMAkGA1UEBhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQx\n" + "EjAQBgNVBAcTCUFtc3RlcmRhbTERMA8GA1UEChMIUklQRSBOQ0MxDDAKBgNVBAsT\n" + "A09QUzEMMAoGA1UEAxMDQ0EyMRswGQYJKoZIhvcNAQkBFgxvcHNAcmlwZS5uZXSC\n" + "AQAwHgYDVR0RBBcwFYITZTMtMi5zaW5ndy5yaXBlLm5ldDANBgkqhkiG9w0BAQQF\n" + "AAOBgQBTkPZ/lYrwA7mR5VV/X+SP7Bj+ZGKz0LudfKGZCCs1zHPGqr7RDtCYBiw1\n" + "YwoMtlF6aSzgV9MZOZVPZKixCe1dAFShHUUYPctBgsNnanV3sDp9qVQ27Q9HzICo\n" + "mlPZDYRpwo6Jz9TAdeFWisLWBspnl83R1tQepKTXObjVVCmhsA==\n" + "-----END CERTIFICATE-----"); final X509SignedMessage subject = new X509SignedMessage(signedData, signature); assertThat(subject.verify(certificate), is(true)); } @Test public void verify_smime_plaintext_multiple_paragraphs() throws Exception { final String signedData = ("Content-Type: text/plain; charset=\"iso-8859-1\"\n" + "Content-Transfer-Encoding: 7bit\n" + "Content-Language: de-DE\n" + "\n" + "inetnum: 193.0.0.0 - 193.0.0.255\n" + "netname: NETNAME\n" + "descr: Description\n" + "country: NL\n" + "admin-c: TEST-RIPE\n" + "tech-c: TEST-RIPE\n" + "status: ASSIGNED PA\n" + "mnt-by: TEST-MNT\n" + "changed: [email protected]\n" + "source: RIPE\n" + "\n" + "changed: [email protected]\n" + "\n").replaceAll("\\n", "\r\n"); final String signature = "MIIDsAYJKoZIhvcNAQcCoIIDoTCCA50CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3\n" + "DQEHAaCCAd8wggHbMIIBRAIJAJrBRtmpa9a7MA0GCSqGSIb3DQEBBQUAMDIxCzAJ\n" + "BgNVBAYTAk5MMRMwEQYDVQQIEwpTb21lLVN0YXRlMQ4wDAYDVQQKEwVCT0dVUzAe\n" + "Fw0xMzA0MTgxNTQyMjBaFw0xNDA0MTgxNTQyMjBaMDIxCzAJBgNVBAYTAk5MMRMw\n" + "EQYDVQQIEwpTb21lLVN0YXRlMQ4wDAYDVQQKEwVCT0dVUzCBnzANBgkqhkiG9w0B\n" + "AQEFAAOBjQAwgYkCgYEAp9e053n54CuwZNjY0bgslBQDRSjN+f2wZ8ut0Xt5aj3j\n" + "RpjhWVUF4isUzqMm30E0HHev1meDOWQIgzyhnqDJF/+UUjzKBrZ47OvpBR/9W1WY\n" + "EI4xbUHEBd8LIxPuMrY8+l7xJcPw1D1W/MNs/wscUDTMBX63/qq+WkZcl+31idsC\n" + "AwEAATANBgkqhkiG9w0BAQUFAAOBgQBHLN6q1lPTRQ6+VLPc0dK5fQAaGI5C9d6L\n" + "Yb1fAn0vt1eBt6HnAK+H2PX19yaaCmItEh6KPNzX1uT9uBh12sAff47KMGwftGZU\n" + "cw7cVdulM2qr3UTL98AuF1O2XbRE2dtET+IWXCgjnqKID11NNCzksfgEaesrpdkr\n" + "TFrB+nHvuTGCAZkwggGVAgEBMD8wMjELMAkGA1UEBhMCTkwxEzARBgNVBAgTClNv\n" + "bWUtU3RhdGUxDjAMBgNVBAoTBUJPR1VTAgkAmsFG2alr1rswCQYFKw4DAhoFAKCB\n" + "sTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xMzA0\n" + "MTkwOTU5MDdaMCMGCSqGSIb3DQEJBDEWBBS/9gqYJMaWAm8sp2Rf99Oh06aRATBS\n" + "BgkqhkiG9w0BCQ8xRTBDMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDANBggq\n" + "hkiG9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG9w0DAgIBKDANBgkqhkiG9w0BAQEF\n" + "AASBgJ8sFkzA3mksoazwIc/eNpMy20wQh1CKtiGU+xTzErkurSg8Z+7pIkod1bbq\n" + "k6tiSWnWhRzmz/YFqgGuzk+O3MyRt3YqU9nZpdaZVZxepN/p/gjQI1gfTXK+7WJ/\n" + "OcKukh/onU6eXZOD50r1RdgFPL4+lXpe0VrWjUOT3CoglnU1"; final X509Certificate certificate = getCertificate( "-----BEGIN CERTIFICATE-----\n" + "MIIB2zCCAUQCCQCawUbZqWvWuzANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJO\n" + "TDETMBEGA1UECBMKU29tZS1TdGF0ZTEOMAwGA1UEChMFQk9HVVMwHhcNMTMwNDE4\n" + "MTU0MjIwWhcNMTQwNDE4MTU0MjIwWjAyMQswCQYDVQQGEwJOTDETMBEGA1UECBMK\n" + "U29tZS1TdGF0ZTEOMAwGA1UEChMFQk9HVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0A\n" + "MIGJAoGBAKfXtOd5+eArsGTY2NG4LJQUA0Uozfn9sGfLrdF7eWo940aY4VlVBeIr\n" + "FM6jJt9BNBx3r9ZngzlkCIM8oZ6gyRf/lFI8yga2eOzr6QUf/VtVmBCOMW1BxAXf\n" + "CyMT7jK2PPpe8SXD8NQ9VvzDbP8LHFA0zAV+t/6qvlpGXJft9YnbAgMBAAEwDQYJ\n" + "KoZIhvcNAQEFBQADgYEARyzeqtZT00UOvlSz3NHSuX0AGhiOQvXei2G9XwJ9L7dX\n" + "gbeh5wCvh9j19fcmmgpiLRIeijzc19bk/bgYddrAH3+OyjBsH7RmVHMO3FXbpTNq\n" + "q91Ey/fALhdTtl20RNnbRE/iFlwoI56iiA9dTTQs5LH4BGnrK6XZK0xawfpx77k=\n" + "-----END CERTIFICATE-----"); final X509SignedMessage subject = new X509SignedMessage(signedData, signature); assertThat(subject.verify(certificate), is(true)); } @Test public void verify_smime_multipart_inetnum() throws Exception { final String signedData = ( "Content-Type: multipart/alternative;\n" + "boundary=\"_000_54F98DDECB052B4A98783EDEF1B77C4C30649470SG000708corproo_\"\n" + "Content-Language: de-DE\n" + "\n" + "--_000_54F98DDECB052B4A98783EDEF1B77C4C30649470SG000708corproo_\n" + "Content-Type: text/plain; charset=\"us-ascii\"\n" + "Content-Transfer-Encoding: quoted-printable\n" + "\n" + "inetnum: 193.0.0.0 - 193.0.0.255\n" + "netname: NETNAME\n" + "descr: Description\n" + "country: NL\n" + "admin-c: TEST-RIPE\n" + "tech-c: TEST-RIPE\n" + "status: ASSIGNED PA\n" + "mnt-by: TEST-MNT\n" + "changed: [email protected]\n" + "source: RIPE\n" + "\n" + "\n" + "--_000_54F98DDECB052B4A98783EDEF1B77C4C30649470SG000708corproo_\n" + "Content-Type: text/html; charset=\"us-ascii\"\n" + "Content-Transfer-Encoding: quoted-printable\n" + "\n" + "<html>\n" + "<head>\n" + "<meta http-equiv=3D\"Content-Type\" content=3D\"text/html; charset=3Dus-ascii\">\n" + "<meta name=3D\"Generator\" content=3D\"Microsoft Exchange Server\">\n" + "<!-- converted from rtf -->\n" + "<style><!-- .EmailQuote { margin-left: 1pt; padding-left: 4pt; border-left:#800000 2px solid; } --></style>\n" + "</head>\n" + "<body>\n" + "<font face=3D\"TheSans\" size=3D\"2\"><span style=3D\"font-size:10pt;\">\n" + "<div>inetnum: 193.0.0.0 - 193.0.0.255</div>\n" + "<div>netname: NETNAME</div>\n" + "<div>descr: Description</div>\n" + "<div>country: NL</div>\n" + "<div>admin-c: TEST-RIPE</div>\n" + "<div>tech-c: TEST-RIPE</div>\n" + "<div>status: ASSIGNED PA</div>\n" + "<div>mnt-by: TEST-MNT</div>\n" + "<div>changed: [email protected]</div>\n" + "<div>source: RIPE</div>\n" + "<div><font face=3D\"Calibri\" size=3D\"2\"><span style=3D\"font-size:11pt;\">&nbsp;</span></font></div>\n" + "</span></font>\n" + "</body>\n" + "</html>\n" + "--_000_54F98DDECB052B4A98783EDEF1B77C4C30649470SG000708corproo_\n").replaceAll("\\n", "\r\n"); final String signature = "MIIDsAYJKoZIhvcNAQcCoIIDoTCCA50CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3\n" + "DQEHAaCCAd8wggHbMIIBRAIJAJrBRtmpa9a7MA0GCSqGSIb3DQEBBQUAMDIxCzAJ\n" + "BgNVBAYTAk5MMRMwEQYDVQQIEwpTb21lLVN0YXRlMQ4wDAYDVQQKEwVCT0dVUzAe\n" + "Fw0xMzA0MTgxNTQyMjBaFw0xNDA0MTgxNTQyMjBaMDIxCzAJBgNVBAYTAk5MMRMw\n" + "EQYDVQQIEwpTb21lLVN0YXRlMQ4wDAYDVQQKEwVCT0dVUzCBnzANBgkqhkiG9w0B\n" + "AQEFAAOBjQAwgYkCgYEAp9e053n54CuwZNjY0bgslBQDRSjN+f2wZ8ut0Xt5aj3j\n" + "RpjhWVUF4isUzqMm30E0HHev1meDOWQIgzyhnqDJF/+UUjzKBrZ47OvpBR/9W1WY\n" + "EI4xbUHEBd8LIxPuMrY8+l7xJcPw1D1W/MNs/wscUDTMBX63/qq+WkZcl+31idsC\n" + "AwEAATANBgkqhkiG9w0BAQUFAAOBgQBHLN6q1lPTRQ6+VLPc0dK5fQAaGI5C9d6L\n" + "Yb1fAn0vt1eBt6HnAK+H2PX19yaaCmItEh6KPNzX1uT9uBh12sAff47KMGwftGZU\n" + "cw7cVdulM2qr3UTL98AuF1O2XbRE2dtET+IWXCgjnqKID11NNCzksfgEaesrpdkr\n" + "TFrB+nHvuTGCAZkwggGVAgEBMD8wMjELMAkGA1UEBhMCTkwxEzARBgNVBAgTClNv\n" + "bWUtU3RhdGUxDjAMBgNVBAoTBUJPR1VTAgkAmsFG2alr1rswCQYFKw4DAhoFAKCB\n" + "sTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0xMzA0\n" + "MTkxMDI2MDhaMCMGCSqGSIb3DQEJBDEWBBQcYbZgEwjIMEBgIQW5vU9ZO2vyETBS\n" + "BgkqhkiG9w0BCQ8xRTBDMAoGCCqGSIb3DQMHMA4GCCqGSIb3DQMCAgIAgDANBggq\n" + "hkiG9w0DAgIBQDAHBgUrDgMCBzANBggqhkiG9w0DAgIBKDANBgkqhkiG9w0BAQEF\n" + "AASBgGh1N+W4rzQ6n9+dvLY4jfP4lavYdcaNKNVZf0Yhx14vW5LQ1iggqtB+ZYtM\n" + "Xzs8SdGSM9FtepvHkLSYtZId0odF/eB6rY7DN3O69TQN7GhmYeICtevT3bkzL950\n" + "P3FhHeI3vHvnW1Xb+fdg46213Ym1tVw3V0caqGdp5Cw5vry5"; final X509Certificate certificate = getCertificate( "-----BEGIN CERTIFICATE-----\n" + "MIIB2zCCAUQCCQCawUbZqWvWuzANBgkqhkiG9w0BAQUFADAyMQswCQYDVQQGEwJO\n" + "TDETMBEGA1UECBMKU29tZS1TdGF0ZTEOMAwGA1UEChMFQk9HVVMwHhcNMTMwNDE4\n" + "MTU0MjIwWhcNMTQwNDE4MTU0MjIwWjAyMQswCQYDVQQGEwJOTDETMBEGA1UECBMK\n" + "U29tZS1TdGF0ZTEOMAwGA1UEChMFQk9HVVMwgZ8wDQYJKoZIhvcNAQEBBQADgY0A\n" + "MIGJAoGBAKfXtOd5+eArsGTY2NG4LJQUA0Uozfn9sGfLrdF7eWo940aY4VlVBeIr\n" + "FM6jJt9BNBx3r9ZngzlkCIM8oZ6gyRf/lFI8yga2eOzr6QUf/VtVmBCOMW1BxAXf\n" + "CyMT7jK2PPpe8SXD8NQ9VvzDbP8LHFA0zAV+t/6qvlpGXJft9YnbAgMBAAEwDQYJ\n" + "KoZIhvcNAQEFBQADgYEARyzeqtZT00UOvlSz3NHSuX0AGhiOQvXei2G9XwJ9L7dX\n" + "gbeh5wCvh9j19fcmmgpiLRIeijzc19bk/bgYddrAH3+OyjBsH7RmVHMO3FXbpTNq\n" + "q91Ey/fALhdTtl20RNnbRE/iFlwoI56iiA9dTTQs5LH4BGnrK6XZK0xawfpx77k=\n" + "-----END CERTIFICATE-----"); final X509SignedMessage subject = new X509SignedMessage(signedData, signature); assertThat(subject.verify(certificate), is(true)); } @Test public void verify_smime_multipart_person() throws Exception { final String signedData = ( "Content-Type: multipart/alternative;\n" + "\tboundary=\"Apple-Mail=_C45B4ECE-1DB6-4DDE-8B6D-4DB0BB0CDC8E\"\n" + "\n" + "\n" + "--Apple-Mail=_C45B4ECE-1DB6-4DDE-8B6D-4DB0BB0CDC8E\n" + "Content-Transfer-Encoding: 7bit\n" + "Content-Type: text/plain;\n" + "\tcharset=us-ascii\n" + "\n" + "person: First Person\n" + "address: St James Street\n" + "address: Burnley\n" + "address: UK\n" + "phone: +44 282 420469\n" + "nic-hdl: FP1-TEST\n" + "mnt-by: OWNER-MNT\n" + "changed: [email protected] 20121016\n" + "source: TEST\n" + "\n" + "\n" + "--Apple-Mail=_C45B4ECE-1DB6-4DDE-8B6D-4DB0BB0CDC8E\n" + "Content-Transfer-Encoding: 7bit\n" + "Content-Type: text/html;\n" + "\tcharset=us-ascii\n" + "\n" + "<html><head></head><body style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; \">" + "<div style=\"font-size: 13px; \">person: &nbsp;First Person</div><div style=\"font-size: 13px; \">address: St James Street</div>" + "<div style=\"font-size: 13px; \">address: Burnley</div><div style=\"font-size: 13px; \">address: UK</div><div style=\"font-size: 13px; \">" + "phone: &nbsp; +44 282 420469</div><div style=\"font-size: 13px; \">nic-hdl: FP1-TEST</div><div style=\"font-size: 13px; \">" + "mnt-by: &nbsp;OWNER-MNT</div><div style=\"font-size: 13px; \">changed: <a href=\"mailto:[email protected]\">[email protected]</a> 20121016</div>" + "<div style=\"font-size: 13px; \">source: &nbsp;TEST</div><div><br></div></body></html>\n" + "--Apple-Mail=_C45B4ECE-1DB6-4DDE-8B6D-4DB0BB0CDC8E--\n").replaceAll("\\n", "\r\n"); final String signature = "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIDtTCCA7Ew\n" + "ggMaoAMCAQICAgF8MA0GCSqGSIb3DQEBBAUAMIGFMQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9v\n" + "cmQtSG9sbGFuZDESMBAGA1UEBxMJQW1zdGVyZGFtMREwDwYDVQQKEwhSSVBFIE5DQzEMMAoGA1UE\n" + "CxMDT1BTMQwwCgYDVQQDEwNDQTIxGzAZBgkqhkiG9w0BCQEWDG9wc0ByaXBlLm5ldDAeFw0xMTEy\n" + "MDExMjM3MjNaFw0yMTExMjgxMjM3MjNaMIGAMQswCQYDVQQGEwJOTDEWMBQGA1UECBMNTm9vcmQt\n" + "SG9sbGFuZDERMA8GA1UEChMIUklQRSBOQ0MxCzAJBgNVBAsTAkRCMRcwFQYDVQQDEw5FZHdhcmQg\n" + "U2hyeWFuZTEgMB4GCSqGSIb3DQEJARYRZXNocnlhbmVAcmlwZS5uZXQwgZ8wDQYJKoZIhvcNAQEB\n" + "BQADgY0AMIGJAoGBAMNs8uEHIiGdYms93PWA4bysV3IUwsabb+fwP6ACS9Jc8OaRQkT+1oK1sfw+\n" + "yX0YloCwJXtnAYDeKHoaPNiJ+dro3GN6BiijjV72KyKThHxWmZwXeqOKVCReREVNNlkuJTvziani\n" + "cZhlr9+bxhwRho1mkEvBmxEzPZTYKl0vQpd1AgMBAAGjggExMIIBLTAJBgNVHRMEAjAAMCwGCWCG\n" + "SAGG+EIBDQQfFh1PcGVuU1NMIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUwSiXle3q\n" + "9cufhKDVUCxrEPhj/9cwgbIGA1UdIwSBqjCBp4AUviRV1EFXFxVsA8ildF9OwyDKY9ihgYukgYgw\n" + "gYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJk\n" + "YW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkGCSqG\n" + "SIb3DQEJARYMb3BzQHJpcGUubmV0ggEAMB4GA1UdEQQXMBWCE2UzLTIuc2luZ3cucmlwZS5uZXQw\n" + "DQYJKoZIhvcNAQEEBQADgYEAU5D2f5WK8AO5keVVf1/kj+wY/mRis9C7nXyhmQgrNcxzxqq+0Q7Q\n" + "mAYsNWMKDLZRemks4FfTGTmVT2SosQntXQBUoR1FGD3LQYLDZ2p1d7A6falUNu0PR8yAqJpT2Q2E\n" + "acKOic/UwHXhVorC1gbKZ5fN0dbUHqSk1zm41VQpobAxggLWMIIC0gIBATCBjDCBhTELMAkGA1UE\n" + "BhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQxEjAQBgNVBAcTCUFtc3RlcmRhbTERMA8GA1UE\n" + "ChMIUklQRSBOQ0MxDDAKBgNVBAsTA09QUzEMMAoGA1UEAxMDQ0EyMRswGQYJKoZIhvcNAQkBFgxv\n" + "cHNAcmlwZS5uZXQCAgF8MAkGBSsOAwIaBQCgggGfMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEw\n" + "HAYJKoZIhvcNAQkFMQ8XDTEzMDEwMzA4MzIwMVowIwYJKoZIhvcNAQkEMRYEFD4JhAipdRLJoj18\n" + "lGrkGzK74L00MIGdBgkrBgEEAYI3EAQxgY8wgYwwgYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1O\n" + "b29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYD\n" + "VQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkGCSqGSIb3DQEJARYMb3BzQHJpcGUubmV0AgIBfDCB\n" + "nwYLKoZIhvcNAQkQAgsxgY+ggYwwgYUxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xs\n" + "YW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAPBgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMx\n" + "DDAKBgNVBAMTA0NBMjEbMBkGCSqGSIb3DQEJARYMb3BzQHJpcGUubmV0AgIBfDANBgkqhkiG9w0B\n" + "AQEFAASBgGlxIaAcSIDw5PUw7JscCO7waLRubOusGlg7KaQOodLNAItiqU1xE8jTDmHXt97RTbRG\n" + "AXWPFW9ByXburQmxCSSxxOnIey5ta8qlP8wXQrp86aKVYO9iUWDRH8B7C1R/ApHWhRsIHadscpDn\n" + "0dZdWzSqRcNJzOJjna7eHLz8SEDFAAAAAAAA\n"; final X509Certificate certificate = getCertificate("-----BEGIN CERTIFICATE-----\n" + "MIIDsTCCAxqgAwIBAgICAXwwDQYJKoZIhvcNAQEEBQAwgYUxCzAJBgNVBAYTAk5M\n" + "MRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5kMRIwEAYDVQQHEwlBbXN0ZXJkYW0xETAP\n" + "BgNVBAoTCFJJUEUgTkNDMQwwCgYDVQQLEwNPUFMxDDAKBgNVBAMTA0NBMjEbMBkG\n" + "CSqGSIb3DQEJARYMb3BzQHJpcGUubmV0MB4XDTExMTIwMTEyMzcyM1oXDTIxMTEy\n" + "ODEyMzcyM1owgYAxCzAJBgNVBAYTAk5MMRYwFAYDVQQIEw1Ob29yZC1Ib2xsYW5k\n" + "MREwDwYDVQQKEwhSSVBFIE5DQzELMAkGA1UECxMCREIxFzAVBgNVBAMTDkVkd2Fy\n" + "ZCBTaHJ5YW5lMSAwHgYJKoZIhvcNAQkBFhFlc2hyeWFuZUByaXBlLm5ldDCBnzAN\n" + "BgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAw2zy4QciIZ1iaz3c9YDhvKxXchTCxptv\n" + "5/A/oAJL0lzw5pFCRP7WgrWx/D7JfRiWgLAle2cBgN4oeho82In52ujcY3oGKKON\n" + "XvYrIpOEfFaZnBd6o4pUJF5ERU02WS4lO/OJqeJxmGWv35vGHBGGjWaQS8GbETM9\n" + "lNgqXS9Cl3UCAwEAAaOCATEwggEtMAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8W\n" + "HU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBTBKJeV7er1\n" + "y5+EoNVQLGsQ+GP/1zCBsgYDVR0jBIGqMIGngBS+JFXUQVcXFWwDyKV0X07DIMpj\n" + "2KGBi6SBiDCBhTELMAkGA1UEBhMCTkwxFjAUBgNVBAgTDU5vb3JkLUhvbGxhbmQx\n" + "EjAQBgNVBAcTCUFtc3RlcmRhbTERMA8GA1UEChMIUklQRSBOQ0MxDDAKBgNVBAsT\n" + "A09QUzEMMAoGA1UEAxMDQ0EyMRswGQYJKoZIhvcNAQkBFgxvcHNAcmlwZS5uZXSC\n" + "AQAwHgYDVR0RBBcwFYITZTMtMi5zaW5ndy5yaXBlLm5ldDANBgkqhkiG9w0BAQQF\n" + "AAOBgQBTkPZ/lYrwA7mR5VV/X+SP7Bj+ZGKz0LudfKGZCCs1zHPGqr7RDtCYBiw1\n" + "YwoMtlF6aSzgV9MZOZVPZKixCe1dAFShHUUYPctBgsNnanV3sDp9qVQ27Q9HzICo\n" + "mlPZDYRpwo6Jz9TAdeFWisLWBspnl83R1tQepKTXObjVVCmhsA==\n" + "-----END CERTIFICATE-----"); X509SignedMessage subject = new X509SignedMessage(signedData, signature); assertThat(subject.verify(certificate), is(true)); }
X509SignedMessage { @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final X509SignedMessage that = (X509SignedMessage) o; return Objects.equals(signature, that.signature); } X509SignedMessage(final String signedData, final String signature); boolean verify(final X509Certificate certificate); boolean verifySigningTime(final DateTimeProvider dateTimeProvider); @Override boolean equals(final Object o); @Override int hashCode(); }
@Test public void isEquals() { X509SignedMessage first = new X509SignedMessage("First Test", "First Signature"); X509SignedMessage second = new X509SignedMessage("Second Test", "Second Signature"); assertThat(first.equals(first), is(true)); assertThat(first.equals(second), is(false)); }
LoggingHandlerAdapter implements LoggingHandler { @Override public void log(final StatementInfo statementInfo, final ResultInfo resultInfo) { loggerContext.logQuery(statementInfo, resultInfo); } @Autowired LoggingHandlerAdapter(final LoggerContext loggerContext); @Override void log(final StatementInfo statementInfo, final ResultInfo resultInfo); }
@Test public void log() throws Exception { subject = new LoggingHandlerAdapter(loggerContext); subject.log(statementInfo, resultInfo); verify(loggerContext, times(1)).logQuery(statementInfo, resultInfo); }
UpdateLog { public void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch) { logger.info(formatMessage(updateRequest, updateContext, update, stopwatch)); } UpdateLog(); UpdateLog(final Logger logger); void logUpdateResult(final UpdateRequest updateRequest, final UpdateContext updateContext, final Update update, final Stopwatch stopwatch); }
@Test public void logUpdateResult_create_success() { final RpslObject maintainer = RpslObject.parse("mntner: TST-MNT"); final UpdateResult updateResult = new UpdateResult(maintainer, maintainer, Action.CREATE, UpdateStatus.SUCCESS, new ObjectMessages(), 0, false); when(update.getCredentials()).thenReturn(new Credentials()); when(updateContext.createUpdateResult(update)).thenReturn(updateResult); subject.logUpdateResult(updateRequest, updateContext, update, stopwatch); verify(logger).info(matches("\\[\\s*0\\] 0[,.]000 ns UPD CREATE mntner TST-MNT \\(1\\) SUCCESS : <E0,W0,I0> AUTH - null")); } @Test public void logUpdateResult_create_success_dryRun() { final RpslObject maintainer = RpslObject.parse("mntner: TST-MNT"); final UpdateResult updateResult = new UpdateResult(maintainer, maintainer, Action.CREATE, UpdateStatus.SUCCESS, new ObjectMessages(), 0, true); when(update.getCredentials()).thenReturn(new Credentials()); when(updateContext.createUpdateResult(update)).thenReturn(updateResult); subject.logUpdateResult(updateRequest, updateContext, update, stopwatch); verify(logger).info(matches("\\[\\s*0\\] 0[,.]000 ns DRY CREATE mntner TST-MNT \\(1\\) SUCCESS : <E0,W0,I0> AUTH - null")); }
AuditLogger { public void logException(final Update update, final Throwable throwable) { final Element updateElement = createOrGetUpdateElement(update); final Element exceptionElement = doc.createElement("exception"); updateElement.appendChild(exceptionElement); exceptionElement.appendChild(keyValue("class", throwable.getClass().getName())); exceptionElement.appendChild(keyValue("message", throwable.getMessage())); final StringWriter stringWriter = new StringWriter(); final PrintWriter stackTraceWriter = new PrintWriter(stringWriter); throwable.printStackTrace(stackTraceWriter); exceptionElement.appendChild(keyValue("stacktrace", stringWriter.getBuffer().toString())); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); }
@Test public void logException() throws Exception { subject.logUpdate(update); subject.logException(update, new NullPointerException()); subject.close(); final String log = outputStream.toString("UTF-8"); assertThat(log, containsString("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates>\n" + " <update attempt=\"1\" time=\"2012-12-01 00:00:00\">\n" + " <key>[mntner] DEV-ROOT-MNT</key>\n" + " <operation>DELETE</operation>\n" + " <reason>reason</reason>\n" + " <paragraph><![CDATA[paragraph]]></paragraph>\n" + " <object><![CDATA[mntner: DEV-ROOT-MNT\n" + "]]></object>\n" + " <exception>\n" + " <class>java.lang.NullPointerException</class>\n" + " <message><![CDATA[null]]></message>\n" + " <stacktrace><![CDATA[java.lang.NullPointerException\n")); }
AuditLogger { public void logDuration(final Update update, final String duration) { final Element updateElement = createOrGetUpdateElement(update); updateElement.appendChild(keyValue("duration", duration)); } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); }
@Test public void logDuration() throws Exception { subject.logUpdate(update); subject.logDuration(update, "1 ns"); subject.close(); final String log = outputStream.toString("UTF-8"); assertThat(log, containsString("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates>\n" + " <update attempt=\"1\" time=\"2012-12-01 00:00:00\">\n" + " <key>[mntner] DEV-ROOT-MNT</key>\n" + " <operation>DELETE</operation>\n" + " <reason>reason</reason>\n" + " <paragraph><![CDATA[paragraph]]></paragraph>\n" + " <object><![CDATA[mntner: DEV-ROOT-MNT\n" + "]]></object>\n" + " <duration>1 ns</duration>\n" + " </update>\n" + " </updates>\n" + "</dbupdate>")); }
AuditLogger { public void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo) { final Element updateElement = createOrGetUpdateElement(update); final Element queryElement = doc.createElement("query"); updateElement.appendChild(queryElement); queryElement.appendChild(keyValue("sql", statementInfo.getSql())); final Element paramsElement = doc.createElement("params"); queryElement.appendChild(paramsElement); for (final Map.Entry<Integer, Object> entry : statementInfo.getParameters().entrySet()) { final Element param = keyValue("param", entry.getValue()); param.setAttribute("idx", String.valueOf(entry.getKey())); paramsElement.appendChild(param); } final Element resultsElement = doc.createElement("results"); queryElement.appendChild(resultsElement); int rowNum = 1; for (final List<String> row : resultInfo.getRows()) { final Element rowElement = doc.createElement("row"); rowElement.setAttribute("idx", String.valueOf(rowNum++)); resultsElement.appendChild(rowElement); int colNum = 0; for (final String column : row) { final Element columnElement = keyValue("column", column); columnElement.setAttribute("idx", String.valueOf(colNum++)); rowElement.appendChild(columnElement); } } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); }
@Test public void logQuery() throws Exception { final Map<Integer, Object> params = Maps.newTreeMap(); params.put(1, "p1"); params.put(2, 22); final List<List<String>> rows = Arrays.asList( Arrays.asList("c1-1", "c1-2"), Arrays.asList("c2-1", "c2-2")); final StatementInfo statementInfo = new StatementInfo("sql", params); final ResultInfo resultInfo = new ResultInfo(rows); subject.logUpdate(update); subject.logQuery(update, statementInfo, resultInfo); subject.close(); final String log = outputStream.toString("UTF-8"); assertThat(log, containsString("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates>\n" + " <update attempt=\"1\" time=\"2012-12-01 00:00:00\">\n" + " <key>[mntner] DEV-ROOT-MNT</key>\n" + " <operation>DELETE</operation>\n" + " <reason>reason</reason>\n" + " <paragraph><![CDATA[paragraph]]></paragraph>\n" + " <object><![CDATA[mntner: DEV-ROOT-MNT\n" + "]]></object>\n" + " <query>\n" + " <sql><![CDATA[sql]]></sql>\n" + " <params>\n" + " <param idx=\"1\">p1</param>\n" + " <param idx=\"2\">22</param>\n" + " </params>\n" + " <results>\n" + " <row idx=\"1\">\n" + " <column idx=\"0\"><![CDATA[c1-1]]></column>\n" + " <column idx=\"1\"><![CDATA[c1-2]]></column>\n" + " </row>\n" + " <row idx=\"2\">\n" + " <column idx=\"0\"><![CDATA[c2-1]]></column>\n" + " <column idx=\"1\"><![CDATA[c2-2]]></column>\n" + " </row>\n" + " </results>\n" + " </query>\n" + " </update>\n" + " </updates>\n" + "</dbupdate>")); }
AuditLogger { public void close() { try { writeAndClose(); } catch (IOException e) { LOGGER.error("IO Exception", e); } } AuditLogger(final DateTimeProvider dateTimeProvider, final OutputStream outputStream); @SuppressWarnings("ThrowableResultOfMethodCallIgnored" /* Throwable is logged */) void log(final Message message, @Nullable final Throwable t); void logDryRun(); void logBatchUpdate(); void logUpdate(final Update update); void logPreparedUpdate(final PreparedUpdate preparedUpdate); void logException(final Update update, final Throwable throwable); void logDuration(final Update update, final String duration); void logQuery(final Update update, final StatementInfo statementInfo, final ResultInfo resultInfo); void logString(Update update, String element, String auditMessage); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logAction(final Update update, final Action action); void logStatus(final Update update, final UpdateStatus status); void logMessage(final Update update, final Message message); void logMessage(final Update update, final RpslAttribute attribute, final Message message); void close(); }
@Test public void empty() throws Exception { subject.close(); assertThat(outputStream.toString("UTF-8"), is("" + "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" + "<dbupdate created=\"2012-12-01 00:00:00\">\n" + " <messages/>\n" + " <updates/>\n" + "</dbupdate>\n" )); verify(outputStream, times(1)).close(); }
LoggerContext { public void checkDirs() { getCreatedDir(baseDir); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }
@Test public void checkDirs() { subject.remove(); final File f = new File(folder.getRoot(), "test/"); subject.setBaseDir(f.getAbsolutePath()); subject.checkDirs(); subject.init("folder"); assertThat(f.exists(), is(true)); }
LoggerContext { public File getFile(final String filename) { final Context tempContext = getContext(); return getFile(tempContext.baseDir, tempContext.nextFileNumber(), filename); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }
@Test public void getFile() throws Exception { assertThat(subject.getFile("test.txt").getName(), is("001.test.txt.gz")); assertThat(subject.getFile("test.txt").getName(), is("002.test.txt.gz")); assertThat(subject.getFile("test.txt").getName(), is("003.test.txt.gz")); }
LoggerContext { public File log(final String name, final LogCallback callback) { final File file = getFile(name); OutputStream os = null; try { os = getOutputstream(file); callback.log(os); } catch (IOException e) { throw new IllegalStateException("Unable to write to " + file.getAbsolutePath(), e); } finally { closeOutputStream(os); } return file; } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }
@Test public void log() throws Exception { final File file = subject.log("test.txt", new LogCallback() { @Override public void log(final OutputStream outputStream) throws IOException { outputStream.write("test".getBytes()); } }); final InputStream is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(new File(folder.getRoot(), "001.test.txt.gz")))); final String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8); assertThat(file.getName(), is("001.test.txt.gz")); assertThat(contents, is("test")); } @Test(expected = IllegalStateException.class) public void log_throws_exception() { subject.log("filename", new LogCallback() { @Override public void log(final OutputStream outputStream) throws IOException { throw new IOException(); } }); }
LoggerContext { public void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo) { final Context ctx = context.get(); if (ctx != null && ctx.currentUpdate != null) { ctx.auditLogger.logQuery(ctx.currentUpdate, statementInfo, resultInfo); } } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }
@Test public void log_query_no_context_should_not_fail() { subject.logQuery(new StatementInfo("sql"), new ResultInfo(Collections.<List<String>>emptyList())); }
LoggerContext { public void logUpdateCompleted(final UpdateContainer updateContainer) { logUpdateComplete(updateContainer, null); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }
@Test(expected = IllegalStateException.class) public void logUpdateComplete_no_context_should_fail() { subject.logUpdateCompleted(update); }
LoggerContext { public void logException(final UpdateContainer updateContainer, final Throwable throwable) { getContext().auditLogger.logException(updateContainer.getUpdate(), throwable); } @Autowired LoggerContext(final DateTimeProvider dateTimeProvider); void setBaseDir(final String baseDir); @PostConstruct void start(); void checkDirs(); void init(final String folderName); void remove(); File getFile(final String filename); File log(final String name, final LogCallback callback); void log(final Message message); void log(final Message message, final Throwable t); void logUpdateStarted(final Update update); void logUpdateCompleted(final UpdateContainer updateContainer); void logUpdateFailed(final UpdateContainer updateContainer, final Throwable throwable); void logPreparedUpdate(PreparedUpdate preparedUpdate); void logQuery(final StatementInfo statementInfo, final ResultInfo resultInfo); void logDryRun(); void logBatchUpdate(); void logAction(final UpdateContainer updateContainer, final Action action); void logAuthenticationStrategy(Update update, String authenticationStrategy, Collection<RpslObject> maintainers); void logCredentials(Update update); void logString(final Update update, final String element, final String auditMessage); void logStatus(final UpdateContainer updateContainer, final UpdateStatus action); void logMessage(final UpdateContainer updateContainer, final Message message); void logMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); void logException(final UpdateContainer updateContainer, final Throwable throwable); void logMessages(final UpdateContainer updateContainer, ObjectMessages objectMessages); }
@Test public void logException() throws IOException { final String content = "mntner: DEV-ROOT-MNT"; final RpslObject object = RpslObject.parse(content); when(update.getOperation()).thenReturn(Operation.DELETE); when(update.getParagraph()).thenReturn(new Paragraph(content)); when(update.getSubmittedObject()).thenReturn(object); subject.logUpdateStarted(update); subject.logUpdateFailed(update, new NullPointerException()); subject.remove(); final InputStream is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(new File(folder.getRoot(), "000.audit.xml.gz")))); final String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8); assertThat(contents, containsString("" + " <exception>\n" + " <class>java.lang.NullPointerException</class>\n" + " <message><![CDATA[null]]></message>\n" + " <stacktrace><![CDATA[java.lang.NullPointerException\n")); }
MailMessageLogCallback implements LogCallback { @Override public void log(final OutputStream outputStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { message.writeTo(baos); String messageData = new String( baos.toByteArray(), "UTF-8" ); String filtered = PasswordFilter.filterPasswordsInContents(messageData); outputStream.write(filtered.getBytes("UTF-8")); } catch (MessagingException e) { LOGGER.warn("Writing message", e); } } MailMessageLogCallback(final Message message); @Override void log(final OutputStream outputStream); }
@Test public void log() throws IOException, MessagingException { final MailMessageLogCallback subject = new MailMessageLogCallback(message); subject.log(outputStream); verify(outputStream).write("".getBytes()); } @Test public void log_never_throws_exception() throws IOException, MessagingException { final MailMessageLogCallback subject = new MailMessageLogCallback(message); doThrow(MessagingException.class).when(message).writeTo(outputStream); subject.log(outputStream); verify(outputStream).write("".getBytes()); }
IterableTransformer implements Iterable<T> { @Override public Iterator<T> iterator() { return new IteratorTransformer(head); } IterableTransformer(final Iterable<? extends T> wrap); IterableTransformer<T> setHeader(T... header); IterableTransformer<T> setHeader(Collection<T> header); abstract void apply(final T input, final Deque<T> result); @Override Iterator<T> iterator(); }
@Test public void empty_input_test() { final Iterable subject = getSimpleIterable(); final Iterator<Integer> iterator = subject.iterator(); assertFalse(iterator.hasNext()); } @Test(expected = NullPointerException.class) public void null_test() { final Iterable<Integer> subject = getSimpleIterable(1, null, 2, null); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); assertTrue(iterator.hasNext()); assertNull(iterator.next()); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertNull(iterator.next()); assertFalse(iterator.hasNext()); } @Test public void simple_test() { final Iterable<Integer> subject = getSimpleIterable(1,2,3); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(3)); assertFalse(iterator.hasNext()); } @Test public void iterable_resettable() { final Iterable<Integer> subject = getSimpleIterable(1,2,3); Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(1)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(3)); assertFalse(iterator.hasNext()); } @Test public void odd_filter_test() { final Iterable<Integer> subject = getOddFilteringIterable(1, 2, 3); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertFalse(iterator.hasNext()); } @Test public void multiple_results_filter_test() { final Iterable<Integer> subject = getOddFilteringEvenDoublingIterable(1, 2, 3); final Iterator<Integer> iterator = subject.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertTrue(iterator.hasNext()); assertThat(iterator.next(), is(2)); assertFalse(iterator.hasNext()); }
GrsImporter implements DailyScheduledTask { @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") public void run() { if (!grsImportEnabled) { LOGGER.info("GRS import is not enabled"); return; } List<Future> futures = grsImport(defaultSources, false); for (Future future : futures) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.error(e.getMessage(), e); } } } @Autowired GrsImporter(final GrsSourceImporter grsSourceImporter, final GrsSource[] grsSources); @Value("${grs.import.enabled}") void setGrsImportEnabled(final boolean grsImportEnabled); @Value("${grs.import.sources}") void setDefaultSources(final String defaultSources); @Override @Scheduled(cron = "0 0 0 * * *") @SchedulerLock(name = "GrsImporter") void run(); List<Future> grsImport(String sources, final boolean rebuild); }
@Test public void run() { subject = spy(subject); subject.setGrsImportEnabled(false); subject.run(); verify(subject, times(0)).grsImport(anyString(), anyBoolean()); }
MailGatewaySmtp implements MailGateway { @Override public void sendEmail(final String to, final ResponseMessage responseMessage) { sendEmail(to, responseMessage.getSubject(), responseMessage.getMessage(), responseMessage.getReplyTo()); } @Autowired MailGatewaySmtp(final LoggerContext loggerContext, final MailConfiguration mailConfiguration, final JavaMailSender mailSender); @Override void sendEmail(final String to, final ResponseMessage responseMessage); @Override void sendEmail(final String to, final String subject, final String text, @Nullable final String replyTo); }
@Test public void sendResponse() throws Exception { subject.sendEmail("to", "subject", "test", ""); verify(mailSender, times(1)).send(any(MimeMessagePreparator.class)); } @Test public void sendResponse_disabled() throws Exception { ReflectionTestUtils.setField(subject, "outgoingMailEnabled", false); subject.sendEmail("to", "subject", "test", ""); verifyZeroInteractions(mailSender); } @Test public void send_invoked_only_once_on_permanent_negative_response() { Mockito.doAnswer(invocation -> { throw new SendFailedException("550 rejected: mail rejected for policy reasons"); }).when(mailSender).send(any(MimeMessagePreparator.class)); try { subject.sendEmail("to", "subject", "test", ""); fail(); } catch (Exception e) { assertThat(e, instanceOf(SendFailedException.class)); verify(mailSender, times(1)).send(any(MimeMessagePreparator.class)); } } @Test public void sendResponseAndCheckForReplyTo() throws Exception { final String replyToAddress = "[email protected]"; setExpectReplyToField(replyToAddress); subject.sendEmail("to", "subject", "test", replyToAddress); } @Test public void sendResponseAndCheckForEmptyReplyTo() throws Exception { final String replyToAddress = ""; setExpectReplyToField(replyToAddress); subject.sendEmail("to", "subject", "test", ""); }
OverrideCredential implements Credential { @Override public String toString() { if (!overrideValues.isPresent()){ return "OverrideCredential{NOT_VALID}"; } if (StringUtils.isBlank(overrideValues.get().getRemarks())){ return String.format("OverrideCredential{%s,FILTERED}", overrideValues.get().getUsername()); } return String.format("OverrideCredential{%s,FILTERED,%s}", overrideValues.get().getUsername(), overrideValues.get().getRemarks()); } private OverrideCredential(final String value, final Optional<OverrideValues> overrideValues); Optional<OverrideValues> getOverrideValues(); @Override boolean equals(final Object o); @Override int hashCode(); @Override String toString(); static OverrideCredential parse(final String value); }
@Test public void testToString() { assertThat(OverrideCredential.parse("").toString(), is("OverrideCredential{NOT_VALID}")); assertThat(OverrideCredential.parse("user").toString(), is("OverrideCredential{NOT_VALID}")); assertThat(OverrideCredential.parse("user,password").toString(), is("OverrideCredential{user,FILTERED}")); assertThat(OverrideCredential.parse("user, password").toString(), is("OverrideCredential{user,FILTERED}")); assertThat(OverrideCredential.parse("user, password, remarks").toString(), is("OverrideCredential{user,FILTERED,remarks}")); assertThat(OverrideCredential.parse("user,password,remarks,more remarks").toString(), is("OverrideCredential{user,FILTERED,remarks,more remarks}")); }
LegacyAutnum { public boolean contains(final CIString autnum) { return cachedLegacyAutnums.contains(autnum); } @Autowired LegacyAutnum(final LegacyAutnumDao legacyAutnumDao); @PostConstruct synchronized void init(); boolean contains(final CIString autnum); int getTotal(); }
@Test public void contains() { assertThat(subject.contains(ciString("AS100")), is(false)); assertThat(subject.contains(ciString("AS102")), is(true)); }
OrganisationId extends AutoKey { @Override public String toString() { return new StringBuilder() .append("ORG-") .append(getSpace().toUpperCase()) .append(getIndex()) .append("-") .append(getSuffix()) .toString(); } OrganisationId(final String space, final int index, final String suffix); @Override String toString(); }
@Test public void string() { final OrganisationId subject = new OrganisationId("SAT", 1, "RIPE"); assertThat(subject.toString(), is("ORG-SAT1-RIPE")); }
NicHandle extends AutoKey { public static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes) { if (StringUtils.startsWithIgnoreCase(nicHdl, "AUTO-")) { throw new NicHandleParseException("Primary key generation request cannot be parsed as NIC-HDL: " + nicHdl); } final Matcher matcher = NIC_HDL_PATTERN.matcher(nicHdl.trim()); if (!matcher.matches()) { throw new NicHandleParseException("Invalid NIC-HDL: " + nicHdl); } final String characterSpace = matcher.group(1); final int index = getIndex(matcher.group(2)); final String suffix = getSuffix(matcher.group(3), source, countryCodes); return new NicHandle(characterSpace, index, suffix); } NicHandle(final String space, final Integer index, final String suffix); static NicHandle parse(final String nicHdl, final CIString source, final Set<CIString> countryCodes); @Override String toString(); }
@Test public void parse_auto() { try { NicHandle.parse("AUTO-1", source, countryCodes); fail("AUTO- should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Primary key generation request cannot be parsed as NIC-HDL: AUTO-1")); } } @Test public void parse_auto_lowercase() { try { NicHandle.parse("auto-1", source, countryCodes); fail("AUTO- should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Primary key generation request cannot be parsed as NIC-HDL: auto-1")); } } @Test public void parse_empty() { try { NicHandle.parse("", source, countryCodes); fail("Empty should not be supported as NIC-HDL"); } catch (NicHandleParseException e) { assertThat(e.getMessage(), is("Invalid NIC-HDL: ")); } } @Test(expected = NicHandleParseException.class) public void parse_space_too_long() { NicHandle.parse("SPACE", source, countryCodes); } @Test(expected = NicHandleParseException.class) public void parse_suffix_too_long() { NicHandle.parse("DW-VERYLONGSUFFIX", source, countryCodes); } @Test(expected = NicHandleParseException.class) public void parse_suffix_invalid() { NicHandle.parse("DW-SOMETHING", source, countryCodes); } @Test public void equal_null() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals(null)); } @Test public void equal_otherClass() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals("")); } @Test public void equal_self() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertTrue(nicHandle.equals(nicHandle)); } @Test public void equal_same() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertTrue(nicHandle.equals(NicHandle.parse("DW", source, countryCodes))); } @Test public void equal_different() { final NicHandle nicHandle = NicHandle.parse("DW", source, countryCodes); assertFalse(nicHandle.equals(NicHandle.parse("AB", source, countryCodes))); } @Test public void hashCode_check() { NicHandle.parse("DW", source, countryCodes).hashCode(); }
UpdateContext { public Messages getGlobalMessages() { return globalMessages; } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); }
@Test public void no_warnings() { assertThat(subject.getGlobalMessages().getAllMessages(), hasSize(0)); }
UpdateContext { public boolean hasErrors(final UpdateContainer updateContainer) { return getOrCreateContext(updateContainer).objectMessages.hasErrors(); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); }
@Test public void no_errors() { final RpslObject mntner = RpslObject.parse(MAINTAINER); final Update update = new Update(new Paragraph(MAINTAINER), Operation.DELETE, Lists.<String>newArrayList(), mntner); final PreparedUpdate preparedUpdate = new PreparedUpdate(update, null, mntner, Action.DELETE); assertThat(subject.hasErrors(preparedUpdate), is(false)); }
UpdateContext { public void status(final UpdateContainer updateContainer, final UpdateStatus status) { getOrCreateContext(updateContainer).status = status; loggerContext.logStatus(updateContainer, status); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); }
@Test public void status() { final String content = "mntner: DEV-ROOT-MNT"; final RpslObject mntner = RpslObject.parse(content); final Update update = new Update(new Paragraph(content), Operation.DELETE, Lists.<String>newArrayList(), mntner); final PreparedUpdate preparedUpdate = new PreparedUpdate(update, null, mntner, Action.DELETE); subject.status(preparedUpdate, UpdateStatus.FAILED_AUTHENTICATION); assertThat(subject.getStatus(preparedUpdate), is(UpdateStatus.FAILED_AUTHENTICATION)); }
UpdateContext { public Ack createAck() { final List<UpdateResult> updateResults = Lists.newArrayList(); for (final Update update : contexts.keySet()) { updateResults.add(createUpdateResult(update)); } final List<Paragraph> ignoredParagraphs = getIgnoredParagraphs(); return new Ack(updateResults, ignoredParagraphs); } UpdateContext(final LoggerContext loggerContext); boolean isDryRun(); void dryRun(); int getNrSinceRestart(); boolean isBatchUpdate(); void setBatchUpdate(); void addDnsCheckResponse(final DnsCheckRequest request, final DnsCheckResponse response); void addSsoTranslationResult(final String username, final String uuid); boolean hasSsoTranslationResult(String usernameOrUuid); @CheckForNull String getSsoTranslationResult(final String usernameOrUuid); @CheckForNull DnsCheckResponse getCachedDnsCheckResponse(final DnsCheckRequest dnsCheckRequest); void addMessage(final UpdateContainer updateContainer, final Message message); void addMessage(final UpdateContainer updateContainer, final RpslAttribute attribute, final Message message); ObjectMessages getMessages(final UpdateContainer updateContainer); void setAction(final UpdateContainer updateContainer, final Action action); Action getAction(final UpdateContainer updateContainer); void setOrigin(final UpdateContainer updateContainer, final Origin origin); Origin getOrigin(final UpdateContainer updateContainer); PreparedUpdate getPreparedUpdate(final UpdateContainer updateContainer); boolean hasErrors(final UpdateContainer updateContainer); int getErrorCount(final UpdateContainer updateContainer); void status(final UpdateContainer updateContainer, final UpdateStatus status); UpdateStatus getStatus(final UpdateContainer updateContainer); void subject(final UpdateContainer updateContainer, final Subject subject); Subject getSubject(final UpdateContainer updateContainer); void updateInfo(final UpdateContainer updateContainer, final RpslObjectUpdateInfo updateInfo); RpslObjectUpdateInfo getUpdateInfo(final UpdateContainer updateContainer); void versionId(final UpdateContainer updateContainer, final int versionId); int getVersionId(final UpdateContainer updateContainer); void setPreparedUpdate(final PreparedUpdate preparedUpdate); void ignore(final Paragraph paragraph); void addGlobalMessage(final Message message); Messages getGlobalMessages(); String printGlobalMessages(); void addGeneratedKey(final UpdateContainer updateContainer, final CIString keyPlaceholder, final GeneratedKey generatedKey); void failedUpdate(final UpdateContainer updateContainer, final Message... messages); @CheckForNull GeneratedKey getGeneratedKey(final CIString keyPlaceholder); Ack createAck(); UpdateResult createUpdateResult(final UpdateContainer updateContainer); void prepareForReattempt(final UpdateContainer update); void setUserSession(final UserSession userSession); UserSession getUserSession(); void setClientCertificate(final Optional<X509CertificateWrapper> clientCertificate); Optional<X509CertificateWrapper> getClientCertificate(); }
@Test public void createAck() { final RpslObject object = RpslObject.parse(MAINTAINER); final Update delete = new Update(new Paragraph(MAINTAINER), Operation.DELETE, Lists.<String>newArrayList(), object); subject.setAction(delete, Action.DELETE); final Update deleteWithError = new Update(new Paragraph(MAINTAINER), Operation.DELETE, Lists.<String>newArrayList(), object); subject.setAction(deleteWithError, Action.DELETE); subject.addMessage(deleteWithError, UpdateMessages.objectInUse(object)); subject.addMessage(deleteWithError, UpdateMessages.filteredNotAllowed()); subject.status(deleteWithError, UpdateStatus.FAILED); final Update update = new Update(new Paragraph(MAINTAINER), Operation.UNSPECIFIED, Lists.<String>newArrayList(), object); subject.setAction(update, Action.MODIFY); final Update updateWithError = new Update(new Paragraph(MAINTAINER), Operation.UNSPECIFIED, Lists.<String>newArrayList(), object); subject.setAction(updateWithError, Action.MODIFY); subject.addMessage(updateWithError, UpdateMessages.filteredNotAllowed()); subject.status(updateWithError, UpdateStatus.FAILED); final String updateMessage = "ignore"; final Paragraph paragraphIgnore = new Paragraph(updateMessage); subject.ignore(paragraphIgnore); final Ack ack = subject.createAck(); assertThat(ack.getNrFound(), is(4)); assertThat(ack.getNrProcessedsuccessfully(), is(2)); assertThat(ack.getNrDelete(), is(1)); assertThat(ack.getNrProcessedErrrors(), is(2)); assertThat(ack.getNrDeleteErrors(), is(1)); assertThat(ack.getIgnoredParagraphs(), contains(paragraphIgnore)); assertThat(ack.getUpdateStatus(), is(UpdateStatus.FAILED)); final List<UpdateResult> failedUpdates = ack.getFailedUpdates(); assertThat(failedUpdates, hasSize(2)); final Iterable<Message> errors = failedUpdates.get(0).getErrors(); assertThat(errors, contains(UpdateMessages.objectInUse(object), UpdateMessages.filteredNotAllowed())); }
ContentWithCredentials { public List<Credential> getCredentials() { return credentials; } ContentWithCredentials(final String content); ContentWithCredentials(final String content, final Charset charset); ContentWithCredentials(final String content, final List<Credential> credentials); ContentWithCredentials(final String content, final List<Credential> credentials, final Charset charset); String getContent(); List<Credential> getCredentials(); Charset getCharset(); }
@Test(expected = UnsupportedOperationException.class) public void credentials_are_immutable() { final ContentWithCredentials subject = new ContentWithCredentials("test", Lists.newArrayList(credential)); subject.getCredentials().add(mock(Credential.class)); }
PreparedUpdate implements UpdateContainer { @Override public Update getUpdate() { return update; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void getUpdate() { assertThat(subject.getUpdate(), is(update)); }
PreparedUpdate implements UpdateContainer { public Paragraph getParagraph() { return update.getParagraph(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void getParagraph() { subject.getParagraph(); verify(update).getParagraph(); }
PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getReferenceObject() { if (originalObject != null) { return originalObject; } return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void getOriginalObject() { assertThat(subject.getReferenceObject(), is(originalObject)); }
PreparedUpdate implements UpdateContainer { @Nullable public RpslObject getUpdatedObject() { return updatedObject; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void getUpdatedObject() { assertThat(subject.getUpdatedObject(), is(updatedObject)); }
PreparedUpdate implements UpdateContainer { public Action getAction() { return action; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void getAction() { assertThat(subject.getAction(), is(Action.MODIFY)); }
PreparedUpdate implements UpdateContainer { public Credentials getCredentials() { return update.getCredentials(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void getCredentials() { subject.getCredentials(); verify(update).getCredentials(); }
PreparedUpdate implements UpdateContainer { public ObjectType getType() { return update.getType(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void getType() { subject.getType(); verify(update).getType(); }
PreparedUpdate implements UpdateContainer { public String getKey() { return updatedObject.getKey().toString(); } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void getKey() { assertThat(subject.getFormattedKey(), is("[mntner] DEV-TST-MNT")); }
PreparedUpdate implements UpdateContainer { public Set<CIString> getNewValues(final AttributeType attributeType) { final Set<CIString> newValues = updatedObject.getValuesForAttribute(attributeType); if (originalObject != null) { newValues.removeAll(originalObject.getValuesForAttribute(attributeType)); } return newValues; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void newValues_create() { subject = new PreparedUpdate( update, null, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), Action.CREATE); final Set<CIString> newValues = subject.getNewValues(AttributeType.MNT_BY); assertThat(newValues, contains(ciString("DEV-MNT-1"), ciString("dev-MNT-2"))); } @Test public void newValues_modify_added() { subject = new PreparedUpdate( update, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n"), RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), Action.MODIFY); final Set<CIString> newValues = subject.getNewValues(AttributeType.MNT_BY); assertThat(newValues, contains(ciString("dev-MNT-2"))); } @Test public void newValues_modify_added_unavailable_attribute() { subject = new PreparedUpdate( update, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n"), RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), Action.MODIFY); final Set<CIString> newValues = subject.getNewValues(AttributeType.MNT_IRT); assertThat(newValues, hasSize(0)); } @Test public void newValues_modify_removed() { subject = new PreparedUpdate( update, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-2\n"), Action.MODIFY); final Set<CIString> newValues = subject.getNewValues(AttributeType.MNT_BY); assertThat(newValues, hasSize(0)); } @Test public void newValues_modify_delete() { subject = new PreparedUpdate( update, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n"), RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n"), Action.DELETE); final Set<CIString> newValues = subject.getNewValues(AttributeType.MNT_BY); assertThat(newValues, hasSize(0)); }
PreparedUpdate implements UpdateContainer { public Set<CIString> getDifferences(final AttributeType attributeType) { Set<CIString> differences = updatedObject.getValuesForAttribute(attributeType); if (originalObject != null && !Action.DELETE.equals(action)) { differences = Sets.symmetricDifference(differences, originalObject.getValuesForAttribute(attributeType)); } return differences; } PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action); PreparedUpdate(final Update update, @Nullable final RpslObject originalObject, @Nullable final RpslObject updatedObject, final Action action, final OverrideOptions overrideOptions); @Override Update getUpdate(); Paragraph getParagraph(); boolean hasOriginalObject(); @Nullable RpslObject getReferenceObject(); @Nullable RpslObject getUpdatedObject(); RpslObject getSubmittedObject(); Action getAction(); Credentials getCredentials(); boolean isOverride(); OverrideOptions getOverrideOptions(); ObjectType getType(); String getKey(); String getFormattedKey(); Set<CIString> getNewValues(final AttributeType attributeType); Set<CIString> getDifferences(final AttributeType attributeType); @Override String toString(); }
@Test public void differentValues_create() { subject = new PreparedUpdate( update, null, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), Action.CREATE); final Set<CIString> differences = subject.getDifferences(AttributeType.MNT_BY); assertThat(differences, contains(ciString("DEV-MNT-1"), ciString("dev-MNT-2"))); } @Test public void differentValues_modify_added() { subject = new PreparedUpdate( update, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n"), RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), Action.MODIFY); final Set<CIString> differences = subject.getDifferences(AttributeType.MNT_BY); assertThat(differences, contains(ciString("dev-MNT-2"))); } @Test public void differentValues_modify_added_unavailable_attribute() { subject = new PreparedUpdate( update, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n"), RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), Action.MODIFY); final Set<CIString> differences = subject.getDifferences(AttributeType.MNT_IRT); assertThat(differences, hasSize(0)); } @Test public void differentValues_modify_removed() { subject = new PreparedUpdate( update, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-2\n"), Action.MODIFY); final Set<CIString> differences = subject.getDifferences(AttributeType.MNT_BY); assertThat(differences, contains(ciString("DEV-MNT-1"))); } @Test public void differentValues_modify_delete() { subject = new PreparedUpdate( update, RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: DEV-MNT-1\n" + "mnt-by: DEV-MNT-2\n"), Action.DELETE); final Set<CIString> differences = subject.getDifferences(AttributeType.MNT_BY); assertThat(differences, contains(ciString("DEV-MNT-1"), ciString("DEV-MNT-2"))); }
UpdateMessages { public static Message authenticationFailed(final RpslObject object, final AttributeType attributeType, final Iterable<RpslObject> candidates) { final CharSequence joined = LIST_JOINED.join( Iterables.transform(candidates,input -> input == null ? "" : input.getKey())); return new Message(Type.ERROR, "" + "Authorisation for [%s] %s failed\n" + "using \"%s:\"\n" + (joined.length() == 0 ? "no valid maintainer found\n" : "not authenticated by: %s"), object.getType().getName(), object.getKey(), attributeType.getName(), joined); } private UpdateMessages(); static String print(final Message message); static Message invalidKeywordsFound(final CharSequence subject); static Message allKeywordsIgnored(); static Message unexpectedError(); static Message filteredNotAllowed(); static Message unrecognizedSource(final CharSequence source); static Message operationNotAllowedForKeyword(final Keyword keyword, final Operation operation); static Message objectNotFound(final CharSequence key); static Message objectMismatch(final CharSequence key); static Message objectInUse(final RpslObject object); static Message nonexistantMntRef(final CharSequence organisation, final CharSequence mntRef); static Message nicHandleNotAvailable(final CharSequence nicHandle); static Message referenceNotFound(final CharSequence reference); static Message invalidReference(final ObjectType objectType, final CharSequence key); static Message updateIsIdentical(); static Message unknownObjectReferenced(final CharSequence value); static Message multipleReasonsSpecified(final Operation operation); static Message referencedObjectMissingAttribute(final ObjectType objectType, final CharSequence objectName, final AttributeType attributeType); static Message referencedObjectMissingAttribute(final ObjectType objectType, final CharSequence objectName, final ObjectType viaType, final CharSequence viaName, final AttributeType attributeType); static Message invalidIpv4Address(final CharSequence value); static Message invalidIpv6Address(final CharSequence value); static Message invalidRouteRange(final CharSequence value); static Message invalidRoutePrefix(final CharSequence type); static Message authenticationFailed(final RpslObject object, final AttributeType attributeType, final Iterable<RpslObject> candidates); static Message parentAuthenticationFailed(final RpslObject object, final AttributeType attributeType, final Iterable<RpslObject> candidates); static Message reservedNameUsed(); static Message reservedNameUsed(final CharSequence name); static Message reservedPrefixUsed(final CharSequence prefix, final ObjectType type); static Message newKeywordAndObjectExists(); static Message invalidMaintainerForOrganisationType(final CharSequence orgType); static Message cantChangeOrgAttribute(); static Message cantRemoveOrgAttribute(); static Message cantChangeOrgName(); static Message countryNotRecognised(final CharSequence country); static Message asblockIsMaintainedByRipe(); static Message asblockParentAlreadyExists(); static Message asblockAlreadyExists(); static Message asblockChildAlreadyExists(); static Message intersectingAsblockAlreadyExists(); static Message languageNotRecognised(final CharSequence language); static Message nameChanged(); static Message statusChange(); static Message adminMaintainerRemoved(); static Message authorisationRequiredForSetStatus(final CharSequence status); static Message authorisationRequiredForAttrChange(final AttributeType attributeType); static Message canOnlyBeChangedByRipeNCC(final AttributeType attributeType); static Message canOnlyBeChangedinLirPortal(final AttributeType attributeType); static Message orgAttributeMissing(); static Message wrongOrgType(final Set<OrgType> allowedOrgTypes); static Message incorrectParentStatus(final Messages.Type messageType, final ObjectType type, final CharSequence parentStatus); static Message incorrectChildStatus(final Messages.Type messageType, final CharSequence givenStatus, final CharSequence childStatus, final CharSequence moreSpecificObject); static Message intersectingRange(final Interval<?> intersectingRange); static Message inetnumStatusLegacy(); static Message createFirstPersonMntnerForOrganisation(); static Message maintainerNotFound(final CharSequence maintainer); static Message cantChangeAssignmentSize(); static Message attributeAssignmentSizeNotAllowed(); static Message assignmentSizeTooSmall(final int prefixLength); static Message assignmentSizeTooLarge(final int prefixLength); static Message prefixTooSmall(final int minimumPrefixLength); static Message tooManyAggregatedByLirInHierarchy(); static Message statusRequiresAuthorization(final CharSequence currentStatus); static Message deleteWithStatusRequiresAuthorization(final CharSequence currentStatus); static Message invalidChildPrefixLength(); static Message invalidParentEntryForInterval(final IpInterval s); static Message invalidPrefixLength(final IpInterval ipInterval, final int assignmentSize); static Message membersNotSupportedInReferencedSet(final CharSequence asName); static Message dnsCheckTimeout(); static Message dnsCheckMessageParsingError(); static Message dnsCheckError(); static Message authorisationRequiredForEnumDomain(); static Message lessSpecificDomainFound(final CharSequence existing); static Message moreSpecificDomainFound(final CharSequence existing); static Message hostNameMustEndWith(final CharSequence s); static Message glueRecordMandatory(final CharSequence s); static Message invalidGlueForEnumDomain(final CharSequence s); static Message authorisationRequiredForDeleteRsMaintainedObject(); static Message authorisationRequiredForChangingRipeMaintainer(); static Message poemRequiresPublicMaintainer(); static Message poeticFormRequiresDbmMaintainer(); static Message tooManyPasswordsSpecified(); static Message overrideIgnored(); static Message noValidUpdateFound(); static Message multipleOverridePasswords(); static Message overrideNotAllowedForOrigin(final Origin origin); static Message overrideOnlyAllowedByDbAdmins(); static Message overrideAuthenticationUsed(); static Message overrideAuthenticationFailed(); static Message overrideOptionInvalid(final CharSequence option); static Message overrideOriginalNotFound(final int id); static Message overrideOriginalMismatch(final int id, final ObjectType type, final CharSequence key); static Message ripeMntnerUpdatesOnlyAllowedFromWithinNetwork(); static Message parentObjectNotFound(final CharSequence parent); static Message autokeyAlreadyDefined(final CharSequence value); static Message autokeyForX509KeyCertsOnly(); static Message noParentAsBlockFound(final CharSequence asNumber); static Message certificateNotYetValid(final CharSequence name); static Message certificateHasExpired(final CharSequence name); static Message publicKeyHasExpired(final CharSequence name); static Message publicKeyIsRevoked(final CharSequence name); static Message cannotCreateOutOfRegionObject(final ObjectType objectType); static Message sourceNotAllowed(final ObjectType objectType, final CharSequence source); static Message cannotUseReservedAsNumber(final Long asNumber); static Message autnumNotFoundInDatabase(final Long asNumber); static Message messageSignedMoreThanOneHourAgo(); static Message eitherSimpleOrComplex(final ObjectType objectType, final CharSequence simple, final CharSequence complex); static Message neitherSimpleOrComplex(final ObjectType objectType, final CharSequence simple, final CharSequence complex); static Message diffNotSupported(); static Message abuseMailboxRequired(final CharSequence key, final ObjectType objectType); static Message abuseCPersonReference(); static Message abuseMailboxReferenced(final CharSequence role, final ObjectType objectType); static Message keyNotFound(final String keyId); static Message keyInvalid(final String keyId); static Message abuseCNoLimitWarning(); static Message duplicateAbuseC(final CharSequence abuseC, final CharSequence organisation); static Message abuseContactNotRemovable(); static Message selfReferenceError(final AttributeType attributeType); static Message commentInSourceNotAllowed(); static Message dryRunNotice(); static Message ripeAccessAccountUnavailable(final CharSequence username); static Message ripeAccessServerUnavailable(); static Message statusCannotBeRemoved(); static Message sponsoringOrgChanged(); static Message sponsoringOrgAdded(); static Message sponsoringOrgRemoved(); static Message sponsoringOrgNotLIR(); static Message sponsoringOrgNotAllowedWithStatus(final CharSequence status); static Message sponsoringOrgMustBePresent(); static Message valueChangedDueToLatin1Conversion(); static Message valueChangedDueToLatin1Conversion(final String attributeName); static Message valueChangedDueToPunycodeConversion(); static Message oldPasswordsRemoved(); static Message creatingRipeMaintainerForbidden(); static Message updatingRipeMaintainerSSOForbidden(); static Message originIsMissing(); static Message netnameCannotBeChanged(); static Message multipleUserMntBy(final Collection<CIString> userMntners); static Message changedAttributeRemoved(); static Message mntRoutesAttributeRemoved(); static Message mntLowerAttributeRemoved(); static Message emailAddressCannotBeUsed(final CIString value); static Message inconsistentOrgNameFormatting(); static Message shortFormatAttributeReplaced(); static Message bogonPrefixNotAllowed(final String prefix); static Message maximumObjectSizeExceeded(final long size, final long maximumSize); }
@Test public void authentication_failed_empty_list() { RpslObject object = RpslObject.parse("person: New Person\nnic-hdl: AUTO-1"); final Message result = UpdateMessages.authenticationFailed(object, AttributeType.MNT_BY, Lists.<RpslObject>newArrayList()); assertThat(result.toString(), is( "Authorisation for [person] AUTO-1 failed\nusing \"mnt-by:\"\nno valid maintainer found\n")); } @Test public void authentication_failed_with_list() { RpslObject object = RpslObject.parse("person: New Person\nnic-hdl: AUTO-1\nmnt-by: maintainer"); RpslObject mntner = RpslObject.parse("mntner: maintainer"); final Message result = UpdateMessages.authenticationFailed(object, AttributeType.MNT_BY, Lists.newArrayList(mntner)); assertThat(result.toString(), is( "Authorisation for [person] AUTO-1 failed\nusing \"mnt-by:\"\nnot authenticated by: maintainer")); }
ObjectKey { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final ObjectKey that = (ObjectKey) o; return Objects.equals(objectType, that.objectType) && Objects.equals(pkey, that.pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void equals() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.equals(null), is(false)); assertThat(subject.equals(""), is(false)); assertThat(subject.equals(subject), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "key")), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "KEY")), is(true)); assertThat(subject.equals(new ObjectKey(ObjectType.MNTNER, "key2")), is(false)); assertThat(subject.equals(new ObjectKey(ObjectType.ORGANISATION, "key")), is(false)); }
ObjectKey { @Override public int hashCode() { return Objects.hash(objectType, pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void hash() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.hashCode(), is(new ObjectKey(ObjectType.MNTNER, "key").hashCode())); assertThat(subject.hashCode(), not(is(new ObjectKey(ObjectType.ORGANISATION, "key").hashCode()))); } @Test public void hash_uppercase() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.hashCode(), is(new ObjectKey(ObjectType.MNTNER, "KEY").hashCode())); }
ObjectKey { @Override public String toString() { return String.format("[%s] %s", objectType.getName(), pkey); } ObjectKey(final ObjectType objectType, final String pkey); ObjectKey(final ObjectType objectType, final CIString pkey); ObjectType getObjectType(); CIString getPkey(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void string() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "key"); assertThat(subject.toString(), is("[mntner] key")); } @Test public void string_uppercase() { final ObjectKey subject = new ObjectKey(ObjectType.MNTNER, "KeY"); assertThat(subject.toString(), is("[mntner] KeY")); }
Notification { public String getEmail() { return email; } Notification(final String email); void add(final Type type, final PreparedUpdate update, UpdateContext updateContext); String getEmail(); Set<Update> getUpdates(final Type type); boolean has(final Type type); }
@Test public void getEmail() { assertThat(subject.getEmail(), is("[email protected]")); }