Skip to content

Commit

Permalink
Make NetworkAddressRulesAdheringDnsResolver testable
Browse files Browse the repository at this point in the history
By using composition rather than inheritance
  • Loading branch information
Mahoney committed Sep 5, 2023
1 parent 90a37e1 commit aa29d9c
Showing 1 changed file with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,21 @@
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.stream.Stream;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;

public class NetworkAddressRulesAdheringDnsResolver extends SystemDefaultDnsResolver {
public class NetworkAddressRulesAdheringDnsResolver implements DnsResolver {

private final DnsResolver delegate;
private final NetworkAddressRules networkAddressRules;

public NetworkAddressRulesAdheringDnsResolver(NetworkAddressRules networkAddressRules) {
this(SystemDefaultDnsResolver.INSTANCE, networkAddressRules);
}

public NetworkAddressRulesAdheringDnsResolver(
DnsResolver delegate, NetworkAddressRules networkAddressRules) {
this.delegate = delegate;
this.networkAddressRules = networkAddressRules;
}

Expand All @@ -36,12 +44,17 @@ public InetAddress[] resolve(String host) throws UnknownHostException {
throw new ProhibitedNetworkAddressException();
}

final InetAddress[] resolved = super.resolve(host);
final InetAddress[] resolved = delegate.resolve(host);
if (Stream.of(resolved)
.anyMatch(address -> !networkAddressRules.isAllowed(address.getHostAddress()))) {
throw new ProhibitedNetworkAddressException();
}

return resolved;
}

@Override
public String resolveCanonicalHostname(String host) throws UnknownHostException {
return delegate.resolveCanonicalHostname(host);
}
}

0 comments on commit aa29d9c

Please sign in to comment.