src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ToKeysFunction implements Function<ResponseObject, ResponseObject> { @Override public ResponseObject apply(final @Nullable ResponseObject input) { if (!(input instanceof RpslObject)) { return input; } final RpslObject rpslObject = (RpslObject) input; final List<RpslAttribute> attributes = rpslObject.getAttributes(); final List<RpslAttribute> newAttributes = new ArrayList<>(attributes.size()); final ObjectTemplate template = ObjectTemplate.getTemplate(rpslObject.getType()); final RpslAttribute typeAttribute = rpslObject.getTypeAttribute(); final Set<AttributeType> keyAttributes = template.getKeyAttributes(); if (keyAttributes.size() == 1 && keyAttributes.contains(typeAttribute.getType()) && !template.isSet()) { newAttributes.add(typeAttribute); } else { for (final RpslAttribute attribute : attributes) { final AttributeType attributeType = attribute.getType(); if (keyAttributes.contains(attributeType) || (template.isSet() && (AttributeType.MEMBERS.equals(attributeType) || AttributeType.MP_MEMBERS.equals(attributeType)))) { newAttributes.add(attribute); } } } return new RpslAttributes(newAttributes); } @Override ResponseObject apply(final @Nullable ResponseObject input); }
@Test public void apply_resonseObject() { final ResponseObject object = new MessageObject("text"); final ResponseObject response = subject.apply(object); assertThat(response, is(object)); } @Test public void apply_inetnum() { RpslObject rpslObject = RpslObject.parse("" + "inetnum: 10.0.0.0\n" + "mnt-by: BAR\n" + "source: QUX\n" + "abuse-mailbox: [email protected]"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "inetnum: 10.0.0.0\n")); } @Test public void keys_route() { RpslObject rpslObject = RpslObject.parse("" + "route: 193.0.0.0/21\n" + "descr: RIPE-NCC\n" + "origin: AS3333\n" + "mnt-by: RIPE-NCC-MNT\n" + "source: RIPE # Filtered"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "route: 193.0.0.0/21\n" + "origin: AS3333\n")); } @Test public void keys_as_set() { RpslObject rpslObject = RpslObject.parse("" + "as-set: AS-TEST\n" + "descr: Description\n" + "members: AS2602, AS42909, AS51966\n" + "tech-c: PN-RIPE\n" + "admin-c: PN-RIPE\n" + "mnt-by: TEST-MNT\n" + "source: RIPE # Filtered"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "as-set: AS-TEST\n" + "members: AS2602, AS42909, AS51966\n")); }
RipeGrsSource extends GrsSource { @Override void handleObjects(final File file, final ObjectHandler handler) throws IOException { FileInputStream is = null; try { is = new FileInputStream(file); final BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(is), StandardCharsets.UTF_8)); handleLines(reader, new LineHandler() { @Override public void handleLines(final List<String> lines) { handler.handle(lines); } }); } finally { IOUtils.closeQuietly(is); } } @Autowired RipeGrsSource( @Value("${grs.import.ripe.source:}") final String source, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader, @Value("${grs.import.ripe.download:}") final String download); }
@Test public void handleObjects() throws Exception { final File file = new File(getClass().getResource("/grs/ripe.test.gz").toURI()); subject.handleObjects(file, objectHandler); assertThat(objectHandler.getObjects(), hasSize(0)); assertThat(objectHandler.getLines(), hasSize(2)); assertThat(objectHandler.getLines(), contains((List<String>) Lists.newArrayList( "as-block: AS1877 - AS1901\n", "descr: RIPE NCC ASN block\n", "remarks: These AS Numbers are further assigned to network\n", "remarks: operators in the RIPE NCC service region. AS\n", "remarks: assignment policy is documented in:\n", "remarks: <http: "remarks: RIPE NCC members can request AS Numbers using the\n", "remarks: form available in the LIR Portal or at:\n", "remarks: <http: "org: ORG-NCC1-RIPE\n", "admin-c: DUMY-RIPE\n", "tech-c: DUMY-RIPE\n", "mnt-by: RIPE-DBM-MNT\n", "mnt-lower: RIPE-NCC-HM-MNT\n", "changed: [email protected] 20090529\n", "source: RIPE\n", "remarks: ****************************\n", "remarks: * THIS OBJECT IS MODIFIED\n", "remarks: * Please note that all data that is generally regarded as personal\n", "remarks: * data has been removed from this object.\n", "remarks: * To view the original object, please query the RIPE Database at:\n", "remarks: * http: "remarks: ****************************\n"), Lists.newArrayList( "as-block: AS2043 - AS2043\n", "descr: RIPE NCC ASN block\n", "remarks: These AS Numbers are further assigned to network\n", "remarks: operators in the RIPE NCC service region. AS\n", "remarks: assignment policy is documented in:\n", "remarks: <http: "remarks: RIPE NCC members can request AS Numbers using the\n", "remarks: form available in the LIR Portal or at:\n", "remarks: <http: "org: ORG-NCC1-RIPE\n", "admin-c: DUMY-RIPE\n", "tech-c: DUMY-RIPE\n", "mnt-by: RIPE-DBM-MNT\n", "mnt-lower: RIPE-NCC-HM-MNT\n", "changed: [email protected] 20090529\n", "source: RIPE\n", "remarks: ****************************\n", "remarks: * THIS OBJECT IS MODIFIED\n", "remarks: * Please note that all data that is generally regarded as personal\n", "remarks: * data has been removed from this object.\n", "remarks: * To view the original object, please query the RIPE Database at:\n", "remarks: * http: "remarks: ****************************\n") )); }
RelatedIrtDecorator implements PrimaryObjectDecorator { @Override public boolean appliesToQuery(final Query query) { return query.isReturningIrt(); } @Autowired RelatedIrtDecorator(final HierarchyLookupIpv4 hierarchyLookupIpv4, final HierarchyLookupIpv6 hierarchyLookupIpv6); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }
@Test public void appliesToQuery_empty() { assertThat(subject.appliesToQuery(Query.parse("foo")), is(false)); } @Test public void appliesToQuery_no_irt() { assertThat(subject.appliesToQuery(Query.parse("-T inetnum 10.0.0.0")), is(false)); } @Test public void appliesToQuery_capital_C() { assertThat(subject.appliesToQuery(Query.parse("-C -T inetnum 10.0.0.0")), is(false)); } @Test public void appliesToQuery_irt() { assertThat(subject.appliesToQuery(Query.parse("-c -T inetnum 10.0.0.0")), is(true)); }
RelatedIrtDecorator implements PrimaryObjectDecorator { @Override public Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject) { for (final HierarchyLookup hierarchyLookup : hierarchyLookups) { if (hierarchyLookup.supports(rpslObject)) { return hierarchyLookup.getReferencedIrtsInHierarchy(rpslObject); } } return Collections.emptyList(); } @Autowired RelatedIrtDecorator(final HierarchyLookupIpv4 hierarchyLookupIpv4, final HierarchyLookupIpv6 hierarchyLookupIpv6); @Override boolean appliesToQuery(final Query query); @Override Collection<RpslObjectInfo> decorate(final Query query, final RpslObject rpslObject); }
@Test public void decorate_not_supported() { final RpslObject rpslObject = RpslObject.parse("poem:RIPE"); final Collection<RpslObjectInfo> infos = subject.decorate(Query.parse("RIPE"), rpslObject); verify(hierarchyLookupIpv4, times(1)).supports(rpslObject); verify(hierarchyLookupIpv6, times(1)).supports(rpslObject); assertThat(infos, hasSize(0)); } @Test public void decorate_inetnum() { final RpslObject rpslObject = RpslObject.parse("inetnum:0.0.0.0"); final RpslObjectInfo rpslObjectInfo = new RpslObjectInfo(0, ObjectType.IRT, "IRT"); final List<RpslObjectInfo> result = Arrays.asList(rpslObjectInfo); when(hierarchyLookupIpv4.supports(rpslObject)).thenReturn(true); when(hierarchyLookupIpv4.getReferencedIrtsInHierarchy(rpslObject)).thenReturn(result); final Collection<RpslObjectInfo> infos = subject.decorate(Query.parse("0.0.0.0"), rpslObject); verify(hierarchyLookupIpv4, times(1)).supports(rpslObject); assertThat(infos, contains(rpslObjectInfo)); } @Test public void decorate_inet6num() { final RpslObject rpslObject = RpslObject.parse("inetnum: ::0"); final RpslObjectInfo rpslObjectInfo = new RpslObjectInfo(0, ObjectType.IRT, "IRT"); final List<RpslObjectInfo> result = Arrays.asList(rpslObjectInfo); when(hierarchyLookupIpv6.supports(rpslObject)).thenReturn(true); when(hierarchyLookupIpv6.getReferencedIrtsInHierarchy(rpslObject)).thenReturn(result); final Collection<RpslObjectInfo> infos = subject.decorate(Query.parse("::0"), rpslObject); verify(hierarchyLookupIpv6, times(1)).supports(rpslObject); assertThat(infos, contains(rpslObjectInfo)); }
HierarchyLookupIpv4 extends HierarchyLookup<Ipv4Resource, Ipv4Entry> { @Override public ObjectType getSupportedType() { return ObjectType.INETNUM; } @Autowired HierarchyLookupIpv4(final Ipv4Tree ipv4Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv4Resource createResource(final String key); }
@Test public void getSupportedType() { assertThat(subject.getSupportedType(), is(ObjectType.INETNUM)); }
AfrinicGrsSource extends GrsSource { @Override public void handleObjects(final File file, final ObjectHandler handler) throws IOException { FileInputStream is = null; try { is = new FileInputStream(file); final BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(is), StandardCharsets.UTF_8)); handleLines(reader, new LineHandler() { @Override public void handleLines(final List<String> lines) { handler.handle(lines); } }); } finally { IOUtils.closeQuietly(is); } } @Autowired AfrinicGrsSource( @Value("${grs.import.afrinic.source:}") final String source, final SourceContext sourceContext, final DateTimeProvider dateTimeProvider, final AuthoritativeResourceData authoritativeResourceData, final Downloader downloader, @Value("${grs.import.afrinic.download:}") final String download); @Override void acquireDump(final Path path); @Override void handleObjects(final File file, final ObjectHandler handler); }
@Test public void handleObjects() throws Exception { final File file = new File(getClass().getResource("/grs/afrinic.test.gz").toURI()); subject.handleObjects(file, objectHandler); assertThat(objectHandler.getObjects(), hasSize(0)); assertThat(objectHandler.getLines(), hasSize(5)); assertThat(objectHandler.getLines().get(0), contains( "as-block: AS30980 - AS30980\n", "descr: AfriNIC ASN block\n", "remarks: These AS Numbers are further assigned to network\n" + " operators in the AfriNIC service region. AS\n" + " assignment policy is documented in:\n" + " <http: " AfriNIC members can request AS Numbers using the\n" + " form located at:\n" + " http: "org: ORG-AFNC1-AFRINIC\n", "admin-c: TEAM-AFRINIC\n", "tech-c: TEAM-AFRINIC\n", "mnt-by: AFRINIC-HM-MNT\n", "mnt-lower: AFRINIC-HM-MNT\n", "changed: [email protected] 20050101\n", "changed: [email protected] 20050205\n", "remarks: data has been transferred from RIPE Whois Database 20050221\n", "source: AFRINIC\n")); assertThat(objectHandler.getLines().get(1), hasItem("inetnum: 196.207.3.172 - 196.207.3.175\n")); assertThat(objectHandler.getLines().get(2), hasItem("inetnum: 196.204.208.1 - 196.204.208.255\n")); assertThat(objectHandler.getLines().get(3), hasItem("as-block: AS30720 - AS30979\n")); assertThat(objectHandler.getLines().get(4), hasItem("as-block: AS31000 - AS31743\n")); }
HierarchyLookupIpv4 extends HierarchyLookup<Ipv4Resource, Ipv4Entry> { @Override public Ipv4Resource createResource(final String key) { return Ipv4Resource.parse(key); } @Autowired HierarchyLookupIpv4(final Ipv4Tree ipv4Tree, final RpslObjectDao rpslObjectDao); @Override ObjectType getSupportedType(); @Override Ipv4Resource createResource(final String key); }
@Test public void createResource() { final String resource = "0.0.0.0"; assertThat(subject.createResource(resource), is(Ipv4Resource.parse(resource))); }
SyntaxFilterFunction implements Function<ResponseObject, Iterable<? extends ResponseObject>> { @Override public Iterable<? extends ResponseObject> apply(final ResponseObject input) { if (input instanceof RpslObject) { final RpslObject object = (RpslObject) input; if (!validSyntax(object) && isValidSyntaxQuery) { return Arrays.asList(new MessageObject(QueryMessages.invalidSyntax(object.getKey()))); } else if (validSyntax(object) && !isValidSyntaxQuery) { return Arrays.asList(new MessageObject(QueryMessages.validSyntax(object.getKey()))); } } return Collections.singletonList(input); } SyntaxFilterFunction(final boolean validSyntaxQuery); @Override Iterable<? extends ResponseObject> apply(final ResponseObject input); }
@Test public void validSyntax_valid_flag() { final RpslObject object = RpslObject.parse("" + "mntner: TST-MNT\n" + "descr: description\n" + "admin-c: TEST-RIPE\n" + "mnt-by: TST-MNT\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$fU9ZMQN9$QQtm3kRqZXWAuLpeOiLN7. # update\n" + "source: TEST"); final Iterable<? extends ResponseObject> result = validSyntaxFilterFunction.apply(object); final ResponseObject responseObject = Iterables.find(result, input -> input instanceof RpslObject); assertThat(responseObject, is(not(nullValue()))); } @Test public void invalidSyntax_valid_flag() { final RpslObject object = RpslObject.parse("" + "person: Admin Person\n" + "address: Admin Road\n" + "address: Town\n" + "address: UK\n" + "phone: [email protected]\n" + "nic-hdl: tst-ripe\n" + "mnt-by: TST-MNT\n" + "source: TEST"); final Iterable<? extends ResponseObject> result = validSyntaxFilterFunction.apply(object); assertThat(Iterables.size(result), is(1)); assertThat(Iterables.getFirst(result, null), is(new MessageObject(QueryMessages.invalidSyntax("tst-ripe")))); } @Test public void invalidSyntax_novalid_flag() { final RpslObject object = RpslObject.parse("" + "person: Admin Person\n" + "address: Admin Road\n" + "address: Town\n" + "address: UK\n" + "phone: [email protected]\n" + "nic-hdl: tst-ripe\n" + "mnt-by: TST-MNT\n" + "source: TEST"); final Iterable<? extends ResponseObject> result = novalidSyntaxFilterFunction.apply(object); final ResponseObject responseObject = Iterables.find(result, input -> input instanceof RpslObject); assertThat(responseObject, is(not(nullValue()))); }
ToShorthandFunction implements Function<ResponseObject, ResponseObject> { @Override public ResponseObject apply(final @Nullable ResponseObject input) { if (!(input instanceof RpslObject)) { return input; } final RpslObject rpslObject = (RpslObject) input; final List<RpslAttribute> attributes = rpslObject.getAttributes(); final List<RpslAttribute> newAttributes = new ArrayList<>(attributes.size()); for (RpslAttribute attribute : attributes) { final AttributeType type = attribute.getType(); final String key = type != null ? "*" + type.getFlag() : attribute.getKey(); newAttributes.add(new RpslAttribute(key, RpslAttributeFilter.getValueForShortHand(attribute.getValue()))); } return new RpslObject(rpslObject, newAttributes); } @Override ResponseObject apply(final @Nullable ResponseObject input); }
@Test public void apply_resonseObject() { final ResponseObject object = new MessageObject("text"); final ResponseObject response = subject.apply(object); assertThat(response, is(object)); } @Test public void apply_mntner() { RpslObject rpslObject = RpslObject.parse("" + "mntner: FOO\n" + "mnt-by: BAR\n" + "source: QUX"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "*mt: FOO\n" + "*mb: BAR\n" + "*so: QUX\n")); } @Test public void apply_unknown() { RpslObject rpslObject = RpslObject.parse("" + "mntner:FOO\n" + "IREALLYDUNNO:BAR\n" + "source:QUX"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "*mt: FOO\n" + "ireallydunno: BAR\n" + "*so: QUX\n")); } @Test public void apply_can_be_parsed_back() { RpslObject rpslObject = RpslObject.parse("" + "mntner:FOO\n" + "IREALLYDUNNO:BAR\n" + "source:QUX"); final ResponseObject response = subject.apply(rpslObject); assertThat(RpslObject.parse(response.toString()), is(rpslObject)); } @Test public void shorthand_empty_attribute() { RpslObject rpslObject = RpslObject.parse("" + "mntner: FOO\n" + "address:\n" + "source: QUX"); final ResponseObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "*mt: FOO\n" + "*ad:\n" + "*so: QUX\n")); }
SystemInfoQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return query.isSystemInfo(); } @Autowired SystemInfoQueryExecutor(final ApplicationVersion applicationVersion, final SourceContext sourceContext); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }
@Test public void supports_version_ignore_case() { assertThat(subject.supports(Query.parse("-q Version")), is(true)); } @Test public void supports_types_ignore_case() { assertThat(subject.supports(Query.parse("-q Types")), is(true)); } @Test public void supports_sources_ignore_case() { assertThat(subject.supports(Query.parse("-q Sources")), is(true)); }
FilterAuthFunction implements FilterFunction { @Override @Nonnull public RpslObject apply(final RpslObject rpslObject) { final List<RpslAttribute> authAttributes = rpslObject.findAttributes(AttributeType.AUTH); if (authAttributes.isEmpty()) { return rpslObject; } final Map<RpslAttribute, RpslAttribute> replace = Maps.newHashMap(); final boolean authenticated = isMntnerAuthenticated(rpslObject); for (final RpslAttribute authAttribute : authAttributes) { final Iterator<String> authIterator = SPACE_SPLITTER.split(authAttribute.getCleanValue()).iterator(); final String passwordType = authIterator.next().toUpperCase(); if (authenticated) { if (passwordType.equals("SSO")) { final String username = crowdClient.getUsername(authIterator.next()); replace.put(authAttribute, new RpslAttribute(AttributeType.AUTH, "SSO " + username)); } } else { if (passwordType.endsWith("-PW") || passwordType.equals("SSO")) { replace.put(authAttribute, new RpslAttribute(AttributeType.AUTH, passwordType + FILTERED_APPENDIX)); } } } if (replace.isEmpty()) { return rpslObject; } else { if (!authenticated) { RpslObjectFilter.addFilteredSourceReplacement(rpslObject, replace); } return new RpslObjectBuilder(rpslObject).replaceAttributes(replace).get(); } } FilterAuthFunction(final List<String> passwords, final String token, final SsoTokenTranslator ssoTokenTranslator, final CrowdClient crowdClient, final RpslObjectDao rpslObjectDao); FilterAuthFunction(); @Override @Nonnull RpslObject apply(final RpslObject rpslObject); static final Splitter SPACE_SPLITTER; static final String FILTERED_APPENDIX; }
@Test public void apply_irt() { final RpslObject rpslObject = RpslObject.parse("" + "irt: DEV-IRT\n" + "auth: MD5-PW $1$YmPozTxJ$s3eGZRVrKVGdSDTeEZJu\n" + "source: RIPE" ); final RpslObject response = subject.apply(rpslObject); assertThat(response, is(RpslObject.parse("" + "irt: DEV-IRT\n" + "auth: MD5-PW # Filtered\n" + "source: RIPE # Filtered\n"))); } @Test public void apply_no_md5() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "auth: value\n" + "source: RIPE" ); final RpslObject response = subject.apply(rpslObject); assertThat(response, is(rpslObject)); } @Test public void apply_md5_filtered() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "auth: MD5-PW $1$YmPozTxJ$s3eGZRVrKVGdSDTeEZJu "auth: MD5-PW $1$YmPozTxJ$s3eGZRVrKVGdSDTeEZJu "source: RIPE" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "auth: MD5-PW # Filtered\n" + "auth: MD5-PW # Filtered\n" + "source: RIPE # Filtered\n")); } @Test public void apply_md5_filtered_incorrect_password() { subject = new FilterAuthFunction(Collections.singletonList("test0"), null, ssoTokenTranslator, crowdClient, rpslObjectDao); final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" + "auth: MD5-PW $1$5XCg9Q1W$O7g9bgeJPkpea2CkBGnz/0 #test1\n" + "auth: MD5-PW $1$ZjlXZmWO$VKyuYp146Vx5b1.398zgH/ #test2\n" + "source: RIPE" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "auth: MD5-PW # Filtered\n" + "auth: MD5-PW # Filtered\n" + "auth: MD5-PW # Filtered\n" + "source: RIPE # Filtered\n")); } @Test public void apply_md5_unfiltered() { subject = new FilterAuthFunction(Collections.singletonList("test1"), null, ssoTokenTranslator, crowdClient, rpslObjectDao); final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" + "auth: MD5-PW $1$5XCg9Q1W$O7g9bgeJPkpea2CkBGnz/0 #test1\n" + "auth: MD5-PW $1$ZjlXZmWO$VKyuYp146Vx5b1.398zgH/ #test2\n" + "source: RIPE" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" + "auth: MD5-PW $1$5XCg9Q1W$O7g9bgeJPkpea2CkBGnz/0 #test1\n" + "auth: MD5-PW $1$ZjlXZmWO$VKyuYp146Vx5b1.398zgH/ #test2\n" + "source: RIPE\n")); } @Test public void apply_sso_filtered() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: SSO-MNT\n" + "auth: SSO T2hOz8tlmka5lxoZQxzC1Q00\n" + "source: RIPE"); final RpslObject result = subject.apply(rpslObject); assertThat(result.toString(), is("" + "mntner: SSO-MNT\n" + "auth: SSO # Filtered\n" + "source: RIPE # Filtered\n")); } @Test public void apply_sso_different_uuid_filtered() { final UserSession userSession = new UserSession("[email protected]", "Test User", true, "2033-01-30T16:38:27.369+11:00"); userSession.setUuid("76cab38b73eb-ac91-4336-94f3-d06e5500"); when(ssoTokenTranslator.translateSsoToken("token")).thenReturn(userSession); when(crowdClient.getUsername("d06e5500-ac91-4336-94f3-76cab38b73eb")).thenReturn("[email protected]"); final RpslObject rpslObject = RpslObject.parse("" + "mntner: SSO-MNT\n" + "auth: SSO d06e5500-ac91-4336-94f3-76cab38b73eb\n" + "source: RIPE"); subject = new FilterAuthFunction(Collections.<String>emptyList(), "token", ssoTokenTranslator, crowdClient, rpslObjectDao); final RpslObject result = subject.apply(rpslObject); assertThat(result.toString(), is( "mntner: SSO-MNT\n" + "auth: SSO # Filtered\n" + "source: RIPE # Filtered\n")); } @Test public void apply_sso_unfiltered() { final UserSession userSession = new UserSession("[email protected]", "Test User", true, "2033-01-30T16:38:27.369+11:00"); userSession.setUuid("d06e5500-ac91-4336-94f3-76cab38b73eb"); when(ssoTokenTranslator.translateSsoToken("token")).thenReturn(userSession); when(crowdClient.getUsername("d06e5500-ac91-4336-94f3-76cab38b73eb")).thenReturn("[email protected]"); final RpslObject rpslObject = RpslObject.parse("" + "mntner: SSO-MNT\n" + "auth: SSO d06e5500-ac91-4336-94f3-76cab38b73eb\n" + "source: RIPE"); subject = new FilterAuthFunction(Collections.<String>emptyList(), "token", ssoTokenTranslator, crowdClient, rpslObjectDao); final RpslObject result = subject.apply(rpslObject); assertThat(result.toString(), is( "mntner: SSO-MNT\n" + "auth: SSO [email protected]\n" + "source: RIPE\n")); } @Test(expected = CrowdClientException.class) public void crowd_client_exception() throws Exception { final UserSession userSession = new UserSession("[email protected]", "Test User", true, "2033-01-30T16:38:27.369+11:00"); userSession.setUuid("d06e5500-ac91-4336-94f3-76cab38b73eb"); when(ssoTokenTranslator.translateSsoToken("token")).thenReturn(userSession); when(crowdClient.getUsername("d06e5500-ac91-4336-94f3-76cab38b73eb")).thenThrow(CrowdClientException.class); subject = new FilterAuthFunction(Collections.<String>emptyList(), "token", ssoTokenTranslator, crowdClient, rpslObjectDao); subject.apply(RpslObject.parse("" + "mntner: SSO-MNT\n" + "auth: SSO d06e5500-ac91-4336-94f3-76cab38b73eb\n" + "source: RIPE")); } @Test public void crowd_client_exception_server_down() throws Exception { final UserSession userSession = new UserSession("[email protected]", "Test User", true, "2033-01-30T16:38:27.369+11:00"); userSession.setUuid("T2hOz8tlmka5lxoZQxzC1Q00"); when(ssoTokenTranslator.translateSsoToken("token")).thenThrow(CrowdClientException.class); when(crowdClient.getUsername("T2hOz8tlmka5lxoZQxzC1Q00")).thenThrow(CrowdClientException.class); subject = new FilterAuthFunction(Collections.<String>emptyList(), "token", ssoTokenTranslator, crowdClient, rpslObjectDao); final RpslObject result = subject.apply( RpslObject.parse("" + "mntner: SSO-MNT\n" + "auth: SSO T2hOz8tlmka5lxoZQxzC1Q00\n" + "source: RIPE")); assertThat(result.toString(), is("" + "mntner: SSO-MNT\n" + "auth: SSO # Filtered\n" + "source: RIPE # Filtered\n")); } @Test public void sso_token_translator_exception() throws Exception { when(ssoTokenTranslator.translateSsoToken(any(String.class))).thenThrow(CrowdClientException.class); subject = new FilterAuthFunction(Collections.<String>emptyList(), "token", ssoTokenTranslator, crowdClient, rpslObjectDao); final RpslObject result = subject.apply( RpslObject.parse("" + "mntner: SSO-MNT\n" + "auth: SSO T2hOz8tlmka5lxoZQxzC1Q00\n" + "source: RIPE")); assertThat(result.toString(), is("" + "mntner: SSO-MNT\n" + "auth: SSO # Filtered\n" + "source: RIPE # Filtered\n")); }
SystemInfoQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { final Query.SystemInfoOption systemInfoOption = query.getSystemInfoOption(); final String responseString; switch (systemInfoOption) { case VERSION: responseString = "% whois-server-" + applicationVersion.getVersion(); break; case TYPES: { final StringBuilder builder = new StringBuilder(); for (ObjectType type : ORDERED_TYPES) { builder.append(type.getName()); builder.append('\n'); } responseString = builder.toString(); break; } case SOURCES: { StringBuilder builder = new StringBuilder(); for (final CIString source : sourceContext.getAllSourceNames()) { builder.append(String.format("%s:3:N:0-0\n", source)); if (sourceContext.getNonauthSource() != null && sourceContext.getWhoisMasterSource().getName().equals(source)) { builder.append(String.format("%s:3:N:0-0\n", sourceContext.getNonauthSource().getName())); } } responseString = builder.toString(); break; } default: throw new QueryException(QueryCompletionInfo.PARAMETER_ERROR, QueryMessages.malformedQuery()); } responseHandler.handle(new MessageObject(responseString)); } @Autowired SystemInfoQueryExecutor(final ApplicationVersion applicationVersion, final SourceContext sourceContext); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }
@Test public void types_query() { final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-q types"), responseHandler); Iterator<? extends ResponseObject> iterator = responseHandler.getResponseObjects().iterator(); String responseString = iterator.next().toString(); assertThat(iterator.hasNext(), is(false)); for (ObjectType objectType : ObjectType.values()) { assertThat(responseString, containsString(objectType.getName())); } } @Test public void types_query_invalid_argument() { try { subject.execute(Query.parse("-q invalid"), new CaptureResponseHandler()); fail("expected QueryException to be thrown"); } catch (QueryException qe) { assertThat(qe.getMessage(), containsString(QueryMessages.malformedQuery().toString())); } } @Test public void version_query() { final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-q version"), responseHandler); Iterator<? extends ResponseObject> iterator = responseHandler.getResponseObjects().iterator(); String responseString = iterator.next().toString(); assertThat(iterator.hasNext(), is(false)); assertThat(responseString, containsString("% whois-server")); } @Test public void sources_query() { when(sourceContext.getAllSourceNames()).thenReturn(ciSet("RIPE")); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-q sources"), responseHandler); Iterator<? extends ResponseObject> iterator = responseHandler.getResponseObjects().iterator(); String responseString = iterator.next().toString(); assertThat(iterator.hasNext(), is(false)); assertThat(responseString, containsString("RIPE:3:N:0-0\n")); }
HelpQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return !query.hasOptions() && query.isHelp(); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }
@Test public void supports_help() { assertThat(subject.supports(Query.parse("help")), is(true)); } @Test public void supports_help_ignore_case() { assertThat(subject.supports(Query.parse("HeLp")), is(true)); } @Test public void supports_help_with_other_argument() { assertThat(subject.supports(Query.parse("help invalid")), is(false)); } @Test public void supports_help_with_other_flags() { assertThat(subject.supports(Query.parse("help -T person")), is(false)); }
HelpQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { responseHandler.handle(HELP_RESPONSE); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }
@Test public void getResponse() { final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(null, responseHandler); final String helpText = responseHandler.getResponseObjects().get(0).toString(); assertThat(helpText, containsString("NAME")); assertThat(helpText, containsString("DESCRIPTION")); for (final QueryFlag queryFlag : QueryFlag.values()) { if (!HelpQueryExecutor.SKIPPED.contains(queryFlag)) { assertThat(helpText, containsString(queryFlag.toString())); } } for (final String line : Splitter.on('\n').split(helpText)) { if (line.length() > 0) { assertThat(line, startsWith("%")); } } assertThat(helpText, containsString("RIPE Database Reference Manual")); }
FilterPersonalDecorator implements ResponseDecorator { @Override public Iterable<? extends ResponseObject> decorate(final Query query, final Iterable<? extends ResponseObject> input) { if (query.hasOption(QueryFlag.SHOW_PERSONAL) || !query.hasOption(QueryFlag.NO_PERSONAL)) { return input; } return new IterableTransformer<ResponseObject>(input) { @Override public void apply(ResponseObject input, Deque<ResponseObject> result) { if (!(input instanceof RpslObject) || !PERSONAL.contains(((RpslObject) input).getType())) { result.add(input); } } }.setHeader(new MessageObject(QueryMessages.noPersonal())); } @Override Iterable<? extends ResponseObject> decorate(final Query query, final Iterable<? extends ResponseObject> input); }
@Test public void no_personal_filters_personal_objects() { List<ResponseObject> input = Lists.newArrayList(relatedMessage, maintainer, role, person, abuseRole); final Query query = Query.parse(String.format("%s test", QueryFlag.NO_PERSONAL)); final Set<ResponseObject> response = Sets.newLinkedHashSet(subject.decorate(query, input)); assertThat(response, hasSize(3)); assertThat(response, contains(filterMessage, relatedMessage, maintainer)); } @Test public void no_personal_message_only() { List<ResponseObject> input = Lists.newArrayList(filterMessage); final Query query = Query.parse(String.format("%s unknown", QueryFlag.NO_PERSONAL)); final Set<ResponseObject> response = Sets.newLinkedHashSet(subject.decorate(query, input)); assertThat(response, hasSize(1)); assertThat(response, contains(filterMessage)); } @Test public void show_personal_filters_nothing() { List<ResponseObject> input = Lists.newArrayList(relatedMessage, maintainer, role, person, abuseRole); final Query query = Query.parse(String.format("%s test", QueryFlag.SHOW_PERSONAL)); final Set<ResponseObject> response = Sets.newLinkedHashSet(subject.decorate(query, input)); assertThat(response, hasSize(5)); assertThat(response, contains(relatedMessage, maintainer, role, person, abuseRole)); } @Test public void show_personal_and_no_personal() { List<ResponseObject> input = Lists.newArrayList(relatedMessage, maintainer, role, person, abuseRole); final Query query = Query.parse(String.format("%s %s test", QueryFlag.NO_PERSONAL, QueryFlag.SHOW_PERSONAL)); final Set<ResponseObject> response = Sets.newLinkedHashSet(subject.decorate(query, input)); assertThat(response, hasSize(5)); assertThat(response, contains(relatedMessage, maintainer, role, person, abuseRole)); }
FilterTagsDecorator implements ResponseDecorator { public Iterable<? extends ResponseObject> decorate(final Query query, final Iterable<? extends ResponseObject> input) { final boolean showTagInfo = query.hasOption(QueryFlag.SHOW_TAG_INFO); final boolean hasInclude = query.hasOption(QueryFlag.FILTER_TAG_INCLUDE); final boolean hasExclude = query.hasOption(QueryFlag.FILTER_TAG_EXCLUDE); if (!(showTagInfo || hasInclude || hasExclude)) { return input; } final Set<CIString> includeArguments = query.getOptionValuesCI(QueryFlag.FILTER_TAG_INCLUDE); final Set<CIString> excludeArguments = query.getOptionValuesCI(QueryFlag.FILTER_TAG_EXCLUDE); final IterableTransformer<ResponseObject> responseObjects = new IterableTransformer<ResponseObject>(input) { @Override public void apply(final ResponseObject input, final Deque<ResponseObject> result) { if (!(input instanceof RpslObject)) { result.add(input); return; } final RpslObject object = (RpslObject) input; final List<Tag> tags = tagsDao.getTags(object.getObjectId()); if (hasInclude && !containsTag(tags, includeArguments)) { return; } if (hasExclude && containsTag(tags, excludeArguments)) { return; } result.add(object); if (showTagInfo && !tags.isEmpty()) { result.add(new TagResponseObject(object.getKey(), tags)); } } }; if (hasInclude || hasExclude) { responseObjects.setHeader(new MessageObject(QueryMessages.filterTagNote(includeArguments, excludeArguments))); } return responseObjects; } @Autowired FilterTagsDecorator(TagsDao tagsDao); Iterable<? extends ResponseObject> decorate(final Query query, final Iterable<? extends ResponseObject> input); }
@Test public void unrefInfo_for_unreferenced_role() { when(tagsDao.getTags(1)).thenReturn(Lists.newArrayList(new Tag(CIString.ciString("unref"), 1, "34"))); final RpslObject role = RpslObject.parse(1, "role: Test Role\nnic-hdl: TR1-TEST"); final Query query = Query.parse("--show-tag-info TR1-TEST"); final Iterable<? extends ResponseObject> result = subject.decorate(query, ImmutableList.of(role)); final Iterator<? extends ResponseObject> iterator = result.iterator(); assertThat(iterator.next() instanceof RpslObject, is(true)); assertThat(iterator.next().toString(), is("% Tags relating to 'TR1-TEST'\n" + "% Unreferenced # 'TR1-TEST' will be deleted in 34 days\n")); assertThat(iterator.hasNext(), is(false)); } @Test public void no_unrefInfo_for_referenced_mntner() { when(tagsDao.getTags(1)).thenReturn(Lists.<Tag>newArrayList()); final Query query = Query.parse("--show-tag-info TEST-MNT"); final RpslObject mntner = RpslObject.parse(1, "mntner: TEST-MNT"); final Iterable<? extends ResponseObject> result = subject.decorate(query, ImmutableList.of(mntner)); final Iterator<? extends ResponseObject> iterator = result.iterator(); final RpslObject object = (RpslObject) iterator.next(); assertThat(mntner, is(object)); assertFalse(iterator.hasNext()); }
TemplateQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return (query.isTemplate() || query.isVerbose()); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }
@Test public void supports_template() { assertThat(subject.supports(Query.parse("-t inetnum")), is(true)); } @Test public void supports_template_case_insensitive() { assertThat(subject.supports(Query.parse("-t iNeTnUm")), is(true)); } @Test public void supports_template_multiple() { assertThat(subject.supports(Query.parse("-t inetnum,inet6num")), is(true)); } @Test public void supports_template_with_type() { assertThat(subject.supports(Query.parse("-t inetnum,inet6num -T inetnum 0/0")), is(true)); } @Test public void supports_template_with_type_invalid() { assertThat(subject.supports(Query.parse("-t inetnum,inet6num -T inetnum")), is(true)); } @Test public void supports_template_with_searchValue() { assertThat(subject.supports(Query.parse("-t inetnum,inet6num query")), is(true)); } @Test public void supports_verbose() { assertThat(subject.supports(Query.parse("-v inetnum")), is(true)); } @Test public void supports_verbose_case_insensitive() { assertThat(subject.supports(Query.parse("-v InEtNuM")), is(true)); } @Test public void supports_verbose_multiple() { assertThat(subject.supports(Query.parse("-v inetnum,inetn6num")), is(true)); } @Test public void supports_verbose_with_type() { assertThat(subject.supports(Query.parse("-v inetnum,inet6num -T inetnum 0/0")), is(true)); } @Test public void supports_verbose_with_searchValue() { assertThat(subject.supports(Query.parse("-v inetnum,inet6num query")), is(true)); } @Test public void supports_template_with_other_arguments() { assertThat(subject.supports(Query.parse("-V ripews -t person")), is(true)); }
TemplateQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { final String objectTypeString = query.isTemplate() ? query.getTemplateOption() : query.getVerboseOption(); final ObjectType objectType = ObjectType.getByNameOrNull(objectTypeString); final MessageObject messageObject; if (objectType == null) { messageObject = new MessageObject(QueryMessages.invalidObjectType(objectTypeString)); } else { messageObject = new MessageObject(query.isTemplate() ? getTemplate(objectType) : getVerbose(objectType)); } responseHandler.handle(messageObject); } @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }
@Test public void getResponse() { for (final ObjectType objectType : ObjectType.values()) { final String name = objectType.getName(); final CaptureResponseHandler templateResponseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-t " + name), templateResponseHandler); final String templateText = templateResponseHandler.getResponseObjects().iterator().next().toString(); assertThat(templateText, containsString(name)); final CaptureResponseHandler verboseResponseHandler = new CaptureResponseHandler(); subject.execute(Query.parse("-v " + name), verboseResponseHandler); final String verboseText = verboseResponseHandler.getResponseObjects().iterator().next().toString(); assertThat(verboseText, containsString(name)); assertThat(verboseText, not(is(templateText))); } }
RpslObjectSearcher { public Iterable<? extends ResponseObject> search(final Query query, final SourceContext sourceContext) { Iterable<? extends ResponseObject> result = Collections.emptyList(); if (query.hasSubstitutions()) { result = Collections.singleton(new MessageObject(QueryMessages.valueChangedDueToLatin1Conversion())); } if (query.isInverse()) { result = indexLookupReverse(query); } else if (query.isMatchPrimaryKeyOnly()) { result = indexLookupDirect(query); } else { for (final ObjectType objectType : query.getObjectTypes()) { result = Iterables.concat(result, executeForObjectType(query, objectType)); } } for (AttributeFilter attributeFilter : attributeFilters) { result = attributeFilter.filter(result, query.getSources(), sourceContext); } return result; } @Autowired RpslObjectSearcher( final RpslObjectDao rpslObjectDao, final InetnumDao inetnumDao, final Inet6numDao inet6numDao, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, final Ipv4RouteTree route4Tree, final Ipv6RouteTree route6Tree, final Ipv4DomainTree ipv4DomainTree, final Ipv6DomainTree ipv6DomainTree, final Set<AttributeFilter> attributeFilters); Iterable<? extends ResponseObject> search(final Query query, final SourceContext sourceContext); }
@Test public void inverse_lookup_never_returns_null() { for (final AttributeType attributeType : AttributeType.values()) { assertNotNull(subject.search(Query.parse("-i " + attributeType.getName() + " query"), sourceContext)); } } @Test public void inverse_lookup_unsupported_attribute() { final Iterator<? extends ResponseObject> responseIterator = subject.search(Query.parse("-i e-mail,phone something"), sourceContext).iterator(); assertThat(responseIterator.next().toString(), is(QueryMessages.attributeNotSearchable("e-mail").toString())); assertThat(responseIterator.next().toString(), is(QueryMessages.attributeNotSearchable("phone").toString())); assertThat(responseIterator.hasNext(), is(false)); }
VersionQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { return query.isVersionList() || query.isObjectVersion() || query.isVersionDiff(); } @Autowired VersionQueryExecutor(final BasicSourceContext sourceContext, @Qualifier("jdbcVersionDao") final VersionDao versionDao); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); Collection<VersionLookupResult> getVersionInfo(final Query query); static final Set<ObjectType> NO_VERSION_HISTORY_FOR; }
@Test public void supportTest() { assertThat(subject.supports(Query.parse("10.0.0.0")), is(false)); assertThat(subject.supports(Query.parse("--list-versions 10.0.0.0")), is(true)); assertThat(subject.supports(Query.parse("--show-version 2 10.0.0.0")), is(true)); }
SearchQueryExecutor implements QueryExecutor { @Override public boolean supports(final Query query) { if ((!query.hasOptions() && query.isHelp()) || query.isSystemInfo() || query.isTemplate() || query.isVerbose() || query.isVersionList() || query.isObjectVersion() || query.isVersionDiff()) { return false; } return true; } @Autowired SearchQueryExecutor(final SourceContext sourceContext, final RpslObjectSearcher rpslObjectSearcher, final RpslResponseDecorator rpslResponseDecorator); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }
@Test public void all_attributes_handled() { for (final AttributeType attributeType : AttributeType.values()) { assertTrue(subject.supports(Query.parse("-i " + attributeType.getName() + " query"))); } } @Test(expected = QueryException.class) public void test_supports_no_attributes() { assertThat(subject.supports(Query.parse("-i")), is(false)); } @Test public void test_supports_inverse_with_filter() { assertThat(subject.supports(Query.parse("-T inetnum -i mnt-by aardvark-mnt")), is(true)); } @Test public void test_supports_inverse_recursive() { assertThat(subject.supports(Query.parse("-i mnt-by aardvark-mnt")), is(true)); } @Test public void test_supports_inverse() { assertThat(subject.supports(Query.parse("-r -i mnt-by aardvark-mnt")), is(true)); } @Test public void test_supports_inverse_multiple() { assertThat(subject.supports(Query.parse("-r -i mnt-by,mnt-ref aardvark-mnt")), is(true)); } @Test public void test_supports_inverse_multiple_unknown() { assertThat(subject.supports(Query.parse("-r -i mnt-by,mnt-ref,mnt-lower aardvark-mnt")), is(true)); }
SearchQueryExecutor implements QueryExecutor { @Override public void execute(final Query query, final ResponseHandler responseHandler) { boolean noResults = true; final Set<Source> sources = getSources(query); for (final Source source : sources) { try { sourceContext.setCurrent(source); final Iterable<? extends ResponseObject> searchResults = rpslObjectSearcher.search(query, sourceContext); for (final ResponseObject responseObject : rpslResponseDecorator.getResponse(query, searchResults)) { responseHandler.handle(responseObject); if (!(responseObject instanceof MessageObject)) { noResults = false; } } } catch (IllegalSourceException e) { responseHandler.handle(new MessageObject(QueryMessages.unknownSource(source.getName()))); noResults = false; } finally { sourceContext.removeCurrentSource(); } } if (noResults) { responseHandler.handle(new MessageObject(QueryMessages.noResults(Joiner.on(',').join(Iterables.transform(sources, source -> source.getName().toUpperCase()))))); } } @Autowired SearchQueryExecutor(final SourceContext sourceContext, final RpslObjectSearcher rpslObjectSearcher, final RpslResponseDecorator rpslResponseDecorator); @Override boolean isAclSupported(); @Override boolean supports(final Query query); @Override void execute(final Query query, final ResponseHandler responseHandler); }
@Test public void unknown_source() { final Query query = Query.parse("-s UNKNOWN 10.0.0.0"); doThrow(IllegalSourceException.class).when(sourceContext).setCurrent(Source.slave("UNKNOWN")); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(rpslObjectSearcher, never()).search(query, sourceContext); assertThat(responseHandler.getResponseObjects(), hasSize(1)); assertThat(responseHandler.getResponseObjects().get(0), Matchers.<ResponseObject>is(new MessageObject(QueryMessages.unknownSource("UNKNOWN")))); } @Test public void query_all_sources() { when(sourceContext.getAllSourceNames()).thenReturn(ciSet("APNIC-GRS", "ARIN-GRS")); final Query query = Query.parse("--all-sources 10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(sourceContext).setCurrent(Source.slave("APNIC-GRS")); verify(sourceContext).setCurrent(Source.slave("ARIN-GRS")); verify(sourceContext, times(2)).removeCurrentSource(); verify(rpslObjectSearcher, times(2)).search(query, sourceContext); } @Test public void query_sources() { final Query query = Query.parse("--sources APNIC-GRS,ARIN-GRS 10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(sourceContext).setCurrent(Source.slave("APNIC-GRS")); verify(sourceContext).setCurrent(Source.slave("ARIN-GRS")); verify(sourceContext, times(2)).removeCurrentSource(); verify(rpslObjectSearcher, times(2)).search(query, sourceContext); } @Test public void query_sources_and_additional() { when(sourceContext.getAllSourceNames()).thenReturn(ciSet("APNIC-GRS", "ARIN-GRS")); final Query query = Query.parse("--all-sources --sources RIPE 10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(sourceContext).setCurrent(Source.slave("APNIC-GRS")); verify(sourceContext).setCurrent(Source.slave("ARIN-GRS")); verify(sourceContext).setCurrent(Source.slave("RIPE")); verify(sourceContext, times(3)).removeCurrentSource(); verify(rpslObjectSearcher, times(3)).search(query, sourceContext); } @Test public void query_resources() { when(sourceContext.getGrsSourceNames()).thenReturn(ciSet("APNIC-GRS", "ARIN-GRS")); final Query query = Query.parse("--resource 10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(sourceContext).setCurrent(Source.slave("APNIC-GRS")); verify(sourceContext).setCurrent(Source.slave("ARIN-GRS")); verify(sourceContext, times(2)).removeCurrentSource(); verify(rpslObjectSearcher, times(2)).search(query, sourceContext); } @Test public void query_all_sources_filters_virtual_sources() { when(sourceContext.getAllSourceNames()).thenReturn(ciSet("RIPE", "RIPE-GRS", "APNIC-GRS", "ARIN-GRS")); when(sourceContext.isVirtual(any(CIString.class))).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { final Object[] arguments = invocation.getArguments(); return (ciString("RIPE-GRS").equals(arguments[0])); } }); final Query query = Query.parse("--all-sources 10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(sourceContext, never()).setCurrent(Source.slave("RIPE-GRS")); verify(sourceContext).setCurrent(Source.slave("APNIC-GRS")); verify(sourceContext).setCurrent(Source.slave("ARIN-GRS")); verify(sourceContext).setCurrent(Source.slave("RIPE")); verify(sourceContext, times(3)).removeCurrentSource(); verify(rpslObjectSearcher, times(3)).search(query, sourceContext); } @Test public void query_no_source_specified() { when(sourceContext.getWhoisSlaveSource()).thenReturn(Source.slave("RIPE")); final Query query = Query.parse("10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(sourceContext).setCurrent(Source.slave("RIPE")); verify(sourceContext).removeCurrentSource(); verify(rpslObjectSearcher).search(query, sourceContext); } @Test public void no_results_found_gives_message() { final Query query = Query.parse("-s RIPE 10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(rpslObjectSearcher).search(query, sourceContext); verify(rpslResponseDecorator).getResponse(eq(query), any(Iterable.class)); assertThat(responseHandler.getResponseObjects(), contains((ResponseObject) new MessageObject(QueryMessages.noResults("RIPE").toString()))); } @Test public void query_additional_sources() { when(sourceContext.getAdditionalSourceNames()).thenReturn(ciSet("APNIC-GRS", "ARIN-GRS")); when(sourceContext.getWhoisSlaveSource()).thenReturn(Source.slave("RIPE")); final Query query = Query.parse("10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(sourceContext).setCurrent(Source.slave("RIPE")); verify(sourceContext).setCurrent(Source.slave("APNIC-GRS")); verify(sourceContext).setCurrent(Source.slave("ARIN-GRS")); verify(sourceContext, times(3)).removeCurrentSource(); verify(rpslObjectSearcher, times(3)).search(query, sourceContext); } @Test public void query_sources_not_additional() { when(sourceContext.getAdditionalSourceNames()).thenReturn(ciSet("RIPE", "APNIC-GRS", "ARIN-GRS")); final Query query = Query.parse("--sources APNIC-GRS,ARIN-GRS 10.0.0.0"); final CaptureResponseHandler responseHandler = new CaptureResponseHandler(); subject.execute(query, responseHandler); verify(sourceContext).setCurrent(Source.slave("APNIC-GRS")); verify(sourceContext).setCurrent(Source.slave("ARIN-GRS")); verify(sourceContext, times(2)).removeCurrentSource(); verify(rpslObjectSearcher, times(2)).search(query, sourceContext); }
QueryDecoder extends OneToOneDecoder { @Override protected Object decode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) { final Query query = Query.parse((String) msg, Query.Origin.LEGACY, isTrusted(channel)); for (final Message warning : query.getWarnings()) { channel.write(warning); } return query; } @Autowired QueryDecoder(final AccessControlListManager accessControlListManager); }
@Test public void validDecodedStringShouldReturnQuery() throws Exception { String queryString = "-Tperson DW-RIPE"; Query expectedQuery = Query.parse(queryString); when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); Query actualQuery = (Query) subject.decode(channelHandlerContextMock, channelMock, queryString); assertEquals(expectedQuery, actualQuery); } @Test public void invalidOptionQuery() { String queryString = "-Yperson DW-RIPE"; when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); try { subject.decode(null, channelMock, queryString); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getCompletionInfo(), is(QueryCompletionInfo.PARAMETER_ERROR)); } } @Test public void invalidProxyQuery() throws Exception { String queryString = "-Vone,two,three DW-RIPE"; when(channelMock.getRemoteAddress()).thenReturn(new InetSocketAddress(InetAddresses.forString("10.0.0.1"), 80)); try { subject.decode(null, channelMock, queryString); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getCompletionInfo(), is(QueryCompletionInfo.PARAMETER_ERROR)); } }
WhoisEncoder extends OneToOneEncoder { @Override protected Object encode(final ChannelHandlerContext ctx, final Channel channel, final Object msg) throws IOException { if (msg instanceof ResponseObject) { final ChannelBuffer result = ChannelBuffers.dynamicBuffer(DEFAULT_BUFFER_SIZE); final ChannelBufferOutputStream out = new ChannelBufferOutputStream(result); ((ResponseObject) msg).writeTo(out); out.write(OBJECT_TERMINATOR); return result; } else if (msg instanceof Message) { return ChannelBuffers.wrappedBuffer(msg.toString().getBytes(StandardCharsets.UTF_8), OBJECT_TERMINATOR); } return msg; } }
@Test public void encode_null() throws IOException { Object result = encode(null); assertThat(result, is(nullValue())); } @Test public void encode_Message() throws IOException { Message message = QueryMessages.inputTooLong(); ChannelBuffer result = encode(message); assertThat(toString(result), is(message.toString() + "\n")); } @Test public void encode_ResponseObject() throws IOException { ChannelBuffer result = encode(objectMock); verify(objectMock, times(1)).writeTo(any(OutputStream.class)); assertThat(toString(result), is("\n")); }
ServedByHandler implements ChannelDownstreamHandler { @Override public void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e) { if (e instanceof QueryCompletedEvent) { e.getChannel().write(QueryMessages.servedByNotice(version)); } ctx.sendDownstream(e); } ServedByHandler(final String version); @Override void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e); }
@Test public void test_handleDownstream_whois() { when(messageEventMock.getMessage()).thenReturn(new MessageObject("")); subject.handleDownstream(ctxMock, messageEventMock); verify(ctxMock, times(1)).sendDownstream(messageEventMock); subject.handleDownstream(ctxMock, queryCompletedEventMock); verify(ctxMock, times(1)).sendDownstream(queryCompletedEventMock); verify(channelMock, times(1)).write(QueryMessages.servedByNotice(anyString())); }
ConnectionStateHandler extends SimpleChannelUpstreamHandler implements ChannelDownstreamHandler { @Override public void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e) { ctx.sendDownstream(e); if (e instanceof QueryCompletedEvent) { final Channel channel = e.getChannel(); if (keepAlive && !((QueryCompletedEvent) e).isForceClose()) { channel.write(NEWLINE); channel.write(QueryMessages.termsAndConditions()); } else { closed = true; channel.write(NEWLINE).addListener(ChannelFutureListener.CLOSE); } } } @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void handleDownstream(final ChannelHandlerContext ctx, final ChannelEvent e); }
@Test public void sendingNoKFlagShouldNotEnableKeepAlive() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("help")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(channelMock, times(1)).write(ConnectionStateHandler.NEWLINE); verify(futureMock, times(1)).addListener(ChannelFutureListener.CLOSE); } @Test public void sendingNoKFlagButConnectionStateIsKeepAliveKeepItThatWay() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k")); subject.handleUpstream(contextMock, messageMock); when(messageMock.getMessage()).thenReturn(Query.parse("help")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(channelMock, times(1)).write(QueryMessages.termsAndConditions()); verify(futureMock, times(0)).addListener(ChannelFutureListener.CLOSE); } @Test public void firstSingleKShouldKeepConnectionOpen() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(0)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(futureMock, times(0)).addListener(ChannelFutureListener.CLOSE); } @Test public void firstKWithArgumentsShouldKeepConnectionOpen() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k -r -T inetnum 10.0.0.0")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); when(contextMock.getAttachment()).thenReturn(Boolean.TRUE); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(futureMock, times(0)).addListener(ChannelFutureListener.CLOSE); verify(channelMock, times(2)).write(any()); } @Test public void secondKWithArgumentsShouldKeepConnectionOpen() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k -r -T inetnum 10.0.0.0")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock)); verify(futureMock, times(0)).addListener(ChannelFutureListener.CLOSE); } @Test public void forceCloseShouldCloseConnection() throws Exception { when(messageMock.getMessage()).thenReturn(Query.parse("-k -r -T inetnum 10.0.0.0")); subject.handleUpstream(contextMock, messageMock); verify(contextMock, times(1)).sendUpstream(messageMock); subject.handleDownstream(contextMock, new QueryCompletedEvent(channelMock, QueryCompletionInfo.DISCONNECTED)); verify(channelMock, times(0)).write(QueryMessages.termsAndConditions()); verify(channelMock, times(1)).write(ConnectionStateHandler.NEWLINE); verify(futureMock, times(1)).addListener(ChannelFutureListener.CLOSE); } @Test public void dontActOnDownstreamNonQueryCompletedEvents() throws Exception { subject.handleDownstream(contextMock, null); verify(channelMock, times(0)).write(any()); }
ExceptionHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) { query = e.getMessage().toString(); ctx.sendUpstream(e); } @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event); }
@Test public void record_incoming_queries() throws Exception { subject.messageReceived(channelHandlerContextMock, messageEventMock); verify(channelHandlerContextMock, times(1)).sendUpstream(messageEventMock); }
ExceptionHandler extends SimpleChannelUpstreamHandler { @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event) { final Throwable cause = event.getCause(); LOGGER.debug("Caught exception", cause); final Channel channel = event.getChannel(); if (cause instanceof ClosedChannelException) { LOGGER.debug("Channel closed", cause); } else if (cause instanceof QueryException) { handleException(channel, ((QueryException) cause).getMessages(), ((QueryException) cause).getCompletionInfo()); } else if (cause instanceof TimeoutException) { handleException(channel, Collections.singletonList(QueryMessages.timeout()), QueryCompletionInfo.EXCEPTION); } else if (cause instanceof TooLongFrameException) { handleException(channel, Collections.singletonList(QueryMessages.inputTooLong()), QueryCompletionInfo.EXCEPTION); } else if (cause instanceof IOException) { handleException(channel, Collections.<Message>emptyList(), QueryCompletionInfo.EXCEPTION); } else if (cause instanceof DataAccessException) { LOGGER.error("Caught exception on channel id = {}, from = {} for query = {}\n{}", channel.getId(), ChannelUtil.getRemoteAddress(channel), query, cause.toString()); handleException(channel, Collections.singletonList(QueryMessages.internalErroroccurred()), QueryCompletionInfo.EXCEPTION); } else { LOGGER.error("Caught exception on channel id = {}, from = {} for query = {}", channel.getId(), ChannelUtil.getRemoteAddress(channel), query, cause); handleException(channel, Collections.singletonList(QueryMessages.internalErroroccurred()), QueryCompletionInfo.EXCEPTION); } } @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e); @Override void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent event); }
@Test public void handle_unknown_exceptions() throws Exception { subject.exceptionCaught(channelHandlerContextMock, exceptionEventMock); verify(channelMock, times(1)).write(QueryMessages.internalErroroccurred()); } @Test public void handle_timeout_exception() throws Exception { when(exceptionEventMock.getCause()).thenReturn(new TimeoutException()); subject.exceptionCaught(null, exceptionEventMock); verify(channelMock, times(1)).write(QueryMessages.timeout()); } @Test public void handle_too_long_frame_exception() throws Exception { when(exceptionEventMock.getCause()).thenReturn(new TooLongFrameException()); subject.exceptionCaught(null, exceptionEventMock); verify(channelMock, times(1)).write(QueryMessages.inputTooLong()); } @Test public void handle_io_exception() throws Exception { when(exceptionEventMock.getCause()).thenReturn(new IOException()); subject.exceptionCaught(null, exceptionEventMock); verify(channelPipelineMock, times(1)).sendDownstream(new QueryCompletedEvent(channelMock, QueryCompletionInfo.EXCEPTION)); } @Test public void no_write_if_channel_closed() { when(channelMock.isOpen()).thenReturn(false); when(exceptionEventMock.getCause()).thenReturn(new TimeoutException()); subject.exceptionCaught(null, exceptionEventMock); verify(channelMock, times(0)).write(QueryMessages.timeout()); }
TermsAndConditionsHandler extends SimpleChannelUpstreamHandler { @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { e.getChannel().write(TERMS_AND_CONDITIONS); ctx.sendUpstream(e); } @Override void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e); }
@Test public void test_terms_and_conditions() { subject.channelConnected(ctxMock, channelStateEventMock); verify(ctxMock, times(1)).sendUpstream(channelStateEventMock); verify(channelMock, times(1)).write(QueryMessages.termsAndConditions()); }
WhoisServerHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent event) { final Query query = (Query) event.getMessage(); final Channel channel = event.getChannel(); queryHandler.streamResults(query, ChannelUtil.getRemoteAddress(channel), channel.getId(), new ResponseHandler() { @Override public String getApi() { return "QRY"; } @Override public void handle(final ResponseObject responseObject) { if (closed) { throw new QueryException(QueryCompletionInfo.DISCONNECTED); } channel.write(responseObject); } }); channel.getPipeline().sendDownstream(new QueryCompletedEvent(channel)); } WhoisServerHandler(final QueryHandler queryHandler); @Override void messageReceived(final ChannelHandlerContext ctx, final MessageEvent event); @Override void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e); }
@Test public void messageReceived_no_proxy_no_personal_object() throws Exception { final Query query = Query.parse("10.0.0.0"); when(messageEvent.getMessage()).thenReturn(query); subject.messageReceived(ctx, messageEvent); verify(channel).write(responseObject); final ArgumentCaptor<QueryCompletedEvent> channelEventCapture = ArgumentCaptor.forClass(QueryCompletedEvent.class); verify(pipeline).sendDownstream(channelEventCapture.capture()); assertNull(channelEventCapture.getValue().getCompletionInfo()); }
ConnectionPerIpLimitHandler extends SimpleChannelUpstreamHandler { private boolean connectionsExceeded(final InetAddress remoteAddress) { final Integer count = connectionCounter.increment(remoteAddress); return (count != null && count >= maxConnectionsPerIp); } @Autowired ConnectionPerIpLimitHandler( final IpResourceConfiguration ipResourceConfiguration, final WhoisLog whoisLog, @Value("${whois.limit.connectionsPerIp:3}") final int maxConnectionsPerIp, final ApplicationVersion applicationVersion); @Override void channelOpen(final ChannelHandlerContext ctx, final ChannelStateEvent e); @Override void channelClosed(final ChannelHandlerContext ctx, final ChannelStateEvent e); }
@Test public void multiple_connected_same_ip() throws Exception { final InetSocketAddress remoteAddress = new InetSocketAddress("10.0.0.0", 43); when(channel.getRemoteAddress()).thenReturn(remoteAddress); final ChannelEvent openEvent = new UpstreamChannelStateEvent(channel, ChannelState.OPEN, Boolean.TRUE); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); subject.handleUpstream(ctx, openEvent); verify(ctx, times(2)).sendUpstream(openEvent); verify(channel, times(1)).write(argThat(new ArgumentMatcher<Object>() { @Override public boolean matches(Object argument) { return QueryMessages.connectionsExceeded(MAX_CONNECTIONS_PER_IP).equals(argument); } })); verify(channelFuture, times(1)).addListener(ChannelFutureListener.CLOSE); verify(whoisLog).logQueryResult(anyString(), eq(0), eq(0), eq(QueryCompletionInfo.REJECTED), eq(0L), (InetAddress) Mockito.anyObject(), Mockito.anyInt(), eq("")); verify(ctx, times(2)).sendUpstream(openEvent); }
AttributeMatcher { static boolean fetchableBy(final AttributeType attributeType, final Query query) { for (final AttributeMatcher matcher : attributeMatchers.get(attributeType)) { try { if (matcher.matches(query)) { return true; } } catch (IllegalArgumentException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } } return false; } }
@Test public void searchKeyTypesName() { assertTrue(AttributeMatcher.fetchableBy(AttributeType.PERSON, Query.parse("name"))); assertTrue(AttributeMatcher.fetchableBy(AttributeType.PERSON, Query.parse("one-two-three"))); } @Test public void searchKeyTypesOrganisationId() { assertTrue(AttributeMatcher.fetchableBy(AttributeType.ORGANISATION, Query.parse("ORG-AX1-RIPE"))); assertTrue(AttributeMatcher.fetchableBy(AttributeType.ORGANISATION, Query.parse("oRg-aX1-rIPe"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.ORGANISATION, Query.parse("name"))); } @Test public void searchKeyTypesNicHandle() { assertTrue(AttributeMatcher.fetchableBy(AttributeType.NIC_HDL, Query.parse("AA1-DEV"))); assertTrue(AttributeMatcher.fetchableBy(AttributeType.NIC_HDL, Query.parse("aA1-deV"))); assertTrue(AttributeMatcher.fetchableBy(AttributeType.NIC_HDL, Query.parse("name"))); } @Test public void searchKeyEmail() { assertTrue(AttributeMatcher.fetchableBy(AttributeType.E_MAIL, Query.parse("[email protected]"))); assertTrue(AttributeMatcher.fetchableBy(AttributeType.E_MAIL, Query.parse("[email protected]"))); assertTrue(AttributeMatcher.fetchableBy(AttributeType.E_MAIL, Query.parse("[email protected]"))); } @Test public void searchInetnum() { assertTrue(AttributeMatcher.fetchableBy(AttributeType.ROUTE, Query.parse("10.11.12.0/24"))); assertTrue(AttributeMatcher.fetchableBy(AttributeType.INETNUM, Query.parse("10.11.12.0/24"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.INET6NUM, Query.parse("10.11.12.0/24"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.ROUTE6, Query.parse("10.11.12.0/24"))); } @Test public void searchInet6num() { assertTrue(AttributeMatcher.fetchableBy(AttributeType.INET6NUM, Query.parse("2001::/32"))); assertTrue(AttributeMatcher.fetchableBy(AttributeType.ROUTE6, Query.parse("2001::/32"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.ROUTE, Query.parse("2001::/32"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.INETNUM, Query.parse("2001::/32"))); } @Test public void searchRoute() { assertTrue(AttributeMatcher.fetchableBy(AttributeType.ROUTE, Query.parse("10.11.12.0/24AS3333"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.INETNUM, Query.parse("10.11.12.0/24AS3333"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.INET6NUM, Query.parse("10.11.12.0/24AS3333"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.ROUTE6, Query.parse("10.11.12.0/24AS3333"))); } @Test public void searchRoute6() { assertTrue(AttributeMatcher.fetchableBy(AttributeType.ROUTE6, Query.parse("2001::/32AS3333"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.ROUTE, Query.parse("2001::/32AS3333"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.INETNUM, Query.parse("2001::/32AS3333"))); assertFalse(AttributeMatcher.fetchableBy(AttributeType.INET6NUM, Query.parse("2001::/32AS3333"))); }
TagValidator implements QueryValidator { @Override public void validate(final Query query, final Messages messages) { if (query.hasOption(QueryFlag.FILTER_TAG_INCLUDE) && query.hasOption(QueryFlag.FILTER_TAG_EXCLUDE)) { final Sets.SetView<String> intersection = Sets.intersection(query.getOptionValues(QueryFlag.FILTER_TAG_INCLUDE), query.getOptionValues(QueryFlag.FILTER_TAG_EXCLUDE)); if (!intersection.isEmpty()) { final String args = " (" + Joiner.on(',').join(intersection.iterator()) + ")"; messages.add(QueryMessages.invalidCombinationOfFlags( QueryFlag.FILTER_TAG_INCLUDE.toString() + args, QueryFlag.FILTER_TAG_EXCLUDE.toString() + args)); } } } @Override void validate(final Query query, final Messages messages); }
@Test public void both_filter_tag_include_and_exclude() { try { subject.validate(Query.parse("--filter-tag-include unref --filter-tag-exclude unref TEST-MNT"), messages); } catch (QueryException e) { assertThat(e.getMessage(), containsString(QueryMessages.invalidCombinationOfFlags("--filter-tag-include (unref)", "--filter-tag-exclude (unref)").toString())); } } @Test public void both_filter_tag_include_and_exclude_different_arguments() { subject.validate(Query.parse("--filter-tag-include foo --filter-tag-exclude unref TEST-MNT"), messages); } @Test public void filter_tag_include_correct() { subject.validate(Query.parse("--filter-tag-include unref TEST-MNT"), messages); } @Test public void filter_tag_exclude_correct() { subject.validate(Query.parse("--filter-tag-exclude unref TEST-MNT"), messages); }
SearchKey { public String getValue() { return value; } SearchKey(final String value); String getValue(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); AsBlockRange getAsBlockRangeOrNull(); @Override String toString(); String getOrigin(); static final Pattern WHITESPACE_PATTERN; }
@Test public void parse_and_value() { subject = new SearchKey("test"); assertThat(subject.getValue(), is("test")); }
SearchKey { public IpInterval<?> getIpKeyOrNull() { return ipKey; } SearchKey(final String value); String getValue(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); AsBlockRange getAsBlockRangeOrNull(); @Override String toString(); String getOrigin(); static final Pattern WHITESPACE_PATTERN; }
@Test public void comma_in_search_key() { subject = new SearchKey("10,10"); assertNull(subject.getIpKeyOrNull()); } @Test public void parse_ipv6_with_v4() { final SearchKey searchKey = new SearchKey("::ffff:0.0.0.0"); final IpInterval<?> ipKeyOrNull = searchKey.getIpKeyOrNull(); assertNull(ipKeyOrNull); } @Test public void parse_ipv6_with_v4_prefix() { final SearchKey searchKey = new SearchKey("::ffff:0.0.0.0/72"); final IpInterval<?> ipKeyOrNull = searchKey.getIpKeyOrNull(); assertNull(ipKeyOrNull); }
InverseValidator implements QueryValidator { @Override public void validate(final Query query, final Messages messages) { if (query.isInverse()) { final String auth = query.getSearchValue().toUpperCase(); if ((!query.isTrusted() && auth.startsWith("SSO ")) || auth.startsWith("MD5-PW ")) { messages.add(net.ripe.db.whois.query.QueryMessages.inverseSearchNotAllowed()); } } } @Override void validate(final Query query, final Messages messages); }
@Test public void not_inverse_query() { when(query.isInverse()).thenReturn(FALSE); subject.validate(query, messages); assertThat(messages.hasMessages(), is(false)); } @Test public void searchValue_not_SSO_nor_MD5() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("ORG-TP1-TEST"); subject.validate(query, messages); assertThat(messages.hasMessages(), is(false)); } @Test public void searchValue_SSO() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("SSO [email protected]"); subject.validate(query, messages); assertThat(messages.getErrors(), contains(QueryMessages.inverseSearchNotAllowed())); } @Test public void searchValue_MD5() { when(query.isInverse()).thenReturn(TRUE); when(query.getSearchValue()).thenReturn("MD5-PW \\$1\\$fU9ZMQN9\\$QQtm3kRqZXWAuLpeOiLN7."); subject.validate(query, messages); assertThat(messages.getErrors(), contains(QueryMessages.inverseSearchNotAllowed())); }
Query { public static Query parse(final String args) { return parse(args, Origin.LEGACY, false); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }
@Test public void empty() { try { parse(""); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.noSearchKeySpecified())); } } @Test public void deprecated_R() { try { parse("-R test"); } catch (QueryException e) { assertThat(e.getMessages(), hasSize(1)); assertThat(e.getMessages().iterator().next(), is(QueryMessages.malformedQuery())); } } @Test public void missing_arguments_for_flags() { String[] flagsWithArguments = {"i", "s", "t", "v", "q", "V"}; for (String flag : flagsWithArguments) { try { parse("-" + flag); fail("Missing argument for " + flag + " should throw an exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.malformedQuery())); } } } @Test public void single_type_invalid_searchkey() { try { parse("-T aut-num foo"); fail("Expected query exception"); } catch (QueryException e) { assertThat(e.getCompletionInfo(), Matchers.is(QueryCompletionInfo.PARAMETER_ERROR)); assertThat(e.getMessages(), contains(QueryMessages.invalidSearchKey())); } } @Test public void non_existing_types() { try { parse("-T aUT-Num,IAmInvalid,iNETnUm"); fail("Non existing type should throw an exception"); } catch (QueryException e) { assertThat(e.getMessage(), containsString("ERROR:103")); } } @Test(expected = QueryException.class) public void proxied_for_invalid() { parse("-VclientId,ipAddress"); } @Test(expected = QueryException.class) public void proxy_with_invalid_ip() { parse("-Vone,two"); } @Test(expected = QueryException.class) public void proxy_with_more_than_two_elements() { parse("-Vone,two,10.1.1.1"); } @Test(expected = QueryException.class) public void invalidProxyShouldThrowException() { Query.parse("-Vone,two,three -Tperson DW-RIPE"); } @Test(expected = QueryException.class) public void multiple_proxies() { Query.parse("-V ripews,188.111.4.162 -V 85.25.132.61"); } @Test public void multiple_match_operations() { try { Query.parse("-m -x 10.0.0.0"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.duplicateIpFlagsPassed())); } } @Test public void invalid_combination() { try { Query.parse("-b -F 10.0.0.0"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.invalidCombinationOfFlags("-b, --abuse-contact", "-F, --brief"))); } } @Test public void brief_without_ipkey() { try { Query.parse("-b test"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.malformedQuery())); } } @Test public void unsupportedQuery() { try { Query.parse("..."); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.invalidSearchKey())); } } @Test public void allow_only_k_T_and_V_options_for_version_queries() { final String[] validQueries = { "--show-version 1 AS12 -k", "--show-version 1 AS12 -V fred", "--show-version 1 AS12 -k -V fred", "--list-versions AS12 -k -V fred", "--list-versions AS12 -V fred", "--list-versions AS12 -k", "--diff-versions 1:2 AS12", "--diff-versions 1:2 AS12 -k", "--diff-versions 1:2 AS12 -V fred", "--show-version 1 AS12 -T aut-num", }; for (String query : validQueries) { Query.parse(query); } final String[] invalidQueries = { "--show-version 1 AS12 -B", "--list-versions AS12 -G", "--list-versions AS12 -V fred --no-tag-info", "--list-versions AS12 -k --show-version 1 AS12", "--diff-versions 1:2 AS12 -k --show-version 1", "--diff-versions 1:2 AS12 -B", "--diff-versions 1:2 AS12 -V fred --no-tag-info" }; for (String query : invalidQueries) { try { Query.parse(query); fail(String.format("%s should not succeed", query)); } catch (final QueryException e) { assertThat(e.getMessage(), containsString("cannot be used together")); } } } @Test public void filter_tag_include_no_query() { try { Query.parse("--filter-tag-include unref"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.noSearchKeySpecified())); } } @Test public void filter_tag_exclude_no_query() { try { Query.parse("--filter-tag-exclude unref"); fail("Expected exception"); } catch (QueryException e) { assertThat(e.getMessages(), contains(QueryMessages.noSearchKeySpecified())); } } @Test public void no_tag_info_and_show_tag_info_in_the_same_query() { try { Query.parse("--no-tag-info --show-tag-info TEST-MNT"); fail(); } catch (QueryException e) { assertThat(e.getMessage(), containsString("The flags \"--show-tag-info\" and \"--no-tag-info\" cannot be used together.")); } }
Query { public boolean isReturningIrt() { return isBriefAbuseContact() || (!isKeysOnly() && queryParser.hasOption(QueryFlag.IRT)); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }
@Test public void isReturningIrt() { Query query = Query.parse("-c 10.0.0.0"); assertTrue(query.isReturningIrt()); }
Query { public boolean hasSources() { return !sources.isEmpty(); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }
@Test public void hasSources() { Query query = Query.parse("-s RIPE,TEST 10.0.0.0"); assertTrue(query.hasSources()); assertThat(query.getSources(), contains("RIPE", "TEST")); }
Query { public boolean isPrimaryObjectsOnly() { return !(isReturningReferencedObjects() || isReturningIrt() || isGrouping()); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }
@Test public void isPrimaryObjectsOnly() { Query query = Query.parse("-rG 10.0.0.0"); assertTrue(query.isPrimaryObjectsOnly()); }
Query { public boolean isAllSources() { return queryParser.hasOption(QueryFlag.ALL_SOURCES); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }
@Test public void isAllSources() { Query query = Query.parse("-a foo"); assertThat(query.isAllSources(), is(true)); }
Query { public boolean isKeysOnly() { return queryParser.hasOption(QueryFlag.PRIMARY_KEYS); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }
@Test public void isKeysOnly() { Query query = Query.parse("-K 10.0.0.0"); assertThat(query.isKeysOnly(), is(true)); }
Query { public boolean hasOption(QueryFlag queryFlag) { return queryParser.hasOption(queryFlag); } private Query(final String query, final Origin origin, final boolean trusted); static Query parse(final String args); static Query parse(final String args, final Origin origin, final boolean trusted); static Query parse(final String args, final String ssoToken, final List<String> passwords, final boolean trusted); List<String> getPasswords(); String getSsoToken(); boolean isTrusted(); boolean hasSubstitutions(); boolean via(Origin origin); Collection<Message> getWarnings(); boolean isAllSources(); boolean isResource(); boolean isLookupInBothDirections(); boolean isReturningIrt(); boolean isGrouping(); boolean isBriefAbuseContact(); boolean isKeysOnly(); boolean isPrimaryObjectsOnly(); boolean isFiltered(); boolean isHelp(); boolean isSystemInfo(); boolean isReturningReferencedObjects(); boolean isInverse(); boolean isTemplate(); boolean isVersionList(); boolean isVersionDiff(); boolean isObjectVersion(); int getObjectVersion(); int[] getObjectVersions(); String getTemplateOption(); boolean isVerbose(); boolean isValidSyntax(); boolean isNoValidSyntax(); SystemInfoOption getSystemInfoOption(); String getVerboseOption(); boolean hasObjectTypesSpecified(); Set<ObjectType> getObjectTypes(); Set<AttributeType> getAttributeTypes(); MatchOperation matchOperation(); boolean hasIpFlags(); boolean hasObjectTypeFilter(ObjectType objectType); String getSearchValue(); Set<ObjectType> getSuppliedObjectTypes(); IpInterval<?> getIpKeyOrNull(); IpInterval<?> getIpKeyOrNullReverse(); String getRouteOrigin(); AsBlockRange getAsBlockRangeOrNull(); String getProxy(); boolean hasProxy(); boolean hasProxyWithIp(); boolean hasKeepAlive(); boolean isShortHand(); boolean hasOnlyKeepAlive(); boolean isProxyValid(); String getProxyIp(); boolean hasOptions(); boolean hasOption(QueryFlag queryFlag); @Deprecated Set<String> getOptionValues(QueryFlag queryFlag); @Deprecated Set<CIString> getOptionValuesCI(QueryFlag queryFlag); boolean hasSources(); Set<String> getSources(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); boolean matchesObjectTypeAndAttribute(final ObjectType objectType, final AttributeType attributeType); boolean isMatchPrimaryKeyOnly(); Query setMatchPrimaryKeyOnly(boolean matchPrimaryKeyOnly); static final EnumSet<ObjectType> ABUSE_CONTACT_OBJECT_TYPES; }
@Test public void hasOption() { Query query = Query.parse("-s RIPE -T inetnum 10.0.0.0"); assertThat(query.hasOption(QueryFlag.SOURCES), is(true)); assertThat(query.hasOption(QueryFlag.SELECT_TYPES), is(true)); assertThat(query.hasOption(QueryFlag.NO_REFERENCED), is(false)); }
FilterEmailFunction implements FilterFunction { @Override @Nonnull public RpslObject apply(RpslObject rpslObject) { RpslObjectBuilder builder = new RpslObjectBuilder(rpslObject).removeAttributeTypes(filterAttributes); return rpslObject.size() == builder.size() ? rpslObject : RpslObjectFilter.setFiltered(builder).get(); } @Override @Nonnull RpslObject apply(RpslObject rpslObject); }
@Test public void apply_no_email_attribute() { final RpslObject rpslObject = RpslObject.parse("" + "irt: DEV-IRT\n" + "auth: MD5-PW $1$YmPozTxJ$s3eGZRVrKVGdSDTeEZJu\n" + "source: RIPE" ); final RpslObject response = subject.apply(rpslObject); assertThat(response, is(rpslObject)); } @Test public void apply_email_attributes() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "e-mail: value\n" + "e-mail: value\n" + "notify: value\n" + "notify: value\n" + "ref-nfy: value\n" + "ref-nfy: value\n" + "mnt-nfy: value\n" + "mnt-nfy: value\n" + "upd-to: value\n" + "upd-to: value\n" + "source: RIPE\n" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "source: RIPE # Filtered\n")); } @Test public void apply_email_attributes_not_filtered() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "source: RIPE\n" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "source: RIPE\n")); } @Test public void apply_filtered_only_once() { final RpslObject rpslObject = RpslObject.parse("" + "mntner: WEIRD-MNT\n" + "source:RIPE # Filtered\n" + "e-mail:[email protected]\n" ); final RpslObject response = subject.apply(rpslObject); assertThat(response.toString(), is("" + "mntner: WEIRD-MNT\n" + "source: RIPE # Filtered\n")); }
IpResourceConfiguration { public int getLimit(final InetAddress address) { final Integer result = limit.getValue(IpInterval.asIpInterval(address)); return result == null ? DEFAULT_LIMIT : result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }
@Test public void test_limit_default() throws Exception { assertThat(subject.getLimit(inetAddress), is(5000)); }
IpResourceConfiguration { public boolean isProxy(final InetAddress address) { final Boolean result = proxy.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }
@Test public void test_proxy_default() throws Exception { assertThat(subject.isProxy(inetAddress), is(false)); }
IpResourceConfiguration { public boolean isDenied(final InetAddress address) { final Boolean result = denied.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }
@Test public void test_denied_default() throws Exception { assertThat(subject.isDenied(inetAddress), is(false)); }
IpResourceConfiguration { public boolean isUnlimitedConnections(final InetAddress address) { final Boolean result = unlimitedConnections.getValue(IpInterval.asIpInterval(address)); return result != null && result; } @Autowired IpResourceConfiguration(final Loader loader); boolean isDenied(final InetAddress address); boolean isDenied(final IpInterval address); boolean isProxy(final InetAddress address); boolean isProxy(final IpInterval address); int getLimit(final InetAddress address); int getLimit(final IpInterval address); boolean isUnlimitedConnections(final InetAddress address); boolean isUnlimitedConnections(final IpInterval address); @PostConstruct @Scheduled(fixedDelay = TREE_UPDATE_IN_SECONDS * 1000) synchronized void reload(); }
@Test public void test_unlimitedConnections_default() throws Exception { assertThat(subject.isUnlimitedConnections(inetAddress), is(false)); }
AccessControlListManager { public boolean isDenied(final InetAddress remoteAddress) { return resourceConfiguration.isDenied(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }
@Test public void check_denied_restricted() throws Exception { assertTrue(subject.isDenied(ipv4Restricted)); assertTrue(subject.isDenied(ipv6Restricted)); } @Test public void check_denied_unrestricted() throws Exception { assertFalse(subject.isDenied(ipv4Unrestricted)); assertFalse(subject.isDenied(ipv6Unrestricted)); } @Test public void check_denied_unknown() throws Exception { assertFalse(subject.isDenied(ipv4Unknown)); assertFalse(subject.isDenied(ipv6Unknown)); }
AccessControlListManager { public boolean isAllowedToProxy(final InetAddress remoteAddress) { return resourceConfiguration.isProxy(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }
@Test public void check_proxy_restricted() throws Exception { assertFalse(subject.isAllowedToProxy(ipv4Restricted)); assertFalse(subject.isAllowedToProxy(ipv6Restricted)); } @Test public void check_proxy_unrestricted() throws Exception { assertTrue(subject.isAllowedToProxy(ipv4Unrestricted)); assertTrue(subject.isAllowedToProxy(ipv6Unrestricted)); } @Test public void check_proxy_unknown() throws Exception { assertFalse(subject.isAllowedToProxy(ipv4Unknown)); assertFalse(subject.isAllowedToProxy(ipv6Unknown)); }
AccessControlListManager { int getPersonalDataLimit(final InetAddress remoteAddress) { return resourceConfiguration.getLimit(remoteAddress); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }
@Test public void check_getLimit_restricted() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Restricted), is(PERSONAL_DATA_LIMIT)); assertThat(subject.getPersonalDataLimit(ipv6Restricted), is(PERSONAL_DATA_LIMIT)); } @Test public void check_getLimit_unrestricted() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Unrestricted), is(PERSONAL_DATA_NO_LIMIT)); assertThat(subject.getPersonalDataLimit(ipv6Unrestricted), is(PERSONAL_DATA_NO_LIMIT)); } @Test public void check_getLimit_unknown() throws Exception { assertThat(subject.getPersonalDataLimit(ipv4Unknown), is(PERSONAL_DATA_LIMIT_UNKNOWN)); assertThat(subject.getPersonalDataLimit(ipv6Unknown), is(PERSONAL_DATA_LIMIT_UNKNOWN)); }
AccessControlListManager { public void blockTemporary(final InetAddress hostAddress, final int limit) { IpInterval<?> maskedAddress; if (hostAddress instanceof Inet6Address) { maskedAddress = Ipv6Resource.parse(mask(hostAddress, IPV6_NETMASK).getHostAddress() + "/" + IPV6_NETMASK); } else { maskedAddress = Ipv4Resource.asIpInterval(hostAddress); } accessControlListDao.saveAclEvent(maskedAddress, dateTimeProvider.getCurrentDate(), limit, BlockEvent.Type.BLOCK_TEMPORARY); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }
@Test public void test_if_block_temporary_is_logged() { subject.blockTemporary(ipv6Restricted, PERSONAL_DATA_LIMIT); verify(accessControlListDao).saveAclEvent(ipv6ResourceCaptor.capture(), eq(now), eq(PERSONAL_DATA_LIMIT), eq(BlockEvent.Type.BLOCK_TEMPORARY)); Ipv6Resource ipv6Resource = ipv6ResourceCaptor.getValue(); assertThat(ipv6Resource.toString(), is("2001::/64")); }
AccessControlListManager { public boolean requiresAcl(final RpslObject rpslObject, final Source source) { if (source.isGrs()) { return false; } final ObjectType objectType = rpslObject.getType(); return ObjectType.PERSON.equals(objectType) || (ObjectType.ROLE.equals(objectType) && rpslObject.findAttributes(AttributeType.ABUSE_MAILBOX).isEmpty()); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }
@Test public void requiresAcl_withRipeSource() { assertTrue(subject.requiresAcl(person, Source.slave("RIPE"))); assertTrue(subject.requiresAcl(role, Source.slave("RIPE"))); assertFalse(subject.requiresAcl(roleWithAbuseMailbox, Source.slave("RIPE"))); assertFalse(subject.requiresAcl(autNum, Source.slave("RIPE"))); assertFalse(subject.requiresAcl(inetnum, Source.slave("RIPE"))); assertFalse(subject.requiresAcl(domain, Source.slave("RIPE"))); } @Test public void requiresAcl_withNonRipeSource() { assertFalse(subject.requiresAcl(autNum, Source.slave("APNIC-GRS"))); assertFalse(subject.requiresAcl(person, Source.slave("APNIC-GRS"))); assertFalse(subject.requiresAcl(role, Source.slave("AFRINIC-GRS"))); assertFalse(subject.requiresAcl(person, Source.slave("AFRINIC-GRS"))); assertFalse(subject.requiresAcl(role, Source.slave("JPIRR-GRS"))); assertFalse(subject.requiresAcl(inetnum, Source.slave("JPIRR-GRS"))); assertFalse(subject.requiresAcl(autNum, Source.slave("RADB-GRS"))); } @Test public void requiresAcl_withTest() { assertTrue(subject.requiresAcl(person, Source.slave("TEST"))); assertTrue(subject.requiresAcl(role, Source.slave("TEST"))); assertFalse(subject.requiresAcl(roleWithAbuseMailbox, Source.slave("TEST"))); assertFalse(subject.requiresAcl(autNum, Source.slave("TEST"))); assertFalse(subject.requiresAcl(inetnum, Source.slave("TEST"))); assertFalse(subject.requiresAcl(domain, Source.slave("TEST"))); }
AccessControlListManager { public static InetAddress mask(final InetAddress address, final int mask) { if (address instanceof Inet6Address) { byte[] bytes = address.getAddress(); int part = mask % 8; int firstMaskedIndex = (mask / 8) + (part == 0 ? 0 : 1); for (int i = firstMaskedIndex; i < bytes.length; i++) { bytes[i] = (byte) 0; } if (part != 0) { bytes[mask / 8] &= ~((1 << (8 - part)) - 1); } try { return Inet6Address.getByAddress(bytes); } catch (UnknownHostException e) { LOGGER.warn("We do not change the length; we cannot ever have this exception", e); } } return address; } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }
@Test public void testMask() throws UnknownHostException { InetAddress subject = Inet6Address.getByName("3ffe:6a88:85a3:98d3:1319:8a2e:9370:7344"); assertThat(mask(subject, 125).getHostAddress(), is("3ffe:6a88:85a3:98d3:1319:8a2e:9370:7340")); assertThat(mask(subject, 112).getHostAddress(), is("3ffe:6a88:85a3:98d3:1319:8a2e:9370:0")); assertThat(mask(subject, 96).getHostAddress(), is("3ffe:6a88:85a3:98d3:1319:8a2e:0:0")); assertThat(mask(subject, 80).getHostAddress(), is("3ffe:6a88:85a3:98d3:1319:0:0:0")); assertThat(mask(subject, 64).getHostAddress(), is("3ffe:6a88:85a3:98d3:0:0:0:0")); assertThat(mask(subject, 48).getHostAddress(), is("3ffe:6a88:85a3:0:0:0:0:0")); assertThat(mask(subject, 32).getHostAddress(), is("3ffe:6a88:0:0:0:0:0:0")); assertThat(mask(subject, 16).getHostAddress(), is("3ffe:0:0:0:0:0:0:0")); assertThat(mask(subject, 8).getHostAddress(), is("3f00:0:0:0:0:0:0:0")); assertThat(mask(subject, 7).getHostAddress(), is("3e00:0:0:0:0:0:0:0")); assertThat(mask(subject, 6).getHostAddress(), is("3c00:0:0:0:0:0:0:0")); assertThat(mask(subject, 5).getHostAddress(), is("3800:0:0:0:0:0:0:0")); assertThat(mask(subject, 4).getHostAddress(), is("3000:0:0:0:0:0:0:0")); assertThat(mask(subject, 3).getHostAddress(), is("2000:0:0:0:0:0:0:0")); assertThat(mask(subject, 2).getHostAddress(), is("0:0:0:0:0:0:0:0")); assertThat(mask(subject, 1).getHostAddress(), is("0:0:0:0:0:0:0:0")); assertThat(mask(subject, 0).getHostAddress(), is("0:0:0:0:0:0:0:0")); assertThat(mask(Inet6Address.getByName("::1"), AccessControlListManager.IPV6_NETMASK), is(Inet6Address.getByName("0:0:0:0:0:0:0:0"))); }
AccessControlListManager { public boolean isTrusted(final InetAddress remoteAddress) { return ipRanges.isTrusted(IpInterval.asIpInterval(remoteAddress)); } @Autowired AccessControlListManager(final DateTimeProvider dateTimeProvider, final IpResourceConfiguration resourceConfiguration, final AccessControlListDao accessControlListDao, final PersonalObjectAccounting personalObjectAccounting, final IpRanges ipRanges); boolean requiresAcl(final RpslObject rpslObject, final Source source); boolean isDenied(final InetAddress remoteAddress); boolean isAllowedToProxy(final InetAddress remoteAddress); boolean isUnlimited(final InetAddress remoteAddress); boolean canQueryPersonalObjects(final InetAddress remoteAddress); boolean isTrusted(final InetAddress remoteAddress); int getPersonalObjects(final InetAddress remoteAddress); void accountPersonalObjects(final InetAddress remoteAddress, final int amount); void blockTemporary(final InetAddress hostAddress, final int limit); static InetAddress mask(final InetAddress address, final int mask); }
@Test public void override_from_trusted_range() { when(ipRanges.isTrusted(any(IpInterval.class))).thenReturn(true); assertThat(subject.isTrusted(InetAddresses.forString("10.0.0.1")), is(true)); } @Test public void override_from_untrusted_range() { when(ipRanges.isTrusted(any(IpInterval.class))).thenReturn(false); assertThat(subject.isTrusted(InetAddresses.forString("10.0.0.1")), is(false)); }
HazelcastPersonalObjectAccounting implements PersonalObjectAccounting { @Override public int getQueriedPersonalObjects(final InetAddress remoteAddress) { Integer count = null; try { count = counterMap.get(remoteAddress); } catch (OperationTimeoutException | IllegalStateException e) { LOGGER.debug("{}: {}", e.getClass().getName(), e.getMessage()); } if (count == null) { return 0; } return count; } @PostConstruct void startService(); @PreDestroy void stopService(); @Override int getQueriedPersonalObjects(final InetAddress remoteAddress); @Override int accountPersonalObject(final InetAddress remoteAddress, final int amount); @Override void resetAccounting(); }
@Test public void test_queried_personal_objects() { assertThat(subject.getQueriedPersonalObjects(ipv4Address), is(0)); }
HazelcastPersonalObjectAccounting implements PersonalObjectAccounting { @Override public int accountPersonalObject(final InetAddress remoteAddress, final int amount) { try { Integer count = counterMap.tryLockAndGet(remoteAddress, 3, TimeUnit.SECONDS); if (count == null) { count = amount; } else { count += amount; } counterMap.putAndUnlock(remoteAddress, count); return count; } catch (TimeoutException | IllegalStateException e) { LOGGER.info("Unable to account personal object, allowed by default. Threw " + e.getClass().getName() + ": " + e.getMessage()); } return 0; } @PostConstruct void startService(); @PreDestroy void stopService(); @Override int getQueriedPersonalObjects(final InetAddress remoteAddress); @Override int accountPersonalObject(final InetAddress remoteAddress, final int amount); @Override void resetAccounting(); }
@Test public void test_account_personal_object_amount_1() { for (int i = 1; i < 100; i++) { int balance = subject.accountPersonalObject(ipv4Address, 1); assertThat(balance, is(i)); } }
ReferencedTypeResolver { @Nullable public String getReferencedType(final AttributeType attributeType, final CIString value) { final Set<ObjectType> references = attributeType.getReferences(); switch (references.size()) { case 0: if (AttributeType.MEMBERS.equals(attributeType)) { if (AttributeType.AUT_NUM.isValidValue(ObjectType.AUT_NUM, value)) { return ObjectType.AUT_NUM.getName(); } if (AttributeType.AS_SET.isValidValue(ObjectType.AS_SET, value)) { return ObjectType.AS_SET.getName(); } if (AttributeType.ROUTE_SET.isValidValue(ObjectType.ROUTE_SET, value)) { return ObjectType.ROUTE_SET.getName(); } if (AttributeType.RTR_SET.isValidValue(ObjectType.RTR_SET, value)) { return ObjectType.RTR_SET.getName(); } } return null; case 1: if (AttributeType.AUTH.equals(attributeType)) { final String authType = SPACE_SPLITTER.split(value).iterator().next().toUpperCase(); if (authType.endsWith("-PW") || authType.equals("SSO")) { return null; } } if (AttributeType.MBRS_BY_REF.equals(attributeType)) { if (value.toLowerCase().equals("any")) { return null; } } if (AttributeType.MNT_ROUTES.equals(attributeType)) { try { MNT_ROUTES_PARSER.parse(value.toString()); } catch (AttributeParseException e) { return null; } } return references.iterator().next().getName(); default: if (references.contains(ObjectType.PERSON) || references.contains(ObjectType.ROLE)) { for (ObjectType objectType : references) { if (attributeType.isValidValue(objectType, value)) { try { return rpslObjectDao.findByKey(objectType, value.toString()).getObjectType().getName(); } catch (EmptyResultDataAccessException ignored) { LOGGER.debug("{}: {}", ignored.getClass().getName(), ignored.getMessage()); } } } } else { for (ObjectType objectType : references) { for (AttributeType lookupAttribute : ObjectTemplate.getTemplate(objectType).getLookupAttributes()) { if (lookupAttribute.isValidValue(objectType, value)) { return objectType.getName(); } } } } return null; } } @Autowired ReferencedTypeResolver(@Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao); @Nullable String getReferencedType(final AttributeType attributeType, final CIString value); }
@Test public void auth_attribute_md5() { assertThat(subject.getReferencedType(AttributeType.AUTH, CIString.ciString("MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/")), is(nullValue())); } @Test public void auth_attribute_md5_filtered() { assertThat(subject.getReferencedType(AttributeType.AUTH, CIString.ciString("MD5-PW # Filtered")), is(nullValue())); } @Test public void auth_attribute_x509() { assertThat(subject.getReferencedType(AttributeType.AUTH, CIString.ciString("X509-1")), is("key-cert")); } @Test public void auth_attribute_pgpkey() { assertThat(subject.getReferencedType(AttributeType.AUTH, CIString.ciString("PGPKEY-28F6CD6C")), is("key-cert")); } @Test public void members_by_ref_any() { assertThat(subject.getReferencedType(AttributeType.MBRS_BY_REF, CIString.ciString("ANY")), is(nullValue())); } @Test public void members_by_ref_mntner() { assertThat(subject.getReferencedType(AttributeType.MBRS_BY_REF, CIString.ciString("OWNER-MNT")), is("mntner")); } @Test public void member_of_as_set() { assertThat(subject.getReferencedType(AttributeType.MEMBER_OF, CIString.ciString("AS-TEST")), is("as-set")); } @Test public void member_of_route_set() { assertThat(subject.getReferencedType(AttributeType.MEMBER_OF, CIString.ciString("rs-ripe")), is("route-set")); } @Test public void member_of_rtr_set() { assertThat(subject.getReferencedType(AttributeType.MEMBER_OF, CIString.ciString("RTRS-TEST")), is("rtr-set")); } @Test public void members_as_set() { assertThat(subject.getReferencedType(AttributeType.MEMBERS, CIString.ciString("AS-TEST")), is("as-set")); } @Test public void members_autnum() { assertThat(subject.getReferencedType(AttributeType.MEMBERS, CIString.ciString("AS100")), is("aut-num")); } @Test public void members_route_set() { assertThat(subject.getReferencedType(AttributeType.MEMBERS, CIString.ciString("rs-ripe")), is("route-set")); } @Test public void members_rtr_set() { assertThat(subject.getReferencedType(AttributeType.MEMBERS, CIString.ciString("RTRS-TEST")), is("rtr-set")); } @Test public void mnt_routes_mntner() { assertThat(subject.getReferencedType(AttributeType.MNT_ROUTES, CIString.ciString("OWNER-MNT")), is("mntner")); } @Test public void mnt_routes_mntner_any() { assertThat(subject.getReferencedType(AttributeType.MNT_ROUTES, CIString.ciString("OWNER-MNT ANY")), is("mntner")); } @Test public void mnt_routes_mntner_with_curly_braces() { assertThat(subject.getReferencedType(AttributeType.MNT_ROUTES, CIString.ciString("OWNER-MNT {2a00:c00::/24,2a00:c00::/16}")), is("mntner")); } @Test public void mnt_routes_invalid_syntax() { assertThat(subject.getReferencedType(AttributeType.MNT_ROUTES, CIString.ciString("NONE NONE")), is(nullValue())); } @Test public void person() { when(rpslObjectDao.findByKey(ObjectType.PERSON, "PP1-RIPE")).thenReturn(new RpslObjectInfo(1, ObjectType.PERSON, "PP1-RIPE")); when(rpslObjectDao.findByKey(ObjectType.ROLE, "PP1-RIPE")).thenThrow(EmptyResultDataAccessException.class); assertThat(subject.getReferencedType(AttributeType.TECH_C, CIString.ciString("PP1-RIPE")), is("person")); } @Test public void role() { when(rpslObjectDao.findByKey(ObjectType.ROLE, "RR1-RIPE")).thenReturn(new RpslObjectInfo(1, ObjectType.ROLE, "RR1-RIPE")); when(rpslObjectDao.findByKey(ObjectType.PERSON, "RR1-RIPE")).thenThrow(EmptyResultDataAccessException.class); assertThat(subject.getReferencedType(AttributeType.TECH_C, CIString.ciString("RR1-RIPE")), is("role")); }
DummifierNrtm implements Dummifier { public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The given object type should be skipped", objectType); if (version <= 2 && usePlaceHolder(rpslObject)) { return objectType.equals(ObjectType.ROLE) ? getPlaceholderRoleObject() : getPlaceholderPersonObject(); } final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); stripSomeNonMandatoryAttributes(attributes, objectType); dummifyRemainingAttributes(attributes, rpslObject.getKey()); insertPlaceholder(attributes); attributes.addAll(getDummificationRemarks(rpslObject)); return new RpslObject(rpslObject, attributes); } RpslObject dummify(final int version, final RpslObject rpslObject); boolean isAllowed(final int version, final RpslObject rpslObject); static RpslObject getPlaceholderPersonObject(); static RpslObject getPlaceholderRoleObject(); }
@Test(expected = IllegalArgumentException.class) public void null_type() { subject.dummify(3, RpslObject.parse("FOOO:BAR\n")); } @Test public void dummify_removes_double_person_role_references() { final ArrayList<RpslAttribute> attributes = Lists.newArrayList(createObject(ObjectType.INETNUM, "10.0.0.0").getAttributes()); final String tempValue = "VALUE"; for (AttributeType personRoleReference : DummifierNrtm.PERSON_ROLE_REFERENCES) { final RpslAttribute attribute = new RpslAttribute(personRoleReference.getName(), tempValue); attributes.add(attribute); attributes.add(attribute); } assertThat(attributes, hasSize(3 + 2 * DummifierNrtm.PERSON_ROLE_REFERENCES.size())); attributes.add(new RpslAttribute(AttributeType.SOURCE, "TEST")); final RpslObject rpslObject = new RpslObject(0, attributes); final RpslObject dummifiedObject = subject.dummify(3, rpslObject); for (AttributeType personRoleReference : DummifierNrtm.PERSON_ROLE_REFERENCES) { final List<RpslAttribute> rpslAttributes = dummifiedObject.findAttributes(personRoleReference); assertThat(personRoleReference.toString(), rpslAttributes, hasSize(1)); assertThat(rpslAttributes.get(0).getValue(), is(not(tempValue))); } assertThat(dummifiedObject.findAttributes(AttributeType.CREATED, AttributeType.LAST_MODIFIED), hasSize(2)); } @Test public void dummify_adds_remarks() { final RpslObject routeObject = RpslObject.parse( "route: 10/8\n" + "origin: AS3333\n" + "source: TEST"); final RpslObject dummifiedRouteObject = subject.dummify(3, routeObject); assertThat(dummifiedRouteObject.toString(), is( "route: 10/8\n" + "origin: AS3333\n" + "source: TEST\n" + "remarks: ****************************\n" + "remarks: * THIS OBJECT IS MODIFIED\n" + "remarks: * Please note that all data that is generally regarded as personal\n" + "remarks: * data has been removed from this object.\n" + "remarks: * To view the original object, please query the RIPE Database at:\n" + "remarks: * http: "remarks: ****************************\n")); } @Test public void strip_optional_from_organisation() { final List<RpslAttribute> attributes = Lists.newArrayList(); for (AttributeType attributeType : AttributeType.values()) { if (attributeType != AttributeType.ORGANISATION && attributeType != AttributeType.CREATED && attributeType != AttributeType.LAST_MODIFIED) { final RpslAttribute rpslAttribute = new RpslAttribute(attributeType, "FOO"); attributes.add(rpslAttribute); } } final RpslObject organisation = createObject(ObjectType.ORGANISATION, "FOO", attributes); final RpslObject dummifiedOrganisation = subject.dummify(3, organisation); assertThat(dummifiedOrganisation.toString(), is( "organisation: FOO\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "abuse-c: FOO\n" + "address: Dummy address for FOO\n" + "e-mail: [email protected]\n" + "mnt-by: FOO\n" + "mnt-ref: FOO\n" + "org-name: FOO\n" + "org-type: FOO\n" + "source: FOO\n")); } @Test public void strip_optional_from_mntner() { final List<RpslAttribute> attributes = Lists.newArrayList(); for (AttributeType attributeType : AttributeType.values()) { if (attributeType != AttributeType.MNTNER && attributeType != AttributeType.CREATED && attributeType != AttributeType.LAST_MODIFIED) { final RpslAttribute rpslAttribute = new RpslAttribute(attributeType, "FOO"); attributes.add(rpslAttribute); } } final RpslObject mntner = createObject(ObjectType.MNTNER, "FOO", attributes); final RpslObject dummifiedMntner = subject.dummify(3, mntner); assertThat(dummifiedMntner.toString(), is( "mntner: FOO\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "abuse-c: FOO\n" + "admin-c: DUMY-RIPE\n" + "auth: MD5-PW $1$SaltSalt$DummifiedMD5HashValue. # Real value hidden for security\n" + "mnt-by: FOO\n" + "source: FOO\n" + "upd-to: [email protected]\n")); } @Test public void strip_optional_from_mntner_and_make_replacements() { final RpslObject mntner = RpslObject.parse( "mntner: FOO\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "address: REPLACEME\n" + "address: REPLACEME\n" + "auth: REPLACEME\n" + "auth: REPLACEME\n" + "e-mail: REPLACEME\n" + "e-mail: REPLACEME\n" + "fax-no: REPLACEME\n" + "fax-no: REPLACEME\n" + "phone: REPLACEME\n" + "phone: REPLACEME\n" + "upd-to: REPLACEME\n" + "upd-to: REPLACEME\n" + "source: TEST"); final RpslObject dummifiedMtner = subject.dummify(3, mntner); assertThat(dummifiedMtner.toString(), is( "mntner: FOO\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "auth: MD5-PW $1$SaltSalt$DummifiedMD5HashValue. # Real value hidden for security\n" + "upd-to: [email protected]\n" + "source: TEST\n" + "remarks: ****************************\n" + "remarks: * THIS OBJECT IS MODIFIED\n" + "remarks: * Please note that all data that is generally regarded as personal\n" + "remarks: * data has been removed from this object.\n" + "remarks: * To view the original object, please query the RIPE Database at:\n" + "remarks: * http: "remarks: ****************************\n")); } @Test public void strip_optional_from_organisation_and_make_replacements() { final RpslObject organisation = RpslObject.parse( "organisation: FOO\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "address: REPLACEME\n" + "address: REPLACEME\n" + "auth: REPLACEME\n" + "auth: REPLACEME\n" + "e-mail: REPLACEME\n" + "e-mail: REPLACEME\n" + "fax-no: REPLACEME\n" + "fax-no: REPLACEME\n" + "phone: REPLACEME\n" + "phone: REPLACEME\n" + "upd-to: REPLACEME\n" + "upd-to: REPLACEME\n" + "source: TEST"); final RpslObject dummifiedOrganisation = subject.dummify(3, organisation); assertThat(dummifiedOrganisation.toString(), is( "organisation: FOO\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "address: Dummy address for FOO\n" + "e-mail: [email protected]\n" + "source: TEST\n" + "remarks: ****************************\n" + "remarks: * THIS OBJECT IS MODIFIED\n" + "remarks: * Please note that all data that is generally regarded as personal\n" + "remarks: * data has been removed from this object.\n" + "remarks: * To view the original object, please query the RIPE Database at:\n" + "remarks: * http: "remarks: ****************************\n")); } @Test public void dummify_role_with_abuse_mailbox() { final RpslObject rpslObject = RpslObject.parse(1, "" + "role: Test Role\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "nic-hdl: TR1-TEST\n" + "abuse-mailbox: [email protected]\n" + "source: TEST"); final RpslObject dummified = subject.dummify(3, rpslObject); assertThat(dummified.toString(), is("" + "role: Test Role\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "nic-hdl: TR1-TEST\n" + "abuse-mailbox: [email protected]\n" + "source: TEST\n" + "remarks: ****************************\n" + "remarks: * THIS OBJECT IS MODIFIED\n" + "remarks: * Please note that all data that is generally regarded as personal\n" + "remarks: * data has been removed from this object.\n" + "remarks: * To view the original object, please query the RIPE Database at:\n" + "remarks: * http: "remarks: ****************************\n")); } @Test public void dummify_mntner_keeps_dummy_auth_line_only() { final RpslObject mntner = RpslObject.parse(11, "" + "mntner: AARDVARK-MNT\n" + "descr: Mntner for guy's objects\n" + "admin-c: FB99999-RIPE\n" + "tech-c: FB99999-RIPE\n" + "upd-to: [email protected]\n" + "auth: X509-1\n" + "auth: X509-1689\n" + "auth: MD5-PW $1$SaltSalt$ThisIsABrokenMd5Hash.\n" + "auth: SSO 1234-5678-9abc-dead-beef\n" + "notify: [email protected]\n" + "mnt-by: AARDVARK-MNT\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "source: RIPE # Filtered"); final RpslObject dummified = subject.dummify(3, mntner); assertThat(dummified.findAttribute(AttributeType.AUTH), is(new RpslAttribute("auth", "MD5-PW $1$SaltSalt$DummifiedMD5HashValue."))); assertThat(dummified.getValueForAttribute(AttributeType.CREATED).toString(), is("2001-02-04T17:00:00Z")); assertThat(dummified.getValueForAttribute(AttributeType.LAST_MODIFIED).toString(), is("2001-02-04T17:00:00Z")); }
WhoisRestService { void setDryRun(final UpdateContext updateContext, final String dryRun) { if (isQueryParamSet(dryRun)) { updateContext.dryRun(); } } @Autowired WhoisRestService(final RpslObjectDao rpslObjectDao, final RpslObjectStreamer rpslObjectStreamer, final SourceContext sourceContext, final AccessControlListManager accessControlListManager, final WhoisObjectMapper whoisObjectMapper, final InternalUpdatePerformer updatePerformer, final SsoTranslator ssoTranslator, final LoggerContext loggerContext, final AuthoritativeResourceData authoritativeResourceData, @Value("${api.rest.baseurl}") final String baseUrl); @DELETE @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("/{source}/{objectType}/{key:.*}") Response delete( @Context final HttpServletRequest request, @PathParam("source") final String source, @PathParam("objectType") final String objectType, @PathParam("key") final String key, @QueryParam("reason") @DefaultValue("--") final String reason, @QueryParam("password") final List<String> passwords, @CookieParam("crowd.token_key") final String crowdTokenKey, @QueryParam("override") final String override, @QueryParam("dry-run") final String dryRun); @PUT @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("/{source}/{objectType}/{key:.*}") Response update( final WhoisResources resource, @Context final HttpServletRequest request, @PathParam("source") final String source, @PathParam("objectType") final String objectType, @PathParam("key") final String key, @QueryParam("password") final List<String> passwords, @CookieParam("crowd.token_key") final String crowdTokenKey, @QueryParam("override") final String override, @QueryParam("dry-run") final String dryRun, @QueryParam("unformatted") final String unformatted); @POST @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("/{source}/{objectType}") Response create( final WhoisResources resource, @Context final HttpServletRequest request, @PathParam("source") final String source, @PathParam("objectType") final String objectType, @QueryParam("password") final List<String> passwords, @CookieParam("crowd.token_key") final String crowdTokenKey, @QueryParam("override") final String override, @QueryParam("dry-run") final String dryRun, @QueryParam("unformatted") final String unformatted); @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("/{source}/{objectType}/{key:.*}") Response lookup( @Context final HttpServletRequest request, @PathParam("source") final String source, @PathParam("objectType") final String objectType, @PathParam("key") final String key, @QueryParam("password") final List<String> passwords, @CookieParam("crowd.token_key") final String crowdTokenKey, @QueryParam("unformatted") final String unformatted, @QueryParam("unfiltered") final String unfiltered, @QueryParam("managed-attributes") final String managedAttributes, @QueryParam("resource-holder") final String resourceHolder, @QueryParam("abuse-contact") final String abuseContact); }
@Test public void dryRun_null() { subject.setDryRun(updateContext, null); verify(updateContext, never()).dryRun(); } @Test public void dryRun_false() { subject.setDryRun(updateContext, "fAlsE"); verify(updateContext, never()).dryRun(); } @Test public void dryRun_emptyString() { subject.setDryRun(updateContext, ""); verify(updateContext).dryRun(); } @Test public void dryRun_true() { subject.setDryRun(updateContext, "tRuE"); verify(updateContext).dryRun(); } @Test public void dryRun_whatever() { subject.setDryRun(updateContext, "whatever"); verify(updateContext, never()).dryRun(); }
DummifierNrtm implements Dummifier { public boolean isAllowed(final int version, final RpslObject rpslObject) { return version <= 2 || !usePlaceHolder(rpslObject); } RpslObject dummify(final int version, final RpslObject rpslObject); boolean isAllowed(final int version, final RpslObject rpslObject); static RpslObject getPlaceholderPersonObject(); static RpslObject getPlaceholderRoleObject(); }
@Test public void allow_objects_version_3() { for (ObjectType objectType : ObjectType.values()) { if (DummifierNrtm.SKIPPED_OBJECT_TYPES.contains(objectType)) { continue; } final RpslObject rpslObject = createObject(objectType, "YAY", new RpslAttribute(AttributeType.REMARKS, "Remark!")); assertThat(subject.isAllowed(3, rpslObject), is(true)); } } @Test public void allow_role_with_abuse_mailbox() { final RpslObject role = RpslObject.parse( "role: Test Role\n" + "created: 2001-02-04T17:00:00Z\n" + "last-modified: 2001-02-04T17:00:00Z\n" + "nic-hdl: TR1-TEST\n" + "abuse-mailbox: [email protected]\n" + "source: TEST"); assertThat(subject.isAllowed(3, role), is(true)); }
WhoisRestApi implements Origin { @Override public String getId() { return remoteAddress; } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void getId() { assertThat(subject.getId(), is("127.0.0.1")); }
WhoisRestApi implements Origin { @Override public String getFrom() { return remoteAddress; } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void getFrom() { assertThat(subject.getFrom(), is("127.0.0.1")); }
WhoisRestApi implements Origin { @Override public String getName() { return "rest api"; } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void getName() { assertThat(subject.getName(), is("rest api")); }
WhoisRestApi implements Origin { @Override public String getResponseHeader() { return getHeader(); } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void response_header_for_any_request() { when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.of(2013, 3, 3, 12, 55)); assertThat(subject.getResponseHeader(), is(" - From-Host: 127.0.0.1\n - Date/Time: Sun Mar 3 12:55:00 2013\n")); }
WhoisRestApi implements Origin { @Override public String getNotificationHeader() { return getHeader(); } WhoisRestApi(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void notification_header_for_any_request() { when(dateTimeProvider.getCurrentDateTime()).thenReturn(LocalDateTime.of(2013, 3, 3, 12, 55)); assertThat(subject.getNotificationHeader(), is(" - From-Host: 127.0.0.1\n - Date/Time: Sun Mar 3 12:55:00 2013\n")); }
WhoisSearchService { @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("/search") public Response search( @Context final HttpServletRequest request, @QueryParam("source") final Set<String> sources, @QueryParam("query-string") final String searchKey, @QueryParam("inverse-attribute") final Set<String> inverseAttributes, @QueryParam("include-tag") final Set<String> includeTags, @QueryParam("exclude-tag") final Set<String> excludeTags, @QueryParam("type-filter") final Set<String> types, @QueryParam("flags") final Set<String> flags, @QueryParam("unformatted") final String unformatted, @QueryParam("managed-attributes") final String managedAttributes, @QueryParam("resource-holder") final String resourceHolder, @QueryParam("abuse-contact") final String abuseContact, @QueryParam("limit") final Integer limit, @QueryParam("offset") final Integer offset) { validateSources(request, sources); validateSearchKey(request, searchKey); final Set<QueryFlag> separateFlags = splitInputFlags(request, flags); checkForInvalidFlags(request, separateFlags); final QueryBuilder queryBuilder = new QueryBuilder(); queryBuilder.addFlag(QueryFlag.SHOW_TAG_INFO); queryBuilder.addCommaList(QueryFlag.SOURCES, sources); queryBuilder.addCommaList(QueryFlag.SELECT_TYPES, types); queryBuilder.addCommaList(QueryFlag.INVERSE, inverseAttributes); queryBuilder.addCommaList(QueryFlag.FILTER_TAG_INCLUDE, includeTags); queryBuilder.addCommaList(QueryFlag.FILTER_TAG_EXCLUDE, excludeTags); for (QueryFlag separateFlag : separateFlags) { queryBuilder.addFlag(separateFlag); } final Query query = Query.parse(queryBuilder.build(searchKey), Query.Origin.REST, isTrusted(request)); final Parameters parameters = new Parameters.Builder() .inverseAttributes(new InverseAttributes(inverseAttributes)) .typeFilters(new TypeFilters(types)) .flags(new Flags(separateFlags)) .queryStrings(new QueryStrings(new QueryString(searchKey))) .sources(new Sources(sources)) .managedAttributes(isQueryParamSet(managedAttributes)) .resourceHolder(isQueryParamSet(resourceHolder)) .abuseContact(isQueryParamSet(abuseContact)) .limit(limit) .offset(offset) .unformatted(isQueryParamSet(unformatted)) .build(); return rpslObjectStreamer.handleQueryAndStreamResponse( query, request, InetAddresses.forString(request.getRemoteAddr()), parameters, SEARCH_SERVICE); } @Autowired WhoisSearchService( final AccessControlListManager accessControlListManager, final RpslObjectStreamer rpslObjectStreamer, final SourceContext sourceContext); @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("/search") Response search( @Context final HttpServletRequest request, @QueryParam("source") final Set<String> sources, @QueryParam("query-string") final String searchKey, @QueryParam("inverse-attribute") final Set<String> inverseAttributes, @QueryParam("include-tag") final Set<String> includeTags, @QueryParam("exclude-tag") final Set<String> excludeTags, @QueryParam("type-filter") final Set<String> types, @QueryParam("flags") final Set<String> flags, @QueryParam("unformatted") final String unformatted, @QueryParam("managed-attributes") final String managedAttributes, @QueryParam("resource-holder") final String resourceHolder, @QueryParam("abuse-contact") final String abuseContact, @QueryParam("limit") final Integer limit, @QueryParam("offset") final Integer offset); }
@Test public void search_disallowedFlags() { final List<String> disallowedFlags = ImmutableList.of("t", "template", "v", "verbose", "V", "client", "G", "no-grouping", "no-tag-info", "show-tag-info", "a", "all-sources", "q", "list-sources", "diff-versions", "list-versions", "show-version", "k", "persistent-connection"); for (String disallowedFlag : disallowedFlags) { try { subject.search( request, Sets.newHashSet("TEST"), "AARDVARK-MNT", Collections.EMPTY_SET, Collections.EMPTY_SET, Collections.EMPTY_SET, Collections.EMPTY_SET, Sets.newHashSet(disallowedFlag), null, null, null, null, null, null); fail("Disallowed option " + disallowedFlag + " did not throw error"); } catch (WebApplicationException e) { assertThat(((WhoisResources)e.getResponse().getEntity()).getErrorMessages().get(0).getText(), is("Disallowed search flag '%s'")); } } }
FormattedServerAttributeMapper implements FormattedAttributeMapper { @Override public Collection<Attribute> map(final RpslAttribute rpslAttribute, final String source) { final List<Attribute> result = Lists.newArrayList(); for (CIString value : rpslAttribute.getCleanValues()) { final String referencedType = (rpslAttribute.getType() != null) ? referencedTypeResolver.getReferencedType(rpslAttribute.getType(), value) : null; final Link link = (referencedType != null) ? Link.create(baseUrl, sourceResolver.getSource(referencedType, value, source), referencedType, getLinkValue(rpslAttribute.getType(), value)) : null; result.add(new Attribute(rpslAttribute.getKey(), value.toString(), rpslAttribute.getCleanComment(), referencedType, link, null)); } return result; } @Autowired FormattedServerAttributeMapper(final ReferencedTypeResolver referencedTypeResolver, final SourceResolver sourceResolver, @Value("${api.rest.baseurl}") final String baseUrl); @Override Collection<Attribute> map(final RpslAttribute rpslAttribute, final String source); }
@Test public void map_rpslAttribute_lacking_attributeType() { final Collection<Attribute> attributes = subject.map( new RpslAttribute("key", CIString.ciString("value")), "TEST"); assertThat(attributes, hasSize(1)); final Attribute attribute = attributes.iterator().next(); assertThat(attribute.getLink(), is(nullValue())); assertThat(attribute.getValue(), is("value")); assertThat(attribute.getName(), is("key")); } @Test public void map_rpslAttribute_attributeType_given() { when(referencedTypeResolver.getReferencedType(AttributeType.NIC_HDL, CIString.ciString("TP-TEST"))).thenReturn(AttributeType.ROLE.getName()); final Collection<Attribute> attributes = subject.map( new RpslAttribute(AttributeType.NIC_HDL, CIString.ciString("TP-TEST")), "TEST"); assertThat(attributes, hasSize(1)); final Attribute attribute = attributes.iterator().next(); assertThat(attribute.getLink().toString(), is("locator: http: assertThat(attribute.getName(), is("nic-hdl")); assertThat(attribute.getValue(), is("TP-TEST")); } @Test public void map_rpslAttribute_multiple_values() { when(referencedTypeResolver.getReferencedType(AttributeType.MEMBERS, CIString.ciString("AS1"))).thenReturn(AttributeType.AUT_NUM.getName()); when(referencedTypeResolver.getReferencedType(AttributeType.MEMBERS, CIString.ciString("AS2"))).thenReturn(AttributeType.AUT_NUM.getName()); when(referencedTypeResolver.getReferencedType(AttributeType.MEMBERS, CIString.ciString("AS3"))).thenReturn(AttributeType.AUT_NUM.getName()); final Collection<Attribute> attributes = subject.map(new RpslAttribute(AttributeType.MEMBERS, "AS1, AS2,AS3"), "TEST"); assertThat(attributes, contains( new Attribute("members", "AS1", null, "aut-num", new Link("locator", "http: new Attribute("members", "AS2", null, "aut-num", new Link("locator", "http: new Attribute("members", "AS3", null, "aut-num", new Link("locator", "http: )); } @Test public void map_rpslAttribute_mntRoutes_prefix() { when(referencedTypeResolver.getReferencedType(AttributeType.MNT_ROUTES, CIString.ciString("OWNER-MNT {10.0.0.0/8}"))).thenReturn(AttributeType.MNTNER.getName()); final Collection<Attribute> attributes = subject.map(new RpslAttribute(AttributeType.MNT_ROUTES, "OWNER-MNT {10.0.0.0/8}"), "TEST"); assertThat(attributes, contains( new Attribute("mnt-routes", "OWNER-MNT {10.0.0.0/8}", null, "mntner", new Link("locator", "http: }
WhoisObjectServerMapper { public WhoisObject map(final RpslObject rpslObject, final Parameters parameters) { final Class<? extends AttributeMapper> attributeMapper = getServerAttributeMapper(Boolean.TRUE.equals(parameters.getUnformatted())); return whoisObjectMapper.map(rpslObject, attributeMapper); } @Autowired WhoisObjectServerMapper( final WhoisObjectMapper whoisObjectMapper, final ResourceHolderSearch resourceHolderSearch, final AbuseContactSearch abuseContactSearch, final ManagedAttributeSearch managedAttributeSearch); List<WhoisVersion> mapVersions(final List<DeletedVersionResponseObject> deleted, final List<VersionResponseObject> versions); WhoisObject map(final RpslObject rpslObject, final Parameters parameters); void mapTags(final WhoisObject whoisObject, final TagResponseObject tagResponseObject); void mapResourceHolder(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); void mapAbuseContact(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); void mapManagedAttributes(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); }
@Test public void map_rpsl_mntner() throws Exception { when(referencedTypeResolver.getReferencedType(AttributeType.ADMIN_C, ciString("TP1-TEST"))).thenReturn("person"); when(referencedTypeResolver.getReferencedType(AttributeType.AUTH, ciString("PGPKEY-28F6CD6C"))).thenReturn("key-cert"); when(referencedTypeResolver.getReferencedType(AttributeType.MNT_BY, ciString("TST-MNT"))).thenReturn("mntner"); final RpslObject rpslObject = RpslObject.parse( "mntner: TST-MNT\n" + "descr: MNTNER for test\n" + "admin-c: TP1-TEST\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ # test\n" + "auth: PGPKEY-28F6CD6C\n" + "mnt-by: TST-MNT\n" + "source: TEST\n"); final WhoisObject whoisObject = whoisObjectMapper.map(rpslObject, FormattedServerAttributeMapper.class); assertThat(whoisObject.getType(), is("mntner")); assertThat(whoisObject.getSource().getId(), is("test")); assertThat(whoisObject.getLink().getType(), is("locator")); assertThat(whoisObject.getLink().getHref(), is("http: assertThat(whoisObject.getPrimaryKey(), hasSize(1)); final Attribute primaryKeyAttribute = whoisObject.getPrimaryKey().get(0); assertThat(primaryKeyAttribute.getName(), is("mntner")); assertThat(primaryKeyAttribute.getValue(), is("TST-MNT")); assertThat(whoisObject.getAttributes(), contains( new Attribute("mntner", "TST-MNT", null, null, null, null), new Attribute("descr", "MNTNER for test", null, null, null, null), new Attribute("admin-c", "TP1-TEST", null, "person", Link.create("http: new Attribute("upd-to", "[email protected]", null, null, null, null), new Attribute("auth", "MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/", "test", null, null, null), new Attribute("auth", "PGPKEY-28F6CD6C", null, "key-cert", Link.create("http: new Attribute("mnt-by", "TST-MNT", null, "mntner", Link.create("http: new Attribute("source", "TEST", null, null, null, null) )); } @Test public void map_rpsl_as_set_members_multiple_values() throws Exception { when(referencedTypeResolver.getReferencedType(eq(AttributeType.TECH_C), any(CIString.class))).thenReturn("person"); when(referencedTypeResolver.getReferencedType(eq(AttributeType.ADMIN_C), any(CIString.class))).thenReturn("person"); when(referencedTypeResolver.getReferencedType(eq(AttributeType.MEMBERS), any(CIString.class))).thenReturn("aut-num"); when(referencedTypeResolver.getReferencedType(eq(AttributeType.MNT_BY), any(CIString.class))).thenReturn("mntner"); final RpslObject rpslObject = RpslObject.parse("" + "as-set: AS-set-attendees\n" + "descr: AS-set containing all attendees' ASNs.\n" + "tech-c: TS1-TEST\n" + "admin-c: TS1-TEST\n" + "members: as1,as2,as3\n" + "mnt-by: TS1-MNT\n" + "source: TEST"); final WhoisObject whoisObject = whoisObjectMapper.map(rpslObject, FormattedServerAttributeMapper.class); assertThat(whoisObject.getType(), is("as-set")); assertThat(whoisObject.getSource().getId(), is("test")); assertThat(whoisObject.getLink().getType(), is("locator")); assertThat(whoisObject.getLink().getHref(), is("http: assertThat(whoisObject.getPrimaryKey(), hasSize(1)); final Attribute primaryKeyAttribute = whoisObject.getPrimaryKey().get(0); assertThat(primaryKeyAttribute.getName(), is("as-set")); assertThat(primaryKeyAttribute.getValue(), is("AS-set-attendees")); assertThat(whoisObject.getAttributes(), containsInAnyOrder( new Attribute("as-set", "AS-set-attendees", null, null, null, null), new Attribute("descr", "AS-set containing all attendees' ASNs.", null, null, null, null), new Attribute("tech-c", "TS1-TEST", null, "person", Link.create("http: new Attribute("admin-c", "TS1-TEST", null, "person", Link.create("http: new Attribute("members", "as1", null, "aut-num", Link.create("http: new Attribute("members", "as2", null, "aut-num", Link.create("http: new Attribute("members", "as3", null, "aut-num", Link.create("http: new Attribute("mnt-by", "TS1-MNT", null, "mntner", Link.create("http: new Attribute("source", "TEST", null, null, null, null) )); }
WhoisObjectServerMapper { public List<WhoisVersion> mapVersions(final List<DeletedVersionResponseObject> deleted, final List<VersionResponseObject> versions) { final List<WhoisVersion> whoisVersions = Lists.newArrayList(); for (final DeletedVersionResponseObject deletedVersion : deleted) { whoisVersions.add(new WhoisVersion(deletedVersion.getDeletedDate().toString())); } for (final VersionResponseObject version : versions) { whoisVersions.add(new WhoisVersion(version.getOperation() == Operation.UPDATE ? "ADD/UPD" : "DEL", version.getDateTime().toString(), version.getVersion())); } return whoisVersions; } @Autowired WhoisObjectServerMapper( final WhoisObjectMapper whoisObjectMapper, final ResourceHolderSearch resourceHolderSearch, final AbuseContactSearch abuseContactSearch, final ManagedAttributeSearch managedAttributeSearch); List<WhoisVersion> mapVersions(final List<DeletedVersionResponseObject> deleted, final List<VersionResponseObject> versions); WhoisObject map(final RpslObject rpslObject, final Parameters parameters); void mapTags(final WhoisObject whoisObject, final TagResponseObject tagResponseObject); void mapResourceHolder(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); void mapAbuseContact(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); void mapManagedAttributes(final WhoisObject whoisObject, final Parameters parameters, final RpslObject rpslObject); }
@Test public void map_versions() { final DeletedVersionResponseObject deleted = new DeletedVersionResponseObject(new VersionDateTime(LocalDateTime.now()), ObjectType.AUT_NUM, "AS102"); final List<VersionResponseObject> versionInfos = Lists.newArrayList( new VersionResponseObject(2, Operation.UPDATE, 3, new VersionDateTime(LocalDateTime.now()), ObjectType.AUT_NUM, "AS102"), new VersionResponseObject(2, Operation.UPDATE, 4, new VersionDateTime(LocalDateTime.now()), ObjectType.AUT_NUM, "AS102")); final List<WhoisVersion> whoisVersions = whoisObjectServerMapper.mapVersions(Lists.newArrayList(deleted), versionInfos); assertThat(whoisVersions, hasSize(3)); final WhoisVersion deletedVersion = whoisVersions.get(0); assertThat(deletedVersion.getOperation(), nullValue()); assertThat(deletedVersion.getRevision(), nullValue()); assertThat(deletedVersion.getDeletedDate(), is(not(nullValue()))); final WhoisVersion whoisVersion1 = whoisVersions.get(1); assertThat(whoisVersion1.getOperation(), is("ADD/UPD")); assertThat(whoisVersion1.getRevision(), is(3)); assertThat(whoisVersion1.getDate(), is(not(nullValue()))); final WhoisVersion whoisVersion2 = whoisVersions.get(2); assertThat(whoisVersion2.getOperation(), is("ADD/UPD")); assertThat(whoisVersion2.getRevision(), is(4)); assertThat(whoisVersion2.getDate(), is(not(nullValue()))); }
RestServiceHelper { public static String getRequestURL(final HttpServletRequest request) { return request.getRequestURL().toString() + filter(request.getQueryString()); } private RestServiceHelper(); static String getRequestURL(final HttpServletRequest request); static String getRequestURI(final HttpServletRequest request); static boolean isQueryParamSet(final String queryString, final String key); static boolean isQueryParamSet(final String queryParam); static Class<? extends AttributeMapper> getServerAttributeMapper(final boolean unformatted); static Class<? extends AttributeMapper> getRestResponseAttributeMapper(String queryString); static WhoisResources createErrorEntity(final HttpServletRequest request, final Message... errorMessage); static WhoisResources createErrorEntity(final HttpServletRequest request, final List<Message> errorMessages); static List<ErrorMessage> createErrorMessages(final List<Message> messages); static WebApplicationException createWebApplicationException(final RuntimeException exception, final HttpServletRequest request); static WebApplicationException createWebApplicationException(final RuntimeException exception, final HttpServletRequest request, final List<Message> messages); }
@Test public void getRequestUrl() { assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: assertThat(getRequestURL("http: }
ClientCertificateExtractor { public static Optional<X509CertificateWrapper> getClientCertificate(final HttpServletRequest request, final DateTimeProvider dateTimeProvider) { final String sslClientCert = request.getHeader(HEADER_SSL_CLIENT_CERT); if (StringUtils.isBlank(sslClientCert)) { return Optional.empty(); } if (!hasAcceptableVerifyHeader(request)) { return Optional.empty(); } return getX509Certificate(sslClientCert, dateTimeProvider); } static Optional<X509CertificateWrapper> getClientCertificate(final HttpServletRequest request, final DateTimeProvider dateTimeProvider); }
@Test public void testValidCertificate() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_CERT)).thenReturn(cert); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("GENEROUS"); assertThat(ClientCertificateExtractor.getClientCertificate(request, new ClockDateTimeProvider()).isPresent(), is(true)); } @Test public void testInvalidVerifyHeader() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_CERT)).thenReturn(cert); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("NOT-ACCEPTED"); assertThat(ClientCertificateExtractor.getClientCertificate(request, new ClockDateTimeProvider()).isPresent(), is(false)); } @Test public void testNoCertificate() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("GENEROUS"); assertThat(ClientCertificateExtractor.getClientCertificate(request, new ClockDateTimeProvider()).isPresent(), is(false)); } @Test public void testCertificateExpired() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_CERT)).thenReturn(cert); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("GENEROUS"); final TestDateTimeProvider testDateTimeProvider = new TestDateTimeProvider(); testDateTimeProvider.setTime(LocalDateTime.now().plusYears(5)); assertThat(ClientCertificateExtractor.getClientCertificate(request, testDateTimeProvider).isPresent(), is(false)); } @Test public void testCertificateNotYetValid() { final HttpServletRequest request = mock(HttpServletRequest.class); when(request.getHeader(HEADER_SSL_CLIENT_CERT)).thenReturn(cert); when(request.getHeader(HEADER_SSL_CLIENT_VERIFY)).thenReturn("GENEROUS"); final TestDateTimeProvider testDateTimeProvider = new TestDateTimeProvider(); testDateTimeProvider.setTime(LocalDateTime.now().minusMonths(1)); assertThat(ClientCertificateExtractor.getClientCertificate(request, testDateTimeProvider).isPresent(), is(false)); }
HttpRequestMessage extends Message { private static String toString(final HttpServletRequest request) { return String.format("%s %s\n%s", request.getMethod(), formatUri(request), formatHttpHeaders(request)); } HttpRequestMessage(final HttpServletRequest request); }
@Test public void log_no_headers() { assertThat(toString(request), is("GET /some/path\n")); } @Test public void log_single_header() { request.addHeader("name", "value"); assertThat(toString(request), is("GET /some/path\nHeader: name=value\n")); } @Test public void log_multiple_headers() { request.addHeader("header1", "value1"); request.addHeader("header2", "value2"); request.addHeader("header3", "value3"); assertThat(toString(request), is("GET /some/path\nHeader: header1=value1\nHeader: header2=value2\nHeader: header3=value3\n")); } @Test public void log_empty_query_string() { request.setQueryString(""); assertThat(toString(request), is("GET /some/path\n")); } @Test public void log_encoded_query_parameter() { request.setQueryString("password=p%3Fssword%26"); assertThat(toString(request), is("GET /some/path?password=FILTERED\n")); } @Test public void log_query_parameters_including_password() { request.setQueryString("password=secret"); assertThat(toString(request), is("GET /some/path?password=FILTERED\n")); request.setQueryString("password=secret&param"); assertThat(toString(request), is("GET /some/path?password=FILTERED&param\n")); request.setQueryString("password=secret&password=other"); assertThat(toString(request), is("GET /some/path?password=FILTERED&password=FILTERED\n")); request.setQueryString("password=secret&password=other&param=value"); assertThat(toString(request), is("GET /some/path?password=FILTERED&password=FILTERED&param=value\n")); request.setQueryString("param=value&password=secret&password=other"); assertThat(toString(request), is("GET /some/path?param=value&password=FILTERED&password=FILTERED\n")); request.setQueryString("param=value&password=secret&param=password"); assertThat(toString(request), is("GET /some/path?param=value&password=FILTERED&param=password\n")); }
SyncUpdatesService { @GET @Path("/{source}") @Produces(MediaType.TEXT_PLAIN) public Response doGet( @Context final HttpServletRequest httpServletRequest, @PathParam(SOURCE) final String source, @Encoded @QueryParam(Command.DATA) final String data, @QueryParam(Command.HELP) final String help, @QueryParam(Command.NEW) final String nnew, @QueryParam(Command.DIFF) final String diff, @QueryParam(Command.REDIRECT) final String redirect, @HeaderParam(HttpHeaders.CONTENT_TYPE) final String contentType, @CookieParam("crowd.token_key") final String crowdTokenKey) { final Request request = new Request.RequestBuilder() .setData(decode(data, getCharset(contentType))) .setNew(nnew) .setHelp(help) .setRedirect(redirect) .setDiff(diff) .setRemoteAddress(httpServletRequest.getRemoteAddr()) .setSource(source) .setSsoToken(crowdTokenKey) .build(); return doSyncUpdate(httpServletRequest, request, getCharset(contentType)); } @Autowired SyncUpdatesService(final DateTimeProvider dateTimeProvider, final UpdateRequestHandler updateRequestHandler, final UpdatesParser updatesParser, final LoggerContext loggerContext, final SourceContext sourceContext, final IpRanges ipRanges, final SsoTokenTranslator ssoTokenTranslator); @GET @Path("/{source}") @Produces(MediaType.TEXT_PLAIN) Response doGet( @Context final HttpServletRequest httpServletRequest, @PathParam(SOURCE) final String source, @Encoded @QueryParam(Command.DATA) final String data, @QueryParam(Command.HELP) final String help, @QueryParam(Command.NEW) final String nnew, @QueryParam(Command.DIFF) final String diff, @QueryParam(Command.REDIRECT) final String redirect, @HeaderParam(HttpHeaders.CONTENT_TYPE) final String contentType, @CookieParam("crowd.token_key") final String crowdTokenKey); @POST @Path("/{source}") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) Response doUrlEncodedPost( @Context final HttpServletRequest httpServletRequest, @PathParam(SOURCE) final String source, @FormParam(Command.DATA) final String data, @FormParam(Command.HELP) final String help, @FormParam(Command.NEW) final String nnew, @FormParam(Command.DIFF) final String diff, @FormParam(Command.REDIRECT) final String redirect, @HeaderParam(HttpHeaders.CONTENT_TYPE) final String contentType, @CookieParam("crowd.token_key") final String crowdTokenKey); @POST @Path("/{source}") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_PLAIN) Response doMultipartPost( @Context final HttpServletRequest httpServletRequest, @PathParam(SOURCE) final String source, @FormDataParam(Command.DATA) final String data, @FormDataParam(Command.HELP) final String help, @FormDataParam(Command.NEW) final String nnew, @FormDataParam(Command.DIFF) final String diff, @FormDataParam(Command.REDIRECT) final String redirect, @HeaderParam(HttpHeaders.CONTENT_TYPE) final String contentType, @CookieParam("crowd.token_key") final String crowdTokenKey); }
@Test public void handle_no_parameters() { final String data = null; final String help = null; final String nnew = null; final String diff = null; final String redirect = null; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_BAD_REQUEST)); assertThat(response.getEntity().toString(), is("Invalid request")); } @Test public void handle_only_new_parameter() { final String data = null; final String help = null; final String nnew = "YES"; final String diff = null; final String redirect = null; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_BAD_REQUEST)); assertThat(response.getEntity().toString(), is("DATA parameter is missing")); } @Test public void handle_only_diff_parameter() { final String data = null; final String help = null; final String nnew = null; final String diff = "YES"; final String redirect = null; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_BAD_REQUEST)); assertThat(response.getEntity().toString(), is("the DIFF method is not actually supported by the Syncupdates interface")); } @Test public void handle_only_data_parameter() { final String data = "person"; final String help = null; final String nnew = null; final String diff = null; final String redirect = null; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK)); assertThat(response.getEntity().toString(), is("OK")); } @Test public void handle_unauthorised() { final String data = "person"; final String help = null; final String nnew = null; final String diff = null; final String redirect = null; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; when(messageHandler.handle(any(UpdateRequest.class), any(UpdateContext.class))).thenReturn(new UpdateResponse(UpdateStatus.FAILED_AUTHENTICATION, "FAILED")); final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_UNAUTHORIZED)); assertThat(response.getEntity().toString(), is("FAILED")); } @Test public void handle_diff_and_data_parameters() { final String data = "lkajkafa"; final String help = null; final String nnew = null; final String diff = "YES"; final String redirect = null; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_BAD_REQUEST)); assertThat(response.getEntity().toString(), is("the DIFF method is not actually supported by the Syncupdates interface")); } @Test public void throw_illegal_argument_exception() { try { final String data = "person"; final String help = null; final String nnew = null; final String diff = null; final String redirect = null; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; doThrow(new IllegalArgumentException("some message")). when(messageHandler).handle(any(UpdateRequest.class), any(UpdateContext.class)); subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); fail(); } catch (RuntimeException e) { assertThat(e.getMessage(), is("some message")); } } @Test public void throw_runtime_exception() { try { final String data = "person"; final String help = null; final String nnew = null; final String diff = null; final String redirect = null; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; doThrow(new RuntimeException("some message", new IllegalStateException("some message"))). when(messageHandler).handle(any(UpdateRequest.class), any(UpdateContext.class)); subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); fail(); } catch (RuntimeException e) { assertThat(e.getMessage(), is("some message")); } } @Test public void handle_invalid_encoding() { final String data = "person"; final String help = null; final String nnew = null; final String diff = null; final String redirect = null; final String source = "test"; final String contentType = "text/plain; charset=RGRFE"; final String ssoToken = null; final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK)); assertThat(response.getEntity().toString(), is("OK")); } @Test public void handle_invalid_content_type() { final String data = "person"; final String help = null; final String nnew = null; final String diff = null; final String redirect = null; final String source = "test"; final String contentType = "invalid"; final String ssoToken = null; final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK)); assertThat(response.getEntity().toString(), is("OK")); } @Test public void handle_redirect_allowed() { final String data = "person"; final String help = null; final String nnew = null; final String diff = null; final String redirect = "YES"; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; when(ipRanges.isTrusted(any(Interval.class))).thenReturn(true); final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK)); assertThat(response.getEntity().toString(), is("OK")); } @Test public void handle_redirect_is_ignored() { final String data = "person"; final String help = null; final String nnew = null; final String diff = null; final String redirect = "YES"; final String source = "test"; final String contentType = "UTF-8"; final String ssoToken = null; final Response response = subject.doGet(request, source, data, help, nnew, diff, redirect, contentType, ssoToken); assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK)); assertThat(response.getEntity().toString(), is("OK")); }
InternalUpdatePerformer { public Update createUpdate(final UpdateContext updateContext, final RpslObject rpslObject, final List<String> passwords, final String deleteReason, final String override) { return UpdateCreator.createUpdate( createParagraph(updateContext, rpslObject, passwords, override), deleteReason != null ? Operation.DELETE : Operation.UNSPECIFIED, deleteReason != null ? Lists.newArrayList(deleteReason) : null, rpslObject.toString(), updateContext ); } @Autowired InternalUpdatePerformer(final UpdateRequestHandler updateRequestHandler, final DateTimeProvider dateTimeProvider, final WhoisObjectMapper whoisObjectMapper, final LoggerContext loggerContext, final SsoTokenTranslator ssoTokenTranslator); UpdateContext initContext(final Origin origin, final String ssoToken, final HttpServletRequest request); void closeContext(); WhoisResources performUpdate(final UpdateContext updateContext, final Origin origin, final Update update, final Keyword keyword, final HttpServletRequest request); WhoisResources performUpdates(final UpdateContext updateContext, final Origin origin, final Collection<Update> updates, final Keyword keyword, final HttpServletRequest request); Response createResponse(final UpdateContext updateContext, final WhoisResources whoisResources, final Update update, final HttpServletRequest request); Update createUpdate(final UpdateContext updateContext, final RpslObject rpslObject, final List<String> passwords, final String deleteReason, final String override); Origin createOrigin(final HttpServletRequest request); void setSsoSessionToContext(final UpdateContext updateContext, final String ssoToken); void logInfo(final String message); void logWarning(final String message); void logError(final Throwable t); }
@Test public void create_update_with_override_no_passwords() { final RpslObject object = RpslObject.parse( "aut-num: AS123\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); final Update update = subject.createUpdate(updateContextMock, object, Collections.EMPTY_LIST, "no reason", "override"); assertThat(update.getCredentials().all(), contains((Credential) OverrideCredential.parse("override"))); assertThat(update.getDeleteReasons(), contains("no reason")); assertThat(update.getOperation(), is(Operation.DELETE)); assertThat(update.getParagraph().getContent(), is( "aut-num: AS123\n" + "mnt-by: TEST-MNT\n" + "source: TEST\n")); assertThat(update.getSubmittedObject(), is(object)); assertThat(update.getType(), is(ObjectType.AUT_NUM)); } @Test public void create_update_with_override_and_password_no_delete_reason() { final RpslObject object = RpslObject.parse( "mntner: TEST-MNT\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); final Update update = subject.createUpdate(updateContextMock, object, Collections.singletonList("password"), null, "override"); assertThat(update.getCredentials().all(), containsInAnyOrder((Credential) OverrideCredential.parse("override"), (Credential) new PasswordCredential("password"))); assertNull(update.getDeleteReasons()); assertThat(update.getOperation(), is(Operation.UNSPECIFIED)); assertThat(update.getParagraph().getContent(), is( "mntner: TEST-MNT\n" + "mnt-by: TEST-MNT\n" + "source: TEST\n")); assertThat(update.getSubmittedObject(), is(object)); assertThat(update.getType(), is(ObjectType.MNTNER)); } @Test public void create_update_no_override() { final RpslObject object = RpslObject.parse( "role: Test Role\n" + "nic-hdl: TP-TEST\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); final Update update = subject.createUpdate(updateContextMock, object, Collections.singletonList("password"), "no reason", null); assertThat(update.getCredentials().all(), contains((Credential) new PasswordCredential("password"))); assertThat(update.getDeleteReasons(), contains("no reason")); assertThat(update.getParagraph().getContent(), is( "role: Test Role\n" + "nic-hdl: TP-TEST\n" + "mnt-by: TEST-MNT\n" + "source: TEST\n")); assertThat(update.getSubmittedObject(), is(object)); assertThat(update.getType(), is(ObjectType.ROLE)); } @Test public void create_update_passwords_only() { final RpslObject object = RpslObject.parse( "person: Test Person\n" + "nic-hdl: TP1-TEST\n" + "mnt-by: TEST-MNT\n" + "source: TEST"); final Update update = subject.createUpdate(updateContextMock, object, Lists.newArrayList("password1", "password2"), null, null); assertThat(update.getCredentials().all(), containsInAnyOrder((Credential) new PasswordCredential("password1"), (Credential) new PasswordCredential("password2"))); assertNull(update.getDeleteReasons()); assertThat(update.getParagraph().getContent(), is( "person: Test Person\n" + "nic-hdl: TP1-TEST\n" + "mnt-by: TEST-MNT\n" + "source: TEST\n")); assertThat(update.getSubmittedObject(), is(object)); assertThat(update.getType(), is(ObjectType.PERSON)); }
InternalUpdatePerformer { public Origin createOrigin(final HttpServletRequest request) { return new WhoisRestApi(dateTimeProvider, request.getRemoteAddr()); } @Autowired InternalUpdatePerformer(final UpdateRequestHandler updateRequestHandler, final DateTimeProvider dateTimeProvider, final WhoisObjectMapper whoisObjectMapper, final LoggerContext loggerContext, final SsoTokenTranslator ssoTokenTranslator); UpdateContext initContext(final Origin origin, final String ssoToken, final HttpServletRequest request); void closeContext(); WhoisResources performUpdate(final UpdateContext updateContext, final Origin origin, final Update update, final Keyword keyword, final HttpServletRequest request); WhoisResources performUpdates(final UpdateContext updateContext, final Origin origin, final Collection<Update> updates, final Keyword keyword, final HttpServletRequest request); Response createResponse(final UpdateContext updateContext, final WhoisResources whoisResources, final Update update, final HttpServletRequest request); Update createUpdate(final UpdateContext updateContext, final RpslObject rpslObject, final List<String> passwords, final String deleteReason, final String override); Origin createOrigin(final HttpServletRequest request); void setSsoSessionToContext(final UpdateContext updateContext, final String ssoToken); void logInfo(final String message); void logWarning(final String message); void logError(final Throwable t); }
@Test public void create_origin() { when(requestMock.getRemoteAddr()).thenReturn("127.0.0.1"); when(dateTimeProviderMock.getCurrentDateTime()).thenReturn(ZonedDateTime.parse("2146-01-31T06:49:37.888+00:00").toLocalDateTime()); final Origin origin = subject.createOrigin(requestMock); assertThat(origin.getFrom(), is("127.0.0.1")); assertThat(origin.getId(), is("127.0.0.1")); assertThat(origin.getName(), is("rest api")); assertThat(origin.getNotificationHeader(), containsString("" + "- From-Host: 127.0.0.1\n" + " - Date/Time: Mon Jan 31 06:49:37")); assertThat(origin.getResponseHeader(), containsString("" + "- From-Host: 127.0.0.1\n" + " - Date/Time: Mon Jan 31 06:49:37")); }
InternalUpdatePerformer { public void setSsoSessionToContext(final UpdateContext updateContext, final String ssoToken) { if (!StringUtils.isBlank(ssoToken)) { try { updateContext.setUserSession(ssoTokenTranslator.translateSsoToken(ssoToken)); } catch (CrowdClientException e) { logError(e); updateContext.addGlobalMessage(RestMessages.ssoAuthIgnored()); } } } @Autowired InternalUpdatePerformer(final UpdateRequestHandler updateRequestHandler, final DateTimeProvider dateTimeProvider, final WhoisObjectMapper whoisObjectMapper, final LoggerContext loggerContext, final SsoTokenTranslator ssoTokenTranslator); UpdateContext initContext(final Origin origin, final String ssoToken, final HttpServletRequest request); void closeContext(); WhoisResources performUpdate(final UpdateContext updateContext, final Origin origin, final Update update, final Keyword keyword, final HttpServletRequest request); WhoisResources performUpdates(final UpdateContext updateContext, final Origin origin, final Collection<Update> updates, final Keyword keyword, final HttpServletRequest request); Response createResponse(final UpdateContext updateContext, final WhoisResources whoisResources, final Update update, final HttpServletRequest request); Update createUpdate(final UpdateContext updateContext, final RpslObject rpslObject, final List<String> passwords, final String deleteReason, final String override); Origin createOrigin(final HttpServletRequest request); void setSsoSessionToContext(final UpdateContext updateContext, final String ssoToken); void logInfo(final String message); void logWarning(final String message); void logError(final Throwable t); }
@Test public void setSsoSessionToContext_no_sso_token() { subject.setSsoSessionToContext(updateContextMock, ""); verifyZeroInteractions(ssoTokenTranslatorMock); verifyZeroInteractions(loggerContextMock); subject.setSsoSessionToContext(updateContextMock, null); verifyZeroInteractions(ssoTokenTranslatorMock); verifyZeroInteractions(loggerContextMock); } @Test public void setSsoSessionToContext_successful_sso_translation() { final UserSession userSession = new UserSession("[email protected]", "Test User", true, "2033-01-30T16:38:27.369+11:00"); when(ssoTokenTranslatorMock.translateSsoToken("test-token")).thenReturn(userSession); subject.setSsoSessionToContext(updateContextMock, "test-token"); verify(ssoTokenTranslatorMock).translateSsoToken("test-token"); verifyZeroInteractions(loggerContextMock); verify(updateContextMock).setUserSession(userSession); } @Test public void setSsoSessionToContext_exception_is_logged() { when(ssoTokenTranslatorMock.translateSsoToken("test-token")).thenThrow(new CrowdClientException("exception")); try { subject.setSsoSessionToContext(updateContextMock, "test-token"); } catch (CrowdClientException e) { verify(ssoTokenTranslatorMock.translateSsoToken("test-token")); verify(loggerContextMock).log(new Message(Messages.Type.ERROR, "exception")); verify(updateContextMock).addGlobalMessage(RestMessages.ssoAuthIgnored()); } }
SyncUpdate implements Origin { @Override public String getId() { return getFrom(); } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void getId() { assertThat(subject.getId(), is(LOCALHOST)); }
SyncUpdate implements Origin { @Override public String getFrom() { return remoteAddress; } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void getFrom() { assertThat(subject.getFrom(), is(LOCALHOST)); }
SyncUpdate implements Origin { @Override public String getName() { return "sync update"; } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void getName() { assertThat(subject.getName(), is("sync update")); }
SyncUpdate implements Origin { @Override public String getResponseHeader() { return getHeader(); } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void response_header_for_any_request() { assertThat(subject.getResponseHeader(), containsString("" + " - From-Host: 127.0.0.1\n" + " - Date/Time: Thu Jan 1 00:00:00 1970\n")); }
SyncUpdate implements Origin { @Override public String getNotificationHeader() { return getHeader(); } SyncUpdate(final DateTimeProvider dateTimeProvider, final String remoteAddress); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); @Override String getId(); @Override String getFrom(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void notification_header_for_any_request() { assertThat(subject.getNotificationHeader(), containsString("" + " - From-Host: 127.0.0.1\n" + " - Date/Time: Thu Jan 1 00:00:00 1970\n")); }
PatternFilter extends TokenFilter { protected void tokenize(final CharSequence input) { final Matcher ipv4matcher = IPV4_PATTERN.matcher(input); if (ipv4matcher.find()) { final StringBuilder token = new StringBuilder(); for (int index = 1; index <= ipv4matcher.groupCount(); index++) { final String group = ipv4matcher.group(index); token.append(group); this.tokens.add(token.toString()); } return; } final Matcher ipv6matcher = IPV6_PATTERN.matcher(input); if (ipv6matcher.find()) { final StringBuilder token = new StringBuilder(); for (int index = 1; index <= ipv6matcher.groupCount(); index++) { final String group = ipv6matcher.group(index); if (group == null) { break; } token.append(group); this.tokens.add(token.toString()); } return; } final Matcher emailMatcher = EMAIL_ADDRESS_PATTERN.matcher(input); if (emailMatcher.find()) { tokens.add(emailMatcher.group(1)); return; } } protected PatternFilter(TokenStream input); @Override final boolean incrementToken(); @Override void reset(); }
@Test public void tokenize_ipv4() throws Exception { tokenize("1", "1"); tokenize("1.2.3.4", "1.2.3.4", "1", "1.2", "1.2.3", "1.2.3.4"); tokenize("1.2.3.4/32", "1.2.3.4/32", "1", "1.2", "1.2.3", "1.2.3.4"); tokenize("255.255.255.255", "255.255.255.255", "255", "255.255", "255.255.255", "255.255.255.255"); } @Test public void tokenize_ipv6() throws Exception { tokenize("2001::", "2001::", "2001", "2001:"); tokenize("2001::/16", "2001::/16", "2001", "2001:"); tokenize("2001::2008/128", "2001::2008/128", "2001", "2001:", "2001::2008"); tokenize("a:b:c:d::", "a:b:c:d::", "a", "a:b", "a:b:c", "a:b:c:d"); tokenize("a:b:c:d::/64", "a:b:c:d::/64", "a", "a:b", "a:b:c", "a:b:c:d"); tokenize("2001:2002:2003:2004::", "2001:2002:2003:2004::", "2001", "2001:2002", "2001:2002:2003", "2001:2002:2003:2004"); tokenize("2001:2002:2003:2004::/64", "2001:2002:2003:2004::/64", "2001", "2001:2002", "2001:2002:2003", "2001:2002:2003:2004"); tokenize("a:b:c:d:e:e:e:e", "a:b:c:d:e:e:e:e", "a", "a:b", "a:b:c", "a:b:c:d"); tokenize("2001:2002:2003:2004:2005:2006:2007:2008", "2001:2002:2003:2004:2005:2006:2007:2008", "2001", "2001:2002", "2001:2002:2003", "2001:2002:2003:2004"); tokenize("a:b:c:d:e:e:e:e/128", "a:b:c:d:e:e:e:e/128", "a", "a:b", "a:b:c", "a:b:c:d"); tokenize("2001:2002:2003:2004:2005:2006:2007:2008/128", "2001:2002:2003:2004:2005:2006:2007:2008/128", "2001", "2001:2002", "2001:2002:2003", "2001:2002:2003:2004"); tokenize("2a00:1f78::fffe/48", "2a00:1f78::fffe/48", "2a00", "2a00:1f78"); } @Test public void tokenize_email_addresses() throws Exception { tokenize("[email protected]", "[email protected]", "HOST.ORG"); tokenize("[email protected]", "[email protected]", "ripe.net"); tokenize("[email protected]", "[email protected]", "host.com.au"); tokenize("a@b", "a@b"); } @Test public void tokenize_words() throws Exception { tokenize("aaaa", "aaaa"); tokenize("something", "something"); }
UpdatesParser { public List<Update> parse(final UpdateContext updateContext, final List<ContentWithCredentials> contentWithCredentials) { final List<Paragraph> paragraphs = Lists.newArrayList(); for (final ContentWithCredentials next : contentWithCredentials) { paragraphs.addAll(createParagraphs(next, updateContext)); } final List<Update> updates = Lists.newArrayList(); for (final Paragraph paragraph : paragraphs) { String content = paragraph.getContent(); Operation operation = Operation.UNSPECIFIED; List<String> deleteReasons = Lists.newArrayList(); final Matcher matcher = DELETE_PATTERN.matcher(content); while (matcher.find()) { operation = Operation.DELETE; deleteReasons.add(matcher.group(1).trim()); } if (operation == Operation.DELETE) { content = matcher.reset().replaceAll(""); } if (content.length() > maximumObjectSize) { updateContext.ignore(paragraph); updateContext.addGlobalMessage(UpdateMessages.maximumObjectSizeExceeded(content.length(), maximumObjectSize)); continue; } try { updates.add(createUpdate(paragraph, operation, deleteReasons, content, updateContext)); } catch (IllegalArgumentException e) { updateContext.ignore(paragraph); } } return updates; } @Autowired UpdatesParser(@Value("${whois.max.object.size:5000000}") final long maximumObjectSize); List<Paragraph> createParagraphs(final ContentWithCredentials contentWithCredentials, final UpdateContext updateContext); List<Update> parse(final UpdateContext updateContext, final List<ContentWithCredentials> contentWithCredentials); }
@Test public void no_paragraphs() { final List<Update> updates = subject.parse(updateContext, Lists.newArrayList()); assertThat(updates, hasSize(0)); } @Test public void single_paragraph() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials(MNTNER_DEV_MNT)); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(1)); final Update update = updates.get(0); assertThat(update.getOperation(), is(Operation.UNSPECIFIED)); assertThat(update.getDeleteReasons(), hasSize(0)); assertFalse(update.isOverride()); assertThat(update.getSubmittedObject(), is(RpslObject.parse(MNTNER_DEV_MNT))); assertThat(update.getParagraph().getContent(), is(MNTNER_DEV_MNT)); verify(updateContext, never()).ignore(any(Paragraph.class)); } @Test public void multiple_paragraphs() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials(MNTNER_DEV_MNT)); content.add(new ContentWithCredentials(MNTNER_DEV_MNT)); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(2)); verify(updateContext, never()).ignore(any(Paragraph.class)); } @Test public void delete_before() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials("delete: reason\n" + MNTNER_DEV_MNT)); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(1)); final Update update = updates.get(0); assertThat(update.getOperation(), is(Operation.DELETE)); assertThat(update.getDeleteReasons(), contains("reason")); assertFalse(update.isOverride()); assertThat(update.getSubmittedObject(), is(RpslObject.parse(MNTNER_DEV_MNT))); verify(updateContext, never()).ignore(any(Paragraph.class)); } @Test public void delete_after() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials(MNTNER_DEV_MNT + "\ndelete: reason")); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(1)); final Update update = updates.get(0); assertThat(update.getOperation(), is(Operation.DELETE)); assertThat(update.getDeleteReasons(), contains("reason")); assertFalse(update.isOverride()); assertThat(update.getSubmittedObject(), is(RpslObject.parse(MNTNER_DEV_MNT))); verify(updateContext, never()).ignore(any(Paragraph.class)); } @Test public void delete_middle() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials( "mntner: UPD-MNT\n" + "descr: description\n" + "admin-c: TEST-RIPE\n" + "mnt-by: UPD-MNT\n" + "delete: reason\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$fU9ZMQN9$QQtm3kRqZXWAuLpeOiLN7. # update\n" + "source: TEST\n")); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(1)); final Update update = updates.get(0); assertThat(update.getOperation(), is(Operation.DELETE)); assertThat(update.getDeleteReasons(), contains("reason")); assertFalse(update.isOverride()); assertThat(update.getSubmittedObject(), is(RpslObject.parse("" + "mntner: UPD-MNT\n" + "descr: description\n" + "admin-c: TEST-RIPE\n" + "mnt-by: UPD-MNT\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$fU9ZMQN9$QQtm3kRqZXWAuLpeOiLN7. # update\n" + "source: TEST\n"))); verify(updateContext, never()).ignore(any(Paragraph.class)); } @Test public void delete_multiple() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials(MNTNER_DEV_MNT + "\ndelete: reason1\ndelete: reason2")); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(1)); final Update update = updates.get(0); assertThat(update.getOperation(), is(Operation.DELETE)); assertThat(update.getDeleteReasons(), contains("reason1", "reason2")); assertFalse(update.isOverride()); assertThat(update.getSubmittedObject(), is(RpslObject.parse(MNTNER_DEV_MNT))); } @Test public void broken_override_and_delete_multiple() { final String input = MNTNER_DEV_MNT + "\n delete: reason\n override: pw"; List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials(input)); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(1)); final Update update = updates.get(0); assertThat(update.getOperation(), is(Operation.UNSPECIFIED)); assertThat(update.getDeleteReasons(), hasSize(0)); assertFalse(update.isOverride()); assertThat(update.getSubmittedObject(), is(RpslObject.parse(input))); } @Test public void no_object() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials("some text")); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(0)); verify(updateContext, times(1)).ignore(any(Paragraph.class)); } @Test public void invalid_object() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials("1234:5678")); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(0)); verify(updateContext, times(1)).ignore(any(Paragraph.class)); } @Test public void no_source_still_parses() { List<ContentWithCredentials> content = Lists.newArrayList(); content.add(new ContentWithCredentials("mntner: DEV-MNT")); final List<Update> updates = subject.parse(updateContext, content); assertThat(updates, hasSize(1)); } @Test public void maximum_object_size_exceeded() { final StringBuilder sb = new StringBuilder(); while (sb.length() < 2_000_000) { sb.append("mntner: DEV1-MNT\n"); } subject.parse(updateContext, Lists.newArrayList(new ContentWithCredentials(sb.toString()))); verify(updateContext).addGlobalMessage(eq(UpdateMessages.maximumObjectSizeExceeded(sb.length() - 1, 1_000_000))); }
UpdatesParser { public List<Paragraph> createParagraphs(final ContentWithCredentials contentWithCredentials, final UpdateContext updateContext) { String content = StringUtils.remove(contentWithCredentials.getContent(), '\r'); if (DRY_RUN_PATTERN.matcher(content).find()) { updateContext.dryRun(); } final Set<Credential> baseCredentials = getPasswordCredentials(content); baseCredentials.addAll(contentWithCredentials.getCredentials()); if (updateContext.getUserSession() != null) { baseCredentials.add(SsoCredential.createOfferedCredential(updateContext.getUserSession())); } updateContext.getClientCertificate().ifPresent(x509 -> baseCredentials.add(ClientCertificateCredential.createOfferedCredential(x509))); final List<Paragraph> paragraphs = Lists.newArrayList(); int offset = 0; while (offset < content.length()) { final Matcher signedMessageMatcher = PgpSignedMessage.SIGNED_MESSAGE_PATTERN.matcher(content).region(offset, content.length()); if (signedMessageMatcher.find(offset)) { addPlainTextContent(baseCredentials, paragraphs, content, offset, signedMessageMatcher.start()); offset = addSignedContent(baseCredentials, paragraphs, content, signedMessageMatcher.start(), contentWithCredentials.getCharset()); } else { offset = addPlainTextContent(baseCredentials, paragraphs, content, offset, content.length()); } } return paragraphs; } @Autowired UpdatesParser(@Value("${whois.max.object.size:5000000}") final long maximumObjectSize); List<Paragraph> createParagraphs(final ContentWithCredentials contentWithCredentials, final UpdateContext updateContext); List<Update> parse(final UpdateContext updateContext, final List<ContentWithCredentials> contentWithCredentials); }
@Test public void empty_message() { final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(""), updateContext); assertThat(paragraphs, hasSize(0)); } @Test public void single_paragraph_unsigned() { final ContentWithCredentials contentWithCredentials = new ContentWithCredentials("" + "mntner: DEV-MNT\n" + "password: pass\n"); final List<Paragraph> paragraphs = subject.createParagraphs(contentWithCredentials, updateContext); assertThat(paragraphs, hasSize(1)); assertParagraphNoDryRun(paragraphs.get(0), "mntner: DEV-MNT", new PasswordCredential("pass")); } @Test public void multiple_paragraphs_unsigned() { final String content1 = "" + "mntner: DEV-MNT\n" + "password: pass"; final String content2 = "mntner: DEV2-MNT"; final ContentWithCredentials contentWithCredentials = new ContentWithCredentials(content1 + "\n\n" + content2); final List<Paragraph> paragraphs = subject.createParagraphs(contentWithCredentials, updateContext); assertThat(paragraphs, hasSize(2)); assertParagraphNoDryRun(paragraphs.get(0), "mntner: DEV-MNT", new PasswordCredential("pass")); assertParagraphNoDryRun(paragraphs.get(1), "mntner: DEV2-MNT", new PasswordCredential("pass")); } @Test public void single_paragraph_signed() { final String content = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n\n" + INPUT + "\n" + SIGNATURE; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(1)); assertParagraphNoDryRun( paragraphs.get(0), "mntner: DEV-MNT", PgpCredential.createOfferedCredential(content), new PasswordCredential("pass")); } @Test public void multiple_paragraphs_signed() { final String content = "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n\n" + INPUT + "\n" + SIGNATURE; final ContentWithCredentials contentWithCredentials = new ContentWithCredentials(content + "\n\n" + content); final List<Paragraph> paragraphs = subject.createParagraphs(contentWithCredentials, updateContext); assertThat(paragraphs, hasSize(2)); for (final Paragraph paragraph : paragraphs) { assertParagraphNoDryRun(paragraph, "mntner: DEV-MNT", new PasswordCredential("pass"), PgpCredential.createOfferedCredential(content)); } } @Test public void multiple_paragraphs_mixed() { final String content1 = "" + "mntner: DEV1-MNT\n" + "password: pw"; final String content2 = "mntner: DEV2-MNT"; final String content = "" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n\n" + INPUT + "\n" + SIGNATURE + "\n\n" + content1 + "\n\n" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n\n" + INPUT + "\n" + SIGNATURE + "\n\n" + content2; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(4)); final PasswordCredential pass = new PasswordCredential("pass"); final PasswordCredential pw = new PasswordCredential("pw"); final PgpCredential pgpCredential = PgpCredential.createOfferedCredential( "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n\n" + INPUT + "\n" + SIGNATURE + "\n\n"); assertParagraphNoDryRun(paragraphs.get(0), "mntner: DEV-MNT", pass, pw, pgpCredential); assertParagraphNoDryRun(paragraphs.get(1), "mntner: DEV1-MNT", pass, pw); assertParagraphNoDryRun(paragraphs.get(2), "mntner: DEV-MNT", pass, pw, pgpCredential); assertParagraphNoDryRun(paragraphs.get(3), "mntner: DEV2-MNT", pass, pw); } @Test public void dryRun() { final String content = "" + "mntner: DEV-MNT\n" + "dry-run: some dry run"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(1)); final Paragraph paragraph = paragraphs.get(0); assertThat(paragraph.getContent(), is("mntner: DEV-MNT")); assertThat(paragraph.getCredentials().all(), hasSize(0)); verify(updateContext).dryRun(); } @Test public void dryRun_detached() { final String content = "" + "mntner: DEV-MNT\n" + "\n" + "\n" + "\n" + "dry-run: some dry run"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(2)); final Paragraph paragraph1 = paragraphs.get(0); assertThat(paragraph1.getContent(), is("mntner: DEV-MNT")); assertThat(paragraph1.getCredentials().all(), hasSize(0)); final Paragraph paragraph2 = paragraphs.get(1); assertThat(paragraph2.getContent(), is("")); assertThat(paragraph2.getCredentials().all(), hasSize(0)); verify(updateContext).dryRun(); } @Test public void dryRun_specified_multiple_times() { final String content = "" + "mntner: DEV-MNT\n" + "dry-run: some dry run\n" + "dry-run: some dry run\n" + "dry-run: some dry run"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(1)); final Paragraph paragraph = paragraphs.get(0); assertThat(paragraph.getContent(), is("mntner: DEV-MNT")); assertThat(paragraph.getCredentials().all(), hasSize(0)); verify(updateContext).dryRun(); } @Test public void dryRun_multiple_objects() { final String content = "" + "mntner: DEV1-MNT\n" + "dry-run: some dry run\n" + "\n" + "mntner: DEV2-MNT\n"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(2)); final Paragraph paragraph1 = paragraphs.get(0); assertThat(paragraph1.getContent(), is("mntner: DEV1-MNT")); assertThat(paragraph1.getCredentials().all(), hasSize(0)); final Paragraph paragraph2 = paragraphs.get(1); assertThat(paragraph2.getContent(), is("mntner: DEV2-MNT")); assertThat(paragraph2.getCredentials().all(), hasSize(0)); verify(updateContext).dryRun(); } @Test public void dryrun_anywhere() { final String content = "" + "dry-run:\n" + "mntner: DEV1-MNT\n" + "password:pwd\n"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(1)); final Paragraph paragraph = paragraphs.get(0); assertThat(paragraph.getContent(), is("mntner: DEV1-MNT")); verify(updateContext).dryRun(); } @Test public void dryrun_removal_leaves_no_blankline() { final String content = "" + "person: First Person\n" + "address: Burnley\n" + "dry-run:\n" + "nic-hdl: TEST-TEST\n" + "source: TEST\n" + "\n" + "password: owner"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(2)); assertThat(paragraphs.get(0).getContent(), is("person: First Person\n" + "address: Burnley\n" + "nic-hdl: TEST-TEST\n" + "source: TEST")); assertThat(paragraphs.get(1).getContent(), is("")); } @Test public void password_with_whitespace() { final String content = "" + "mntner: DEV-MNT\n" + "password: \t 123 and something \t \r\n"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs, hasSize(1)); assertParagraphNoDryRun(paragraphs.get(0), "mntner: DEV-MNT", new PasswordCredential("123 and something")); } @Test public void single_content_multiple_passwords() { final List<Paragraph> paragraphs = subject.createParagraphs( new ContentWithCredentials("" + "mntner: DEV-MNT\n" + "descr: DEV maintainer\n" + "password: pass1\n" + "password: pass2\n" + "password: pass2\n"), updateContext); assertThat(paragraphs, hasSize(1)); final Paragraph paragraph = paragraphs.get(0); assertThat(paragraph.getCredentials().all(), hasSize(2)); assertThat(paragraph.getCredentials().ofType(PasswordCredential.class), containsInAnyOrder(new PasswordCredential("pass1"), new PasswordCredential("pass2"))); } @Test public void invalid_password() { final List<Paragraph> paragraphs = subject.createParagraphs( new ContentWithCredentials("" + "mntner: DEV-MNT\n" + "descr: DEV maintainer\n" + " password: pass1\n"), updateContext); assertThat(paragraphs, hasSize(1)); final Paragraph paragraph = paragraphs.get(0); assertThat(paragraph.getCredentials().all(), hasSize(0)); } @Test public void multiple_passwords_in_different_paragraphs() { final List<Paragraph> paragraphs = subject.createParagraphs( new ContentWithCredentials("" + "mntner: DEV-MNT\n" + "password: password1\n\n" + "mntner: DEV-MNT2\n" + "password: password2"), updateContext); assertThat(paragraphs, hasSize(2)); final Credential[] expectedCredentials = {new PasswordCredential("password1"), new PasswordCredential("password2")}; assertThat(paragraphs.get(0).getCredentials().all(), contains(expectedCredentials)); assertThat(paragraphs.get(1).getCredentials().all(), contains(expectedCredentials)); } @Test(timeout = 2000) public void testPerformance() throws Exception { final String content = IOUtils.toString(new ClassPathResource("testMail/giantRawUnsignedObject").getInputStream()); subject.createParagraphs(new ContentWithCredentials(content + "\n\n" + content), updateContext); } @Test public void multiple_paragraphs_password_attribute_removed_completely() { final String content = "" + "mntner:one\n" + "password: one\n" + "source: RIPE\n" + "\n" + "password: two\n" + "\n" + "mntner:two\n" + "source:RIPE\n" + "password:three\n" + "\n" + "mntner:three\n" + "source:RIPE\n" + "password:four"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs.size(), is(4)); assertThat(paragraphs.get(0).getContent(), is("mntner:one\nsource: RIPE")); assertThat(paragraphs.get(1).getContent(), is("")); assertThat(paragraphs.get(2).getContent(), is("mntner:two\nsource:RIPE")); assertThat(paragraphs.get(3).getContent(), is("mntner:three\nsource:RIPE")); assertThat(paragraphs.get(3).getCredentials().all(), hasSize(4)); } @Test public void multiple_paragraphs_password_attribute_removed_completely_windows_lineending() { final String content = "" + "mntner:one\r\n" + "password: one\r\n" + "source: RIPE\r\n" + "\r\n" + "password: two\r\n" + "\r\n" + "mntner:two\r\n" + "source:RIPE\r\n" + "password:three\r\n" + "\r\n" + "mntner:three\r\n" + "source:RIPE\r\n" + "password:four"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs.size(), is(4)); assertThat(paragraphs.get(0).getContent(), is("mntner:one\nsource: RIPE")); assertThat(paragraphs.get(1).getContent(), is("")); assertThat(paragraphs.get(2).getContent(), is("mntner:two\nsource:RIPE")); assertThat(paragraphs.get(3).getContent(), is("mntner:three\nsource:RIPE")); assertThat(paragraphs.get(3).getCredentials().all(), hasSize(4)); } @Test public void multiple_paragraphs_override_attribute_removed_completely() { final String content = "" + "mntner:one\n" + "override: one\n" + "source: RIPE\n" + "\n" + "override: two\n" + "\n" + "mntner:two\n" + "source: RIPE\n" + "override: three\n\n" + "mntner:three\n" + "source:RIPE\n" + "override:three"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs.size(), is(4)); assertThat(paragraphs.get(0).getContent(), is("mntner:one\nsource: RIPE")); assertThat(paragraphs.get(1).getContent(), is("")); assertThat(paragraphs.get(2).getContent(), is("mntner:two\nsource: RIPE")); assertThat(paragraphs.get(3).getContent(), is("mntner:three\nsource:RIPE")); } @Test public void signed_message() { final String content = "" + "\n" + "\n" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "mntner: SHRYANE-MNT\n" + "descr: description\n" + "admin-c: AA1-TEST\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$8Lm6as7E$ZwbUWIP3BfNAHjhS/RGHi.\n" + "auth: PGPKEY-28F6CD6C\n" + "mnt-by: SHRYANE-MNT\n" + "remarks: 3\n" + "source: RIPE\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJVXytBAAoJELvMuy1XY5UNcSkH/3FzhXBSdyYLK0CQjUOAJ5Te\n" + "xR5h69m1MMvBJXfFxpZN34renHxrQKypN0L09wVEKfvUYRPB6u1d/LqATjEOd5cV\n" + "Li6V4AvOx+Kd2IEpWUaXw2rO/v02Iw3d6rXMy3dnl8XN0xFDkGxMXO1jPpGmfL8j\n" + "WXTtKxt9Vcpp9WRkFix0jtMPlvNId4Gy3NOEm70v25fm8DO+X8Lp+GU9Ko4u5VC1\n" + "nPPgO0EH4eWtpaJFQAIFrHzQRa8HxFNsXzjYuFV4B5WO2aGTgGD3eexRAFPGczMG\n" + "z8paI/+V51hgi7uF1I2XzT/NndD/NG7SmrZD0I4DP5LO7TUv4UueB4qz/MRwE/o=\n" + "=LbbV\n" + "-----END PGP SIGNATURE-----\n"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs.size(), is(1)); assertThat(paragraphs.get(0).getContent(), is("" + "mntner: SHRYANE-MNT\n" + "descr: description\n" + "admin-c: AA1-TEST\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$8Lm6as7E$ZwbUWIP3BfNAHjhS/RGHi.\n" + "auth: PGPKEY-28F6CD6C\n" + "mnt-by: SHRYANE-MNT\n" + "remarks: 3\n" + "source: RIPE")); assertThat(paragraphs.get(0).getCredentials().all(), hasSize(1)); assertThat(paragraphs.get(0).getCredentials().all(), containsInAnyOrder(PgpCredential.createOfferedCredential(content))); } @Test public void double_signed_message() { final String content = "" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "- -----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "person: Admin Person\n" + "address: Admin Road\n" + "address: Town\n" + "address: UK\n" + "phone: +44 282 411141\n" + "nic-hdl: TEST-RIPE\n" + "mnt-by: ADMIN-MNT\n" + "source: TEST\n" + "- -----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJVXy2AAAoJELvMuy1XY5UN2EIH/2zL1L/d86Eoh7bZOSvO/lgk\n" + "v0TgTnvYAC/KFK+hL5CMe9bpxoChTDiVTQ4WOD+7dvkFbrXE+bG6rBfxuGz4eANz\n" + "24Wck/6e1OMLtuQsinkjsc7j7QfkldMF3wqHpQQyX2TpOi0zdn5XMXc5vC5KpeOX\n" + "R1XlE2Jr/8WWraOYfJS8PSfsenDjbIUtLABNS/5xXHbthh7Hn+4SSgNlsPS11pxj\n" + "pl+Xl0XLyUYJs6/Eq7mbsjfk29fYl+ESNKUPzLMc0LTTqgRUtL3Z8EVcgxZOZrz1\n" + "pjbi+CjLqMgrCS7krYvCcA60R6mO/ag+zC1OjQUvn38VDiDWg3zSiS1NCQyVeZU=\n" + "=xeQe\n" + "- -----END PGP SIGNATURE-----\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJVXy2EAAoJELvMuy1XY5UNbNQH/i4ZeTQ27IcYQ7CSyaUEil1p\n" + "WUpExiVZt/cXFtZVpDDVQVkPf9jBYB7Y06k70/4QD+ItOsL6m+JJMvbUAbHgpDfC\n" + "fLB6OjgUbY4qhlW3a1QRDza+CNAOC9ldVaVcXs3LZJr9WLYwHPMfFha/Ar3RtOeo\n" + "tQd99ZsiQ5HswjmtrL+sHHzJ3VnT0FyjMskpE6yk+5szp389KjFw87HT0jvGT5zj\n" + "ysunmUoq8b253oeeWvM3mLhgDPFRlGloOJGwVYFNz/HuxukKtm6LGCi3GBORX12q\n" + "DpeIJbppxGpcCHaesC1KMReltUjun/AKaxd92anuwYPe6kAUk6QeCuy6JmvF7Pc=\n" + "=imcM\n" + "-----END PGP SIGNATURE-----\n"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs.size(), is(1)); assertThat(paragraphs.get(0).getContent(), is("" + "person: Admin Person\n" + "address: Admin Road\n" + "address: Town\n" + "address: UK\n" + "phone: +44 282 411141\n" + "nic-hdl: TEST-RIPE\n" + "mnt-by: ADMIN-MNT\n" + "source: TEST")); assertThat(paragraphs.get(0).getCredentials().ofType(PgpCredential.class), hasSize(2)); } @Test public void triple_signed_message() { final String content = "" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "- -----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "- - -----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "\n" + "person: Admin Person\n" + "address: Admin Road\n" + "address: Town\n" + "address: UK\n" + "phone: +44 282 411141\n" + "nic-hdl: TEST-RIPE\n" + "mnt-by: ADMIN-MNT\n" + "source: TEST\n" + "- - -----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJVXy2AAAoJELvMuy1XY5UN2EIH/2zL1L/d86Eoh7bZOSvO/lgk\n" + "v0TgTnvYAC/KFK+hL5CMe9bpxoChTDiVTQ4WOD+7dvkFbrXE+bG6rBfxuGz4eANz\n" + "24Wck/6e1OMLtuQsinkjsc7j7QfkldMF3wqHpQQyX2TpOi0zdn5XMXc5vC5KpeOX\n" + "R1XlE2Jr/8WWraOYfJS8PSfsenDjbIUtLABNS/5xXHbthh7Hn+4SSgNlsPS11pxj\n" + "pl+Xl0XLyUYJs6/Eq7mbsjfk29fYl+ESNKUPzLMc0LTTqgRUtL3Z8EVcgxZOZrz1\n" + "pjbi+CjLqMgrCS7krYvCcA60R6mO/ag+zC1OjQUvn38VDiDWg3zSiS1NCQyVeZU=\n" + "=xeQe\n" + "- - -----END PGP SIGNATURE-----\n" + "- -----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJVXy2EAAoJELvMuy1XY5UNbNQH/i4ZeTQ27IcYQ7CSyaUEil1p\n" + "WUpExiVZt/cXFtZVpDDVQVkPf9jBYB7Y06k70/4QD+ItOsL6m+JJMvbUAbHgpDfC\n" + "fLB6OjgUbY4qhlW3a1QRDza+CNAOC9ldVaVcXs3LZJr9WLYwHPMfFha/Ar3RtOeo\n" + "tQd99ZsiQ5HswjmtrL+sHHzJ3VnT0FyjMskpE6yk+5szp389KjFw87HT0jvGT5zj\n" + "ysunmUoq8b253oeeWvM3mLhgDPFRlGloOJGwVYFNz/HuxukKtm6LGCi3GBORX12q\n" + "DpeIJbppxGpcCHaesC1KMReltUjun/AKaxd92anuwYPe6kAUk6QeCuy6JmvF7Pc=\n" + "=imcM\n" + "- -----END PGP SIGNATURE-----\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "\n" + "iQEcBAEBAgAGBQJVXy2yAAoJELvMuy1XY5UNo9MH/iQhTzsiY0Z66e3f0YKQNq2y\n" + "wws1+eh1cICMnRBioPyY6CoHzfiTiQRIz7ctFHTg2Nylmn9cz54CZLqZlPM9RFEQ\n" + "g/dV+CwVwNWGAJDq/krrvjN7dae4Kb0Kkf3sy+YbIXPVooVVVcoDZRRsB8yJHLm+\n" + "zHqhq7fdCvgbSigr+uKV73QwPbZA3/h1WMG+kWvONxOQhWkEVuR1QWi/YI8uTHjt\n" + "1+5YTsZkvC/skjIvIO7iIFhxSLR8mq3kdIkyhVOTpORtfGuuTf5idUnu2pad5Y9u\n" + "U6PD8iB1dCatjlsUhqMzunNa0sbbizDZPSvSKlPQ+CJAHrGglfd1hgqFKJxmqEY=\n" + "=aaHZ\n" + "-----END PGP SIGNATURE-----\n"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs.size(), is(1)); assertThat(paragraphs.get(0).getContent(), is("" + "person: Admin Person\n" + "address: Admin Road\n" + "address: Town\n" + "address: UK\n" + "phone: +44 282 411141\n" + "nic-hdl: TEST-RIPE\n" + "mnt-by: ADMIN-MNT\n" + "source: TEST")); assertThat(paragraphs.get(0).getCredentials().ofType(PgpCredential.class), hasSize(3)); } @Test public void malformed_pgp_signed_message() { final String content = "" + "-----BEGIN PGP SIGNED MESSAGE-----\n" + "Hash: SHA1\n" + "mntner: SHRYANE-MNT\n" + "descr: description\n" + "admin-c: AA1-TEST\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$8Lm6as7E$ZwbUWIP3BfNAHjhS/RGHi.\n" + "auth: PGPKEY-28F6CD6C\n" + "mnt-by: SHRYANE-MNT\n" + "remarks: 3\n" + "source: RIPE\n" + "-----BEGIN PGP SIGNATURE-----\n" + "Version: GnuPG v1\n" + "Comment: GPGTools - http: "iQEcBAEBAgAGBQJVXytBAAoJELvMuy1XY5UNcSkH/3FzhXBSdyYLK0CQjUOAJ5Te\n" + "xR5h69m1MMvBJXfFxpZN34renHxrQKypN0L09wVEKfvUYRPB6u1d/LqATjEOd5cV\n" + "Li6V4AvOx+Kd2IEpWUaXw2rO/v02Iw3d6rXMy3dnl8XN0xFDkGxMXO1jPpGmfL8j\n" + "WXTtKxt9Vcpp9WRkFix0jtMPlvNId4Gy3NOEm70v25fm8DO+X8Lp+GU9Ko4u5VC1\n" + "nPPgO0EH4eWtpaJFQAIFrHzQRa8HxFNsXzjYuFV4B5WO2aGTgGD3eexRAFPGczMG\n" + "z8paI/+V51hgi7uF1I2XzT/NndD/NG7SmrZD0I4DP5LO7TUv4UueB4qz/MRwE/o=\n" + "=LbbV\n" + "-----END PGP SIGNATURE-----"; final List<Paragraph> paragraphs = subject.createParagraphs(new ContentWithCredentials(content), updateContext); assertThat(paragraphs.size(), is(1)); assertThat(paragraphs.get(0).getContent(), is(content)); assertThat(paragraphs.get(0).getCredentials().all(), hasSize(0)); }
DelegatedStatsService implements EmbeddedValueResolverAware { public URI getUriForRedirect(final String requestPath, final Query query) { final Optional<ObjectType> objectType = query.getObjectTypes().stream() .filter(ALLOWED_OBJECTTYPES::contains) .findFirst(); if (objectType.isPresent()) { for (Map.Entry<CIString, String> entry : sourceToPathMap.entrySet()) { final CIString sourceName = entry.getKey(); final AuthoritativeResource authoritativeResource = resourceData.getAuthoritativeResource(sourceName); if (authoritativeResource.isMaintainedInRirSpace(objectType.get(), CIString.ciString(query.getSearchValue()))) { final String basePath = entry.getValue(); LOGGER.debug("Redirecting {} to {}", requestPath, sourceName); return URI.create(String.format("%s%s", basePath, requestPath.replaceFirst("/rdap", ""))); } } } LOGGER.debug("Resource {} not found", query.getSearchValue()); throw new WebApplicationException(Response.Status.NOT_FOUND); } @Autowired DelegatedStatsService(@Value("${rdap.sources:}") String rdapSourceNames, final AuthoritativeResourceData resourceData); @Override void setEmbeddedValueResolver(StringValueResolver valueResolver); URI getUriForRedirect(final String requestPath, final Query query); boolean isMaintainedInRirSpace(final CIString source, final ObjectType objectType, final CIString pkey); }
@Test public void getUri_value_not_found() { try { subject.getUriForRedirect("/rdap/autnum/3546", Query.parse("-T aut-num AS3546")); fail(); } catch (WebApplicationException expected) { assertThat(expected.getResponse().getStatus(), is(Response.Status.NOT_FOUND.getStatusCode())); } }
RdapObjectMapper { public Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact) { return mapCommons(getRdapObject(requestUrl, rpslObject, lastChangedTimestamp, abuseContact), requestUrl); } @Autowired RdapObjectMapper( final NoticeFactory noticeFactory, @Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, @Value("${rdap.port43:}") final String port43); Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); }
@Test public void ip() { final AbuseContact abuseContact = new AbuseContact( RpslObject.parse( "role: Abuse Contact\n" + "nic-hdl: AB-TEST\n" + "mnt-by: TEST-MNT\n" + "admin-c: TP1-TEST\n" + "tech-c: TP2-TEST\n" + "phone: +31 12345678\n" + "source: TEST" ), false, ciString("") ); final Ip result = (Ip) map( RpslObject.parse( "inetnum: 10.0.0.0 - 10.255.255.255\n" + "netname: RIPE-NCC\n" + "descr: some descr\n" + "country: NL\n" + "admin-c: TP1-TEST\n" + "tech-c: TP1-TEST\n" + "status: OTHER\n" + "language: EN\n" + "language: DK\n" + "mnt-by: TST-MNT\n" + "mnt-lower: TST-MNT\n" + "mnt-domains: TST-MNT\n" + "mnt-routes: TST-MNT\n" + "mnt-irt: irt-IRT1\n" + "notify: [email protected]\n" + "org: ORG-TOL1-TEST\n" + "source: TEST"), Optional.of(abuseContact)); assertThat(result.getHandle(), is("10.0.0.0 - 10.255.255.255")); assertThat(result.getStartAddress(), is("10.0.0.0")); assertThat(result.getEndAddress(), is("10.255.255.255")); assertThat(result.getIpVersion(), is("v4")); assertThat(result.getName(), is("RIPE-NCC")); assertThat(result.getType(), is("OTHER")); assertThat(result.getCountry(), is("NL")); assertThat(result.getLang(), is("EN")); assertThat(result.getParentHandle(), is("0.0.0.0 - 255.255.255.255")); assertThat(result.getPort43(), is("whois.ripe.net")); final List<Entity> entities = result.getEntitySearchResults(); assertThat(entities, hasSize(4)); assertThat(entities.get(0).getHandle(), is("ORG-TOL1-TEST")); assertThat(entities.get(0).getRoles().get(0), is(Role.REGISTRANT)); assertThat(entities.get(1).getHandle(), is("TP1-TEST")); assertThat(entities.get(1).getRoles(), hasSize(2)); assertThat(entities.get(1).getRoles(), containsInAnyOrder(Role.ADMINISTRATIVE, Role.TECHNICAL)); assertThat(entities.get(2).getHandle(), is("TST-MNT")); assertThat(entities.get(2).getRoles(), hasSize(1)); assertThat(entities.get(2).getRoles().get(0), is(Role.REGISTRANT)); assertThat(entities.get(3).getHandle(), is("AB-TEST")); assertThat(entities.get(3).getRoles(), hasSize(1)); assertThat(entities.get(3).getRoles().get(0), is(Role.ABUSE)); final List<Object> vCardArray = entities.get(3).getVCardArray(); assertThat(vCardArray, hasSize(2)); assertThat(vCardArray.get(0).toString(), is("vcard")); assertThat(Joiner.on("\n").join((List)vCardArray.get(1)), is("" + "[version, {}, text, 4.0]\n" + "[fn, {}, text, Abuse Contact]\n" + "[kind, {}, text, group]\n" + "[tel, {type=voice}, text, +31 12345678]")); final List<Entity> abuseEntities = entities.get(3).getEntitySearchResults(); assertThat(abuseEntities, hasSize(3)); assertThat(abuseEntities.get(0).getHandle(), is("TEST-MNT")); assertThat(abuseEntities.get(0).getRoles().get(0), is(Role.REGISTRANT)); assertThat(abuseEntities.get(1).getHandle(), is("TP1-TEST")); assertThat(abuseEntities.get(1).getRoles().get(0), is(Role.ADMINISTRATIVE)); assertThat(abuseEntities.get(2).getHandle(), is("TP2-TEST")); assertThat(abuseEntities.get(2).getRoles().get(0), is(Role.TECHNICAL)); assertThat(result.getRemarks().get(0).getDescription().get(0), is("some descr")); assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), hasSize(1)); assertThat(result.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(result.getEvents().get(0).getEventDate(), is(VERSION_TIMESTAMP)); } @Test public void autnum() { final Autnum result = (Autnum) map((RpslObject.parse("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "member-of: AS-TESTSET\n" + "descr: description\n" + "import: from AS1 accept ANY\n" + "export: to AS1 announce AS2\n" + "default: to AS1\n" + "mp-import: afi ipv6.unicast from AS1 accept ANY\n" + "mp-export: afi ipv6.unicast to AS1 announce AS2\n" + "mp-default: to AS1\n" + "remarks: remarkable\n" + "org: ORG-NCC1-RIPE\n" + "admin-c: AP1-TEST\n" + "tech-c: AP1-TEST\n" + "notify: [email protected]\n" + "mnt-lower: UPD-MNT\n" + "mnt-routes: UPD-MNT\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n"))); assertThat(result.getHandle(), is("AS102")); assertThat(result.getStartAutnum(), is(nullValue())); assertThat(result.getEndAutnum(), is(nullValue())); assertThat(result.getName(), is("End-User-2")); assertThat(result.getType(), is("DIRECT ALLOCATION")); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getCountry(), is(nullValue())); final List<Entity> entities = result.getEntitySearchResults(); assertThat(entities, hasSize(3)); assertThat(entities.get(1).getHandle(), is("ORG-NCC1-RIPE")); assertThat(entities.get(1).getRoles(), contains(Role.REGISTRANT)); assertThat(entities.get(0).getHandle(), is("AP1-TEST")); assertThat(entities.get(0).getRoles(), containsInAnyOrder(Role.TECHNICAL, Role.ADMINISTRATIVE)); assertThat(entities.get(0).getVCardArray(), is(nullValue())); assertThat(entities.get(2).getHandle(), is("UPD-MNT")); assertThat(entities.get(2).getRoles().get(0), is(Role.REGISTRANT)); assertThat(entities.get(2).getVCardArray(), is(nullValue())); assertThat(result.getRemarks().get(0).getDescription().get(0), is("description")); assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), hasSize(1)); assertThat(result.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(result.getEvents().get(0).getEventDate(), is(VERSION_TIMESTAMP)); assertThat(result.getPort43(), is("whois.ripe.net")); } @Test public void asBlock() { final Autnum result = (Autnum) map((RpslObject.parse("" + "as-block: AS100 - AS200\n" + "member-of: AS-TESTSET\n" + "descr: description\n" + "import: from AS1 accept ANY\n" + "export: to AS1 announce AS2\n" + "default: to AS1\n" + "mp-import: afi ipv6.unicast from AS1 accept ANY\n" + "mp-export: afi ipv6.unicast to AS1 announce AS2\n" + "mp-default: to AS1\n" + "remarks: remarkable\n" + "org: ORG-NCC1-RIPE\n" + "admin-c: AP1-TEST\n" + "tech-c: AP1-TEST\n" + "notify: [email protected]\n" + "mnt-lower: UPD-MNT\n" + "mnt-routes: UPD-MNT\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n"))); assertThat(result.getHandle(), is("AS100")); assertThat(result.getStartAutnum(), is(100L)); assertThat(result.getEndAutnum(), is(200L)); assertThat(result.getName(), is("AS100-AS200")); assertThat(result.getType(), is("DIRECT ALLOCATION")); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getCountry(), is(nullValue())); final List<Entity> entities = result.getEntitySearchResults(); assertThat(entities, hasSize(3)); assertThat(entities.get(0).getHandle(), is("AP1-TEST")); assertThat(entities.get(0).getRoles(), containsInAnyOrder(Role.TECHNICAL, Role.ADMINISTRATIVE)); assertThat(entities.get(0).getVCardArray(), is(nullValue())); assertThat(entities.get(1).getHandle(), is("ORG-NCC1-RIPE")); assertThat(entities.get(1).getRoles(), contains(Role.REGISTRANT)); assertThat(entities.get(2).getHandle(), is("UPD-MNT")); assertThat(entities.get(2).getRoles().get(0), is(Role.REGISTRANT)); assertThat(entities.get(2).getVCardArray(), is(nullValue())); assertThat(result.getRemarks().get(0).getDescription().get(0), is("description")); assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), hasSize(1)); assertThat(result.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(result.getEvents().get(0).getEventDate(), is(VERSION_TIMESTAMP)); assertThat(result.getPort43(), is("whois.ripe.net")); } @Test public void domain() { final Domain result = (Domain) map((RpslObject.parse("" + "domain: 2.1.2.1.5.5.5.2.0.2.1.e164.arpa\n" + "descr: enum domain\n" + "admin-c: TEST-PN\n" + "tech-c: TEST-PN\n" + "zone-c: TEST-PN\n" + "nserver: ns.1.net\n" + "nserver: ns.foo.net.0.0.193.in-addr.arpa. 10.0.0.0/32\n" + "mnt-by: RIPE-NCC-MNT\n" + "ds-rdata: 52314 5 1 93B5837D4E5C063A3728FAA72BA64068F89B39DF\n" + "source: TEST"))); assertThat(result.getHandle(), is("2.1.2.1.5.5.5.2.0.2.1.e164.arpa")); assertThat(result.getLdhName(), is("2.1.2.1.5.5.5.2.0.2.1.e164.arpa")); assertThat(result.getUnicodeName(), is(nullValue())); assertThat(result.getNameservers(), hasSize(2)); assertThat(result.getNameservers().get(0).getLdhName(), is("ns.1.net")); assertThat(result.getNameservers().get(1).getLdhName(), is("ns.foo.net.0.0.193.in-addr.arpa")); assertThat(result.getNameservers().get(1).getIpAddresses().getIpv4().get(0), is("10.0.0.0/32")); final Domain.SecureDNS secureDNS = result.getSecureDNS(); assertThat(secureDNS.isDelegationSigned(), is(true)); assertThat(secureDNS.getDsData().get(0).getAlgorithm(), is(5)); assertThat(secureDNS.getDsData().get(0).getKeyTag(), is(52314L)); assertThat(secureDNS.getDsData().get(0).getDigest(), is("93B5837D4E5C063A3728FAA72BA64068F89B39DF")); assertThat(secureDNS.getDsData().get(0).getDigestType(), is(1)); final List<Entity> entities = result.getEntitySearchResults(); assertThat(entities, hasSize(2)); assertThat(entities.get(0).getHandle(), is("RIPE-NCC-MNT")); assertThat(entities.get(0).getRoles(), contains(Role.REGISTRANT)); assertThat(entities.get(0).getVCardArray(), is(nullValue())); assertThat(entities.get(1).getHandle(), is("TEST-PN")); assertThat(entities.get(1).getRoles(), containsInAnyOrder(Role.ADMINISTRATIVE, Role.TECHNICAL, Role.ZONE)); assertThat(entities.get(1).getVCardArray(), is(nullValue())); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getPublicIds(), is(nullValue())); assertThat(result.getRemarks().get(0).getDescription().get(0), is("enum domain")); assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getPort43(), is("whois.ripe.net")); assertThat(result.getEvents(), hasSize(1)); assertThat(result.getEvents().get(0).getEventActor(), is(nullValue())); assertThat(result.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(result.getEvents().get(0).getEventDate(), is(VERSION_TIMESTAMP)); assertThat(result.getEvents().get(0).getEventActor(), is(nullValue())); assertThat(result.getPort43(), is("whois.ripe.net")); } @Test public void domain_31_12_202_in_addr_arpa() { final Domain result = (Domain) map((RpslObject.parse("" + "domain: 31.12.202.in-addr.arpa\n" + "descr: Test domain\n" + "admin-c: TP1-TEST\n" + "tech-c: TP1-TEST\n" + "zone-c: TP1-TEST\n" + "notify: [email protected]\n" + "nserver: ns1.test.com.au 10.0.0.1\n" + "nserver: ns1.test.com.au 2001:10::1\n" + "nserver: ns2.test.com.au 10.0.0.2\n" + "nserver: ns2.test.com.au 2001:10::2\n" + "nserver: ns3.test.com.au\n" + "ds-rdata: 52151 1 1 13ee60f7499a70e5aadaf05828e7fc59e8e70bc1\n" + "ds-rdata: 17881 5 1 2e58131e5fe28ec965a7b8e4efb52d0a028d7a78\n" + "ds-rdata: 17881 5 2 8c6265733a73e5588bfac516a4fcfbe1103a544b95f254cb67a21e474079547e\n" + "mnt-by: OWNER-MNT\n" + "source: TEST\n"))); assertThat(result.getHandle(), is("31.12.202.in-addr.arpa")); assertThat(result.getLdhName(), is("31.12.202.in-addr.arpa")); assertThat(result.getUnicodeName(), is(nullValue())); assertThat(result.getNameservers(), hasSize(3)); assertThat(result.getNameservers(), containsInAnyOrder( new Nameserver(null, "ns1.test.com.au", null, new Nameserver.IpAddresses(Lists.newArrayList("10.0.0.1/32"), Lists.newArrayList("2001:10::1/128"))), new Nameserver(null, "ns2.test.com.au", null, new Nameserver.IpAddresses(Lists.newArrayList("10.0.0.2/32"), Lists.newArrayList("2001:10::2/128"))), new Nameserver(null, "ns3.test.com.au", null, null) )); final Domain.SecureDNS secureDNS = result.getSecureDNS(); assertThat(secureDNS.isDelegationSigned(), is(true)); assertThat(secureDNS.getDsData(), hasSize(3)); assertThat(secureDNS.getDsData(), containsInAnyOrder( new Domain.SecureDNS.DsData(52151L, 1, "13ee60f7499a70e5aadaf05828e7fc59e8e70bc1", 1, null), new Domain.SecureDNS.DsData(17881L, 5, "2e58131e5fe28ec965a7b8e4efb52d0a028d7a78", 1, null), new Domain.SecureDNS.DsData(17881L, 5, "8c6265733a73e5588bfac516a4fcfbe1103a544b95f254cb67a21e474079547e", 2, null) )); final List<Entity> entities = result.getEntitySearchResults(); assertThat(entities, hasSize(2)); assertThat(entities, containsInAnyOrder( new Entity("OWNER-MNT", null, Lists.newArrayList(Role.REGISTRANT), null), new Entity("TP1-TEST", null, Lists.newArrayList(Role.TECHNICAL, Role.ADMINISTRATIVE, Role.ZONE), null) )); assertThat(result.getPort43(), is("whois.ripe.net")); } @Test public void person() { final Entity result = (Entity) map(RpslObject.parse("" + "person: First Last\n" + "address: Singel 258\n" + "phone: +31 20 123456\n" + "fax-no: +31 20 123457\n" + "e-mail: [email protected]\n" + "org: ORG-TOL1-TEST\n" + "nic-hdl: FL1-TEST\n" + "remarks: remark\n" + "notify: [email protected]\n" + "abuse-mailbox: [email protected]\n" + "mnt-by: TST-MNT\n" + "source: TEST")); assertThat(result.getHandle(), is("FL1-TEST")); final List<Object> vCardArray = result.getVCardArray(); assertThat(vCardArray, hasSize(2)); assertThat(vCardArray.get(0).toString(), is("vcard")); assertThat(Joiner.on("\n").join((List) vCardArray.get(1)), is("" + "[version, {}, text, 4.0]\n" + "[fn, {}, text, First Last]\n" + "[kind, {}, text, individual]\n" + "[adr, {label=Singel 258}, text, [, , , , , , ]]\n" + "[tel, {type=voice}, text, +31 20 123456]\n" + "[tel, {type=fax}, text, +31 20 123457]\n" + "[email, {type=email}, text, [email protected]]\n" + "[email, {type=abuse}, text, [email protected]]\n" + "[org, {}, text, ORG-TOL1-TEST]")); assertThat(result.getRoles(), is(emptyIterable())); assertThat(result.getPublicIds(), is(nullValue())); final List<Entity> entities = result.getEntitySearchResults(); assertThat(entities, hasSize(2)); assertThat(entities.get(0).getHandle(), is("ORG-TOL1-TEST")); assertThat(entities.get(0).getRoles(), contains(Role.REGISTRANT)); assertThat(entities.get(1).getHandle(), is("TST-MNT")); assertThat(entities.get(1).getRoles(), contains(Role.REGISTRANT)); assertThat(entities.get(1).getVCardArray(), is(nullValue())); assertThat(result.getRemarks(), is(emptyIterable())); assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), hasSize(1)); assertThat(result.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getPort43(), is("whois.ripe.net")); } @Test public void mntner() { final Entity result = (Entity) map(RpslObject.parse("" + "mntner: OWNER-MNT\n" + "descr: Owner Maintainer\n" + "admin-c: TP1-TEST\n" + "upd-to: [email protected]\n" + "auth: MD5-PW $1$d9fKeTr2$Si7YudNf4rUGmR71n/cqk/ #test\n" + "mnt-by: OWNER-MNT\n" + "referral-by: OWNER-MNT\n" + "remarks: remark\n" + "source: TEST")); assertThat(result.getHandle(), is("OWNER-MNT")); final List<Object> vCardArray = result.getVCardArray(); assertThat(vCardArray.get(0).toString(), is("vcard")); assertThat(Joiner.on("\n").join((List) vCardArray.get(1)), is("" + "[version, {}, text, 4.0]\n" + "[fn, {}, text, OWNER-MNT]\n" + "[kind, {}, text, individual]")); final List<Entity> entities = result.getEntitySearchResults(); assertThat(entities, hasSize(2)); assertThat(entities.get(0).getHandle(), is("OWNER-MNT")); assertThat(entities.get(0).getRoles(), contains(Role.REGISTRANT)); assertThat(entities.get(0).getVCardArray(), is(nullValue())); assertThat(entities.get(1).getHandle(), is("TP1-TEST")); assertThat(entities.get(1).getRoles(), contains(Role.ADMINISTRATIVE)); assertThat(entities.get(1).getVCardArray(), is(nullValue())); assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), hasSize(1)); assertThat(result.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getPort43(), is("whois.ripe.net")); } @Test public void organisation() { final Entity result = (Entity) map(RpslObject.parse("" + "organisation: ORG-AC1-TEST\n" + "org-name: Acme Carpets\n" + "org-type: OTHER\n" + "address: Singel 258\n" + "e-mail: [email protected]\n" + "descr: Acme Carpet Organisation\n" + "remark: some remark\n" + "phone: +31 1234567\n" + "fax-no: +31 98765432\n" + "geoloc: 52.375599 4.899902\n" + "language: DK\n" + "language: EN\n" + "admin-c: TP1-TEST\n" + "abuse-c: ABU-TEST\n" + "mnt-by: FRED-MNT\n" + "source: TEST")); assertThat(result.getHandle(), is("ORG-AC1-TEST")); final List<Object> vCardArray = result.getVCardArray(); assertThat(vCardArray, hasSize(2)); assertThat(vCardArray.get(0).toString(), is("vcard")); assertThat(Joiner.on("\n").join((List) vCardArray.get(1)), is("" + "[version, {}, text, 4.0]\n" + "[fn, {}, text, Acme Carpets]\n" + "[kind, {}, text, org]\n" + "[adr, {label=Singel 258}, text, [, , , , , , ]]\n" + "[tel, {type=voice}, text, +31 1234567]\n" + "[tel, {type=fax}, text, +31 98765432]\n" + "[email, {type=email}, text, [email protected]]\n" + "[geo, {}, uri, 52.375599 4.899902]")); assertThat(result.getRoles(), is(emptyIterable())); assertThat(result.getPublicIds(), is(nullValue())); assertThat(result.getEntitySearchResults(), hasSize(2)); assertThat(result.getRemarks(), hasSize(1)); assertThat(result.getRemarks().get(0).getDescription().get(0), is("Acme Carpet Organisation")); assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), hasSize(1)); assertThat(result.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getPort43(), is("whois.ripe.net")); assertThat(result.getLang(), is("DK")); final List<Notice> notices = result.getNotices(); assertThat(notices.get(0).getTitle(), is("Multiple language attributes found")); assertThat(notices.get(0).getDescription().get(0), is("There are multiple language attributes DK, EN in ORG-AC1-TEST, but only the first language DK was returned.")); } @Test public void organisation_should_not_have_notice_for_language() { final Entity result = (Entity) map(RpslObject.parse("" + "organisation: ORG-AC1-TEST\n" + "org-name: Acme Carpets\n" + "org-type: OTHER\n" + "address: Singel 258\n" + "e-mail: [email protected]\n" + "descr: Acme Carpet Organisation\n" + "remark: some remark\n" + "phone: +31 1234567\n" + "fax-no: +31 98765432\n" + "geoloc: 52.375599 4.899902\n" + "language: DK\n" + "admin-c: TP1-TEST\n" + "abuse-c: ABU-TEST\n" + "mnt-by: FRED-MNT\n" + "source: TEST")); assertThat(result.getLang(), is("DK")); final List<Notice> notices = result.getNotices(); assertThat(notices, hasSize(1)); assertThat(notices.get(0).getTitle(), is("Terms And Condition")); } @Test public void abuse_validation_failed() { final AbuseContact abuseContact = new AbuseContact( RpslObject.parse( "role: Abuse Contact\n" + "nic-hdl: AB-TEST\n" + "mnt-by: TEST-MNT\n" + "abuse-mailbox: [email protected]\n" + "admin-c: TP1-TEST\n" + "tech-c: TP2-TEST\n" + "phone: +31 12345678\n" + "source: TEST" ), true, ciString("ORG-NCC1-RIPE") ); final Autnum result = (Autnum) map( RpslObject.parse("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "org: ORG-NCC1-RIPE\n" + "admin-c: AP1-TEST\n" + "tech-c: AP1-TEST\n" + "abuse-c: AB-TEST\n" + "notify: [email protected]\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n" ), Optional.of(abuseContact) ); assertThat( result.getRemarks().get(0).getDescription().get(0), is("Abuse contact for 'AS102' is '[email protected]'\nAbuse-mailbox validation failed. Please refer to ORG-NCC1-RIPE for further information.\n") ); } @Test public void abuse_validation_passed() { final AbuseContact abuseContact = new AbuseContact( RpslObject.parse( "role: Abuse Contact\n" + "nic-hdl: AB-TEST\n" + "mnt-by: TEST-MNT\n" + "abuse-mailbox: [email protected]\n" + "admin-c: TP1-TEST\n" + "tech-c: TP2-TEST\n" + "phone: +31 12345678\n" + "source: TEST" ), false, ciString("ORG-NCC1-RIPE") ); final Autnum result = (Autnum) map( RpslObject.parse("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "org: ORG-NCC1-RIPE\n" + "admin-c: AP1-TEST\n" + "tech-c: AP1-TEST\n" + "abuse-c: AB-TEST\n" + "notify: [email protected]\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n" ), Optional.of(abuseContact) ); assertThat(result.getRemarks(), hasSize(0)); } @Test public void abuse_validation_failed_no_responsible_org() { final AbuseContact abuseContact = new AbuseContact( RpslObject.parse( "role: Abuse Contact\n" + "nic-hdl: AB-TEST\n" + "mnt-by: TEST-MNT\n" + "abuse-mailbox: [email protected]\n" + "admin-c: TP1-TEST\n" + "tech-c: TP2-TEST\n" + "phone: +31 12345678\n" + "source: TEST" ), true, null ); final Autnum result = (Autnum) map( RpslObject.parse("" + "aut-num: AS102\n" + "as-name: End-User-2\n" + "org: ORG-NCC1-RIPE\n" + "admin-c: AP1-TEST\n" + "tech-c: AP1-TEST\n" + "abuse-c: AB-TEST\n" + "notify: [email protected]\n" + "mnt-by: UPD-MNT\n" + "source: TEST\n" ), Optional.of(abuseContact) ); assertThat(result.getRemarks(), hasSize(0)); }
DummifierCurrent implements Dummifier { @Override public boolean isAllowed(final int version, final RpslObject object) { return version >= 3; } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); }
@Test public void allowed() { assertThat(subject.isAllowed(3, object), is(true)); assertThat(subject.isAllowed(2, object), is(false)); assertThat(subject.isAllowed(1, object), is(false)); }
RdapObjectMapper { public Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize) { final SearchResult searchResult = new SearchResult(); final Iterator<LocalDateTime> iterator = localDateTimes.iterator(); for (final RpslObject object : objects) { if (object.getType() == DOMAIN) { searchResult.addDomainSearchResult((Domain) getRdapObject(requestUrl, object, iterator.next(), Optional.empty())); } else { searchResult.addEntitySearchResult((Entity) getRdapObject(requestUrl, object, iterator.next(), Optional.empty())); } } if(objects.size() == maxResultSize) { final Notice notice = new Notice(); notice.setTitle(String.format("limited search results to %s maximum" , maxResultSize)); searchResult.getNotices().add(notice); } return mapCommons(searchResult, requestUrl); } @Autowired RdapObjectMapper( final NoticeFactory noticeFactory, @Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, @Value("${rdap.port43:}") final String port43); Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); }
@Test public void mapSearch_twoObjects() { final List<RpslObject> objects = Lists.newArrayList( RpslObject.parse("organisation: ORG-TOL-TEST\norg-name: Test Organisation\nstatus: OTHER\ndescr: comment 1\nsource: TEST"), RpslObject.parse("organisation: ORG-TST-TEST\norg-name: Test Company\nstatus: OTHER\ndescr: comment 2\nsource: TEST") ); final SearchResult response = (SearchResult)mapSearch(objects, Lists.newArrayList(LocalDateTime.parse("1970-04-14T09:22:14.857"), LocalDateTime.parse("1996-02-05T03:52:05.938"))); assertThat(response.getEntitySearchResults(), hasSize(2)); final Entity first = response.getEntitySearchResults().get(0); assertThat(first.getHandle(), is("ORG-TOL-TEST")); assertThat(first.getEvents(), hasSize(1)); assertThat(first.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(first.getRemarks(), hasSize(1)); assertThat(first.getRemarks().get(0).getDescription().get(0), is("comment 1")); final Entity last = response.getEntitySearchResults().get(1); assertThat(last.getHandle(), is("ORG-TST-TEST")); assertThat(last.getEvents(), hasSize(1)); assertThat(last.getEvents().get(0).getEventAction(), is(Action.LAST_CHANGED)); assertThat(last.getRemarks(), hasSize(1)); assertThat(last.getRemarks().get(0).getDescription().get(0), is("comment 2")); }
RdapObjectMapper { public RdapObject mapHelp(final String requestUrl) { return mapCommons(new RdapObject(), requestUrl); } @Autowired RdapObjectMapper( final NoticeFactory noticeFactory, @Qualifier("jdbcRpslObjectSlaveDao") final RpslObjectDao rpslObjectDao, final Ipv4Tree ipv4Tree, final Ipv6Tree ipv6Tree, @Value("${rdap.port43:}") final String port43); Object map(final String requestUrl, final RpslObject rpslObject, final LocalDateTime lastChangedTimestamp, final Optional<AbuseContact> abuseContact); Object mapSearch(final String requestUrl, final List<RpslObject> objects, final Iterable<LocalDateTime> localDateTimes, final int maxResultSize); RdapObject mapError(final int errorCode, final String errorTitle, final List<String> errorDescriptions); RdapObject mapHelp(final String requestUrl); }
@Test public void help() { final RdapObject result = mapper.mapHelp("http: assertThat(result.getLinks(), hasSize(2)); assertThat(result.getLinks().get(0).getRel(), is("self")); assertThat(result.getLinks().get(1).getRel(), is("copyright")); assertThat(result.getEvents(), is(emptyIterable())); assertThat(result.getStatus(), is(emptyIterable())); assertThat(result.getPort43(), is("whois.ripe.net")); }
RdapRequestValidator { public void validateEntity(final String key) { if (key.toUpperCase().startsWith("ORG-")) { if (!AttributeType.ORGANISATION.isValidValue(ORGANISATION, key)) { throw new NotFoundException("Invalid syntax."); } } else { if (!AttributeType.MNTNER.isValidValue(MNTNER, key)) { throw new NotFoundException("Invalid syntax."); } } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); }
@Test public void shouldThrowExceptionForInvalidOrganisation() { expectedEx.expect(NotFoundException.class); expectedEx.expectMessage("Invalid syntax"); validator.validateEntity("ORG-Test"); } @Test public void shouldNotThrowAnyExceptionForValidEntity() { validator.validateEntity("ORG-BAD1-TEST"); }
DummifierCurrent implements Dummifier { @Override public RpslObject dummify(final int version, final RpslObject rpslObject) { final ObjectType objectType = rpslObject.getType(); Validate.isTrue(isAllowed(version, rpslObject), "The version is not supported by this dummifier", version); final List<RpslAttribute> attributes = Lists.newArrayList(rpslObject.getAttributes()); RpslAttribute lastAddressLine = null; int lastAddressLineIndex = 0; for (int i = 0; i < attributes.size(); i++) { RpslAttribute replacement = attributes.get(i); final AttributeType attributeType = replacement.getType(); try { if (!(objectType == ObjectType.ROLE && rpslObject.containsAttribute(ABUSE_MAILBOX))) { replacement = replacePerson(attributeType, replacement); replacement = replaceAuth(attributeType, replacement); replacement = replacePhoneFax(attributeType, replacement); if (attributeType == ADDRESS) { lastAddressLine = replacement; lastAddressLineIndex = i; replacement = new RpslAttribute(ADDRESS, "***"); } } replacement = replaceEmail(attributeType, replacement); attributes.set(i, replacement); } catch (RuntimeException e) { LOGGER.debug("Dummifier failed on [" + attributes.get(i).toString().trim() + "]", e); } } if (lastAddressLine != null) { attributes.set(lastAddressLineIndex, lastAddressLine); } return FILTER_CHANGED_FUNCTION.apply(new RpslObject(rpslObject, attributes)); } @Override RpslObject dummify(final int version, final RpslObject rpslObject); @Override boolean isAllowed(final int version, final RpslObject object); }
@Test public void person() { final RpslObject person = RpslObject.parse(15, "" + "person: Fred Blogs\n" + "address: RIPE Network Coordination Centre (NCC)\n" + "address: Singel 258\n" + "address: 1016 AB Amsterdam\n" + "address: The Netherlands\n" + "phone: +31 20 535 4444\n" + "fax-no: +31 20 535 4445\n" + "e-mail: [email protected]\n" + "nic-hdl: FB99999-RIPE\n" + "mnt-by: AARDVARK-MNT\n" + "notify: [email protected]\n" + "source: RIPE"); final RpslObject dummified = subject.dummify(4, person); assertThat(dummified.getAttributes(), contains( new RpslAttribute("person", "Name Removed"), new RpslAttribute("address", "***"), new RpslAttribute("address", "***"), new RpslAttribute("address", "***"), new RpslAttribute("address", "The Netherlands"), new RpslAttribute("phone", "+31 20 ... ...."), new RpslAttribute("fax-no", "+31 20 ... ...."), new RpslAttribute("e-mail", "***@ripe.net"), new RpslAttribute("nic-hdl", "FB99999-RIPE"), new RpslAttribute("mnt-by", "AARDVARK-MNT"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("source", "RIPE"))); } @Test public void inetnum() { final RpslObject inetnum = RpslObject.parse(13, "" + "inetnum: 193.0.0.0 - 193.0.7.255\n" + "netname: RIPE-NCC\n" + "descr: RIPE Network Coordination Centre\n" + "descr: Amsterdam, Netherlands\n" + "remarks: Used for RIPE NCC infrastructure.\n" + "country: NL\n" + "admin-c: JDR-RIPE\n" + "admin-c: BRD-RIPE\n" + "tech-c: OPS4-RIPE\n" + "notify: [email protected]\n" + "status: ASSIGNED PI\n" + "source: RIPE\n" + "mnt-by: RIPE-NCC-MNT\n" + "mnt-lower: RIPE-NCC-MNT\n" + "source: TEST"); final RpslObject dummified = subject.dummify(4, inetnum); assertThat(dummified.getAttributes(), contains( new RpslAttribute("inetnum", "193.0.0.0 - 193.0.7.255"), new RpslAttribute("netname", "RIPE-NCC"), new RpslAttribute("descr", "RIPE Network Coordination Centre"), new RpslAttribute("descr", "Amsterdam, Netherlands"), new RpslAttribute("remarks", "Used for RIPE NCC infrastructure."), new RpslAttribute("country", "NL"), new RpslAttribute("admin-c", "JDR-RIPE"), new RpslAttribute("admin-c", "BRD-RIPE"), new RpslAttribute("tech-c", "OPS4-RIPE"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("status", "ASSIGNED PI"), new RpslAttribute("source", "RIPE"), new RpslAttribute("mnt-by", "RIPE-NCC-MNT"), new RpslAttribute("mnt-lower", "RIPE-NCC-MNT"), new RpslAttribute("source", "TEST") )); } @Test public void organisation() { final RpslObject organisation = RpslObject.parse(12, "" + "organisation: ORG-NCC1-RIPE\n" + "org-name: RIPE Network Coordination Centre\n" + "org-type: RIR\n" + "address: RIPE NCC\n" + " Singel 258\n" + " 1016 AB Amsterdam\n" + " Netherlands\n" + "phone: +31 20 535 4444\n" + "fax-no: +31 20 535 4445\n" + "e-mail: [email protected]\n" + "admin-c: AP110-RIPE\n" + "admin-c: CREW-RIPE\n" + "tech-c: CREW-RIPE\n" + "ref-nfy: [email protected]\n" + "mnt-ref: RIPE-NCC-RIS-MNT\n" + "mnt-ref: RIPE-NCC-HM-MNT\n" + "notify: [email protected]\n" + "mnt-by: RIPE-NCC-HM-MNT\n" + "source: RIPE"); final RpslObject dummified = subject.dummify(4, organisation); assertThat(dummified.getAttributes(), containsInAnyOrder( new RpslAttribute("organisation", "ORG-NCC1-RIPE"), new RpslAttribute("org-name", "RIPE Network Coordination Centre"), new RpslAttribute("org-type", "RIR"), new RpslAttribute("address", "RIPE NCC\n" + " Singel 258\n" + " 1016 AB Amsterdam\n" + " Netherlands"), new RpslAttribute("e-mail", "***@ripe.net"), new RpslAttribute("mnt-ref", "RIPE-NCC-RIS-MNT"), new RpslAttribute("mnt-ref", "RIPE-NCC-HM-MNT"), new RpslAttribute("mnt-by", "RIPE-NCC-HM-MNT"), new RpslAttribute("phone", "+31 20 ... ...."), new RpslAttribute("fax-no", "+31 20 ... ...."), new RpslAttribute("admin-c", "AP110-RIPE"), new RpslAttribute("admin-c", "CREW-RIPE"), new RpslAttribute("tech-c", "CREW-RIPE"), new RpslAttribute("ref-nfy", "***@ripe.net"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("source", "RIPE") )); } @Test public void mntner() { final RpslObject mntner = RpslObject.parse(11, "" + "mntner: AARDVARK-MNT\n" + "descr: Mntner for guy's objects\n" + "admin-c: FB99999-RIPE\n" + "tech-c: FB99999-RIPE\n" + "upd-to: [email protected]\n" + "auth: X509-1\n" + "auth: X509-1689\n" + "auth: MD5-PW $1$SaltSalt$ThisIsABrokenMd5Hash.\n" + "auth: SSO 1234-5678-9abc-dead-beef\n" + "notify: [email protected]\n" + "mnt-by: AARDVARK-MNT\n" + "source: RIPE # Filtered"); final RpslObject dummified = subject.dummify(4, mntner); assertThat(dummified.getAttributes(), containsInAnyOrder( new RpslAttribute("mntner", "AARDVARK-MNT"), new RpslAttribute("descr", "Mntner for guy's objects"), new RpslAttribute("admin-c", "FB99999-RIPE"), new RpslAttribute("tech-c", "FB99999-RIPE"), new RpslAttribute("upd-to", "***@ripe.net"), new RpslAttribute("auth", "X509-1"), new RpslAttribute("auth", "X509-1689"), new RpslAttribute("auth", "MD5-PW # Filtered"), new RpslAttribute("auth", "SSO # Filtered"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("mnt-by", "AARDVARK-MNT"), new RpslAttribute("source", "RIPE") )); } @Test public void role_without_abuse_mailbox() { final RpslObject role = RpslObject.parse(10, "" + "role: RIPE NCC tech contact\n" + "address: RIPE Network Coordination Centre (NCC)\n" + "address: Singel 258\n" + "address: 1016 AB Amsterdam\n" + "address: The Netherlands\n" + "phone: +31 20 535 4444\n" + "fax-no: +31 20 535 4445\n" + "e-mail: [email protected]\n" + "nic-hdl: RNTC-RIPE\n" + "mnt-by: RIPE-DBM-MNT\n" + "notify: [email protected]\n" + "source: RIPE"); final RpslObject dummified = subject.dummify(4, role); assertThat(dummified.getAttributes(), contains( new RpslAttribute("role", "RIPE NCC tech contact"), new RpslAttribute("address", "***"), new RpslAttribute("address", "***"), new RpslAttribute("address", "***"), new RpslAttribute("address", "The Netherlands"), new RpslAttribute("phone", "+31 20 ... ...."), new RpslAttribute("fax-no", "+31 20 ... ...."), new RpslAttribute("e-mail", "***@ripe.net"), new RpslAttribute("nic-hdl", "RNTC-RIPE"), new RpslAttribute("mnt-by", "RIPE-DBM-MNT"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("source", "RIPE") )); } @Test public void role_with_abuse_mailbox() { final RpslObject role = RpslObject.parse(10, "" + "role: RIPE NCC tech contact\n" + "address: RIPE Network Coordination Centre (NCC)\n" + "address: Singel 258\n" + "address: 1016 AB Amsterdam\n" + "address: The Netherlands\n" + "phone: +31 20 535 4444\n" + "fax-no: +31 20 535 4445\n" + "e-mail: [email protected]\n" + "abuse-mailbox: [email protected]\n" + "nic-hdl: RNTC-RIPE\n" + "mnt-by: RIPE-DBM-MNT\n" + "notify: [email protected]\n" + "source: RIPE"); final RpslObject dummified = subject.dummify(4, role); assertThat(dummified.getAttributes(), contains( new RpslAttribute("role", "RIPE NCC tech contact"), new RpslAttribute("address", "RIPE Network Coordination Centre (NCC)"), new RpslAttribute("address", "Singel 258"), new RpslAttribute("address", "1016 AB Amsterdam"), new RpslAttribute("address", "The Netherlands"), new RpslAttribute("phone", "+31 20 535 4444"), new RpslAttribute("fax-no", "+31 20 535 4445"), new RpslAttribute("e-mail", "***@ripe.net"), new RpslAttribute("abuse-mailbox", "[email protected]"), new RpslAttribute("nic-hdl", "RNTC-RIPE"), new RpslAttribute("mnt-by", "RIPE-DBM-MNT"), new RpslAttribute("notify", "***@ripe.net"), new RpslAttribute("source", "RIPE") )); }
RdapRequestValidator { public void validateAutnum(final String key) { try { AutNum.parse(key); } catch (AttributeParseException e) { throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); }
@Test(expected = BadRequestException.class) public void shouldThrowExceptionForInvalidAutnum() { validator.validateAutnum("TEST"); } @Test public void shouldNotThrowAExceptionForValidAutnum() { validator.validateAutnum("AS102"); }
RdapRequestValidator { public void validateIp(final String rawUri, final String key) { try { IpInterval.parse(key); } catch (IllegalArgumentException e) { throw new BadRequestException("Invalid syntax."); } if (rawUri.contains(" throw new BadRequestException("Invalid syntax."); } } @Autowired RdapRequestValidator(final ReservedAutnum reservedAutnum); void validateDomain(final String key); void validateIp(final String rawUri, final String key); void validateAutnum(final String key); void validateEntity(final String key); boolean isReservedAsNumber(String key); }
@Test(expected = BadRequestException.class) public void shouldThrowExceptionForInvalidIP() { validator.validateIp("", "invalid"); } @Test public void shouldNotThrowExceptionForValidIP() { validator.validateIp("", "192.0.0.0"); }
ExtensionOverridesAcceptHeaderFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(OverrideAcceptHeaderWrapper.wrapRequest((HttpServletRequest) request), response); } else { LOGGER.warn("Unexpected request: {}", request); chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }
@Test public void xml_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.xml"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is("application/xml")); assertThat(toList(request.getHeaders("Accept")), contains("application/xml")); } @Test public void json_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.json"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is("application/json")); assertThat(toList(request.getHeaders("Accept")), contains("application/json")); } @Test public void unknown_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is.unknown"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is.unknown")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } @Test public void no_extension() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/whois/test/inet6num/No%20clue%20what%20the%20range%20is"); assertThat(request.getRequestURI(), is("/whois/test/inet6num/No%20clue%20what%20the%20range%20is")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } @Test public void root_slash() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", "/"); assertThat(request.getRequestURI(), is("/")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); } @Test public void root_no_slash() throws Exception { final HttpServletRequest request = doFilter("http", "localhost", ""); assertThat(request.getRequestURI(), is("")); assertThat(request.getRequestURL().toString(), is("http: assertThat(request.getHeader("Accept"), is(nullValue())); assertThat(request.getHeaders("Accept"), is(nullValue())); }
RemoteAddressFilter implements Filter { @Override public void init(final FilterConfig filterConfig) throws ServletException { } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }
@Test public void init() throws Exception { subject.init(null); }
RemoteAddressFilter implements Filter { @Override public void destroy() { } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }
@Test public void destroy() { subject.destroy(); }
RemoteAddressFilter implements Filter { @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { chain.doFilter(new RemoteAddressRequestWrapper((HttpServletRequest) request), response); } else { chain.doFilter(request, response); } } @Override void init(final FilterConfig filterConfig); @Override void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain); @Override void destroy(); }
@Test public void no_servletRequest() throws Exception { final ServletRequest servletRequest = mock(ServletRequest.class); final ServletResponse servletResponse = mock(ServletResponse.class); subject.doFilter(servletRequest, servletResponse, filterChain); verify(filterChain).doFilter(servletRequest, servletResponse); } @Test public void no_forward_header() throws Exception { when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("10.0.0.0")), any(ServletResponse.class)); } @Test public void forward_header() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("193.0.20.1")), any(ServletResponse.class)); } @Test public void forward_headers_ripe_range() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("74.125.136.99", "193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("74.125.136.99")), any(ServletResponse.class)); } @Test public void forward_header_comma_separated_values() throws Exception { when(request.getHeaders(HttpHeaders.X_FORWARDED_FOR)).thenReturn(Collections.enumeration(Lists.newArrayList("74.125.136.99, 193.0.20.1"))); when(request.getRemoteAddr()).thenReturn("10.0.0.0"); subject.doFilter(request, response, filterChain); verify(filterChain).doFilter(argThat(new CheckRemoteAddress("193.0.20.1")), any(ServletResponse.class)); }
MailMessage implements Origin { public String getUpdateMessage() { StringBuilder builder = new StringBuilder(); Iterator<ContentWithCredentials> iterator = contentWithCredentials.iterator(); while (iterator.hasNext()) { builder.append(iterator.next().getContent()); if (iterator.hasNext()) { builder.append("\n\n"); } } return builder.toString(); } MailMessage(final String id, final String from, final String subject, final String date, final String replyTo, String replyToEmail, final Keyword keyword, List<ContentWithCredentials> contentWithCredentials); @Override boolean isDefaultOverride(); @Override boolean allowAdminOperations(); String getId(); String getSubject(); String getDate(); String getReplyTo(); String getReplyToEmail(); String getUpdateMessage(); List<ContentWithCredentials> getContentWithCredentials(); @Override String getFrom(); Keyword getKeyword(); @Override String getResponseHeader(); @Override String getNotificationHeader(); @Override String getName(); @Override String toString(); }
@Test public void getUpdateMessage() { List<ContentWithCredentials> contentWithCredentialsList = Lists.newArrayList(); contentWithCredentialsList.add(new ContentWithCredentials("password: some password\nmntner: TST-MNT")); contentWithCredentialsList.add(new ContentWithCredentials("password: another password\nmntner: TST2-MNT")); final MailMessage subject = new MailMessage("id", "from", "subject", "date", "replyTo", "replyToEmail", Keyword.NONE, contentWithCredentialsList); assertThat(subject.getUpdateMessage(), is("" + "password: some password\n" + "mntner: TST-MNT\n" + "\n" + "password: another password\n" + "mntner: TST2-MNT")); }
MessageFilter { public boolean shouldProcess(final MailMessage message) { String replyToEmail = message.getReplyToEmail(); if (replyToEmail == null) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, missing reply address")); return false; } try { new InternetAddress(replyToEmail, true); } catch (final AddressException e) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } if (!EmailValidator.getInstance().isValid(replyToEmail)) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply address invalid: %s", replyToEmail)); return false; } replyToEmail = replyToEmail.toLowerCase(); if (replyToEmail.endsWith("localhost") || replyToEmail.endsWith("127.0.0.1")) { loggerContext.log(new Message(Messages.Type.INFO, "Not processing message, reply to localhost: %s", replyToEmail)); return false; } return true; } @Autowired MessageFilter(final LoggerContext loggerContext); boolean shouldProcess(final MailMessage message); }
@Test public void shouldProcess() throws Exception { when(message.getReplyTo()).thenReturn("[email protected]"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(true)); } @Test public void shouldProcessFull() throws Exception { when(message.getReplyTo()).thenReturn("Maximus Maxus <[email protected]>"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(true)); } @Test public void shouldProcess_localhost() throws Exception { when(message.getReplyTo()).thenReturn("something@localhost"); when(message.getReplyToEmail()).thenReturn("something@localhost"); assertThat(subject.shouldProcess(message), is(false)); } @Test public void shouldProcess_127_0_0_1() throws Exception { when(message.getReplyTo()).thenReturn("[email protected]"); when(message.getReplyToEmail()).thenReturn("[email protected]"); assertThat(subject.shouldProcess(message), is(false)); } @Test public void noReplytoFails() throws Exception { when(message.getReplyTo()).thenReturn(null); when(message.getReplyToEmail()).thenReturn(null); assertThat(subject.shouldProcess(message), is(false)); } @Test public void noReplytoFailsFull() throws Exception { when(message.getReplyTo()).thenReturn("Maximus Maxus"); when(message.getReplyToEmail()).thenReturn(null); assertThat(subject.shouldProcess(message), is(false)); } @Test public void invalidReplytoFails() throws Exception { when(message.getReplyTo()).thenReturn("email_with_no_domain_or_at_sign"); when(message.getReplyToEmail()).thenReturn("email_with_no_domain_or_at_sign"); assertThat(subject.shouldProcess(message), is(false)); } @Test public void invalidReplytoFailsFull() throws Exception { when(message.getReplyTo()).thenReturn("Minima Mina <email_with_no_domain_or_at_sign>"); when(message.getReplyToEmail()).thenReturn("email_with_no_domain_or_at_sign"); assertThat(subject.shouldProcess(message), is(false)); }