feat(route53): validate stored ALB targets for public DNS aliases (#8942)

This commit is contained in:
Jackson Price authored and GitHub committed 2026-11-19 07:05:14 -04:00
1 parent b388616273
commit d28bdf664b
10 files changed
+558 -9

No files matched your search

+6 -2
View File
@@ -79,7 +79,11 @@ For a Docker host client, publish UDP separately from HTTP on loopback, for exam
The longest matching public zone answers. Missing names return NXDOMAIN; existing names without the requested supported type return NOERROR with no answers. Both include the zone SOA with the smaller of its TTL and minimum field for negative caching. Changes and deletes affect DNS through the same stored record sets as the Route 53 API.
Public aliases, CNAME chasing, health-based or weighted record selection, and delegation referrals are not implemented. Queries for supported types that require these features, ambiguous duplicate public zones, or malformed stored records return REFUSED without claiming authority. Other query types retain the existing emulator-name and upstream resolution paths. Private-zone and VPC forwarding-rule precedence remains unchanged. UDP responses honor legacy/EDNS size limits and set truncation when necessary; TCP fallback is not implemented.
Simple public `A` aliases to stored Application Load Balancers resolve to the receiving DNS listener's IPv4 address with a 60-second TTL, including the loopback address when only the native host listener is enabled. The target DNS name and canonical hosted-zone ID must match exactly one stored load balancer, including when the zone and balancer have different owners. Names are case-insensitive and accept the load balancer's `dualstack.` prefix. An `AAAA` alias to a valid target returns NOERROR without addresses because this listener has no IPv6 address. Deleted, ambiguous, unsupported, and mismatched targets return REFUSED without recursive DNS or emulator-suffix fallback.
A single simple ALB alias resolves with either `EvaluateTargetHealth` setting. Route 53 still answers when all records are unhealthy, so the setting does not change the answer when there is only one record.
This provides DNS answers; routing an alias hostname through an ALB's HTTP or TLS listener is a separate data-plane capability. Other public alias target types, CNAME chasing, health-based or weighted record selection, and delegation referrals are not implemented. Queries for supported types that require these features, ambiguous duplicate public zones, or malformed stored records return REFUSED without claiming authority. Other query types retain the existing emulator-name and upstream resolution paths. Private-zone and VPC forwarding-rule precedence remains unchanged. UDP responses honor legacy/EDNS size limits and set truncation when necessary; TCP fallback is not implemented.
## Default Nameservers
@@ -215,4 +219,4 @@ the record. DELETE still requires matching record values and routing properties.
- Query logging configs
- DNSSEC (key signing keys, enabling/disabling)
- `TestDNSAnswer`
- Public authoritative record types other than simple A, AAAA, TXT, NS, and SOA; public aliases, routing policies, delegation referrals, and DNS-over-TCP
- Public authoritative record types other than simple A, AAAA, TXT, NS, and SOA; alias targets other than Application Load Balancers, alias data-plane routing, routing policies, delegation referrals, and DNS-over-TCP
@@ -18,6 +18,16 @@ public interface DnsRecordSource {
return Optional.empty();
}
/** Supplies the receiving listener's address to sources that resolve local alias targets. */
default Optional<DnsAnswer> resolveAuthoritative(String name, int type, String listenerAddress) {
return resolveAuthoritative(name, type);
}
/** Resolves a stored resource's alias target without recursive DNS or suffix substitution. */
default Optional<DnsAnswer> resolveAliasTarget(String name, String hostedZoneId, int type, String listenerAddress) {
return Optional.empty();
}
/**
* Resolves a query name to IPv4 addresses and their TTL. An empty optional means this
* source does not own the name. The name arrives without a trailing dot and in the case the client sent.
@@ -377,8 +377,31 @@ public class EmbeddedDnsServer {
return resolveRecordWithOwnership(name, myIp, 1);
}
/** Only one stored resource may claim an alias target; failures cannot fall through to DNS. */
public Optional<DnsAnswer> resolveAliasTarget(String name, String hostedZoneId, int type, String listenerAddress) {
DnsAnswer resolved = null;
if (recordSources != null) {
for (DnsRecordSource source : recordSources) {
try {
Optional<DnsAnswer> candidate = source.resolveAliasTarget(name, hostedZoneId, type, listenerAddress);
if (candidate.isPresent()) {
if (resolved != null) {
return Optional.of(DnsAnswer.refused());
}
resolved = candidate.orElseThrow();
}
} catch (RuntimeException failure) {
LOG.debugv("DNS alias source {0} failed to resolve {1}: {2}",
source.getClass().getSimpleName(), name, failure.getMessage());
return Optional.of(DnsAnswer.refused());
}
}
}
return Optional.ofNullable(resolved);
}
private Optional<DnsAnswer> resolveRecordWithOwnership(String name, String myIp, int type) {
Optional<DnsAnswer> stored = resolveFromRecordSources(name, type, true);
Optional<DnsAnswer> stored = resolveFromRecordSources(name, type, true, myIp);
if (stored.isPresent()) {
return stored;
}
@@ -416,7 +439,7 @@ public class EmbeddedDnsServer {
* hosted zone that matches the same name.
*/
QueryPlan planQuery(String name, String clientAddress, String myIp, int type) {
Optional<DnsAnswer> stored = resolveFromRecordSources(name, type, true);
Optional<DnsAnswer> stored = resolveFromRecordSources(name, type, true, myIp);
Optional<DnsAnswer> emulatorName = resolveEmulatorName(name, myIp, type);
if (emulatorName.isPresent() && stored.isEmpty()) {
return QueryPlan.answering(emulatorName.orElseThrow());
@@ -509,10 +532,11 @@ public class EmbeddedDnsServer {
* through to the upstream resolvers, which is what happened before any source existed.
*/
private Optional<DnsAnswer> resolveFromRecordSources(String name, int type) {
return resolveFromRecordSources(name, type, false);
return resolveFromRecordSources(name, type, false, null);
}
private Optional<DnsAnswer> resolveFromRecordSources(String name, int type, boolean authoritative) {
private Optional<DnsAnswer> resolveFromRecordSources(
String name, int type, boolean authoritative, String listenerAddress) {
if (recordSources == null) {
return Optional.empty();
}
@@ -523,7 +547,7 @@ public class EmbeddedDnsServer {
Optional<DnsAnswer> empty = Optional.empty();
for (DnsRecordSource source : recordSources) {
try {
Optional<DnsAnswer> answer = authoritative ? source.resolveAuthoritative(name, type)
Optional<DnsAnswer> answer = authoritative ? source.resolveAuthoritative(name, type, listenerAddress)
: source.resolve(name, type);
if (answer != null && answer.isPresent()) {
if (answer.get().isEmpty()) {
@@ -0,0 +1,44 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.core.common.dns.DnsAnswer;
import io.floci.aws.core.common.dns.DnsRecordSource;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import jakarta.enterprise.context.ApplicationScoped;
import java.util.List;
import java.util.Optional;
/** Resolves an ALB alias to the emulator address serving its listeners. */
@ApplicationScoped
public class ElbV2DnsRecordSource implements DnsRecordSource {
private final ElbV2Service service;
public ElbV2DnsRecordSource(ElbV2Service service) {
this.service = service;
}
@Override
public Optional<DnsAnswer> resolveIpv4(String name) {
return Optional.empty();
}
@Override
public Optional<DnsAnswer> resolveAliasTarget(String name, String hostedZoneId, int type, String listenerAddress) {
List<LoadBalancer> matches = service.findByDnsName(name);
if (matches.isEmpty()) {
return Optional.empty();
}
if (matches.size() != 1) {
return Optional.of(DnsAnswer.refused());
}
LoadBalancer target = matches.getFirst();
if (!"application".equals(target.getType()) || hostedZoneId == null
|| !hostedZoneId.equals(target.getCanonicalHostedZoneId()) || (type != 1 && type != 28)) {
return Optional.of(DnsAnswer.refused());
}
if (type == 28 || listenerAddress == null || listenerAddress.isBlank()) {
return Optional.of(DnsAnswer.noData());
}
return Optional.of(DnsAnswer.records(List.of(listenerAddress), 60));
}
}
@@ -33,6 +33,7 @@ import java.net.InetAddress;
import java.time.Instant;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -104,6 +105,22 @@ public class ElbV2Service implements ResourceProvider, ServerCertificateReferenc
// tags: resource-ARN → {key → value}
private Map<String, Map<String, String>> tags = new ConcurrentHashMap<>();
/** DNS selects the resource owner independently of a management request's account. */
List<LoadBalancer> findByDnsName(String name) {
if (name == null || name.isBlank()) {
return List.of();
}
String normalized = name.endsWith(".") ? name.substring(0, name.length() - 1) : name;
if (normalized.regionMatches(true, 0, "dualstack.", 0, "dualstack.".length())) {
normalized = normalized.substring("dualstack.".length());
}
String target = normalized;
Collection<Map<String, LoadBalancer>> regions = allAccounts(loadBalancers, loadBalancerStore);
return regions.stream().flatMap(region -> region.values().stream())
.filter(lb -> target.equalsIgnoreCase(lb.getDnsName()))
.toList();
}
@PostConstruct
void initializeStorage()
{
@@ -75,6 +75,11 @@ public class Route53DnsRecordSource implements DnsRecordSource {
@Override
public Optional<DnsAnswer> resolveAuthoritative(String name, int type) {
return resolveAuthoritative(name, type, null);
}
@Override
public Optional<DnsAnswer> resolveAuthoritative(String name, int type, String listenerAddress) {
if (name == null || name.isBlank() || (type != 1 && type != 2 && type != 6 && type != 16 && type != 28)) {
return Optional.empty();
}
@@ -119,9 +124,9 @@ public class Route53DnsRecordSource implements DnsRecordSource {
case 6 -> DnsRecord.Soa::new;
default -> DnsRecord.Txt::new;
};
DnsAnswer answer = buildRecords(name, zone.matchingRecords().stream()
DnsAnswer answer = buildPublicRecords(name, type, zone.matchingRecords().stream()
.filter(record -> record.getType().equals(recordType)).toList(),
recordFactory, Route53DnsRecordSource::publicTtlOf);
recordFactory, listenerAddress);
if (answer.responseCode() != 0) {
return Optional.of(answer);
}
@@ -145,6 +150,32 @@ public class Route53DnsRecordSource implements DnsRecordSource {
}
}
private DnsAnswer buildPublicRecords(String name, int type, List<ResourceRecordSet> sets,
Function<String, DnsRecord> recordFactory, String listenerAddress) {
if (sets.stream().noneMatch(record -> record.getAliasTarget() != null)) {
return buildRecords(name, sets, recordFactory, Route53DnsRecordSource::publicTtlOf);
}
if (sets.size() != 1 || embeddedDnsServer == null || (type != 1 && type != 28)) {
return DnsAnswer.refused();
}
ResourceRecordSet record = sets.getFirst();
AliasTarget alias = record.getAliasTarget();
if (record.getSetIdentifier() != null || record.getWeight() != null || record.getRegion() != null
|| record.getFailover() != null || record.getHealthCheckId() != null
|| Boolean.TRUE.equals(record.getMultiValueAnswer())
|| record.getTtl() != null
|| record.getRecords() != null && !record.getRecords().isEmpty()) {
return DnsAnswer.refused();
}
// A single simple alias still answers when unhealthy, since there is no alternative record.
DnsAnswer target = embeddedDnsServer.resolveAliasTarget(
alias.getDnsName(), alias.getHostedZoneId(), type, listenerAddress).orElseGet(DnsAnswer::refused);
if (target.responseCode() != 0 || target.records().stream().anyMatch(value -> value.type() != type)) {
return DnsAnswer.refused();
}
return target;
}
@Override
public Optional<DnsAnswer> resolve(String name, int type) {
if (type != 33) {
@@ -0,0 +1,186 @@
package io.floci.aws.core.common.dns;
import io.floci.aws.testing.AwsTestClients;
import io.quarkus.test.junit.QuarkusTest;
import io.vertx.core.Vertx;
import io.vertx.core.datagram.DatagramSocket;
import jakarta.inject.Inject;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.elasticloadbalancingv2.ElasticLoadBalancingV2Client;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.DeleteLoadBalancerRequest;
import software.amazon.awssdk.services.elasticloadbalancingv2.model.LoadBalancer;
import software.amazon.awssdk.services.route53.Route53Client;
import software.amazon.awssdk.services.route53.model.AliasTarget;
import software.amazon.awssdk.services.route53.model.Change;
import software.amazon.awssdk.services.route53.model.ChangeAction;
import software.amazon.awssdk.services.route53.model.DeleteHostedZoneRequest;
import software.amazon.awssdk.services.route53.model.ResourceRecordSet;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** Signed management calls followed by real UDP queries through CDI-discovered DNS sources. */
@QuarkusTest
class ElbV2AliasDnsIntegrationTest {
@Inject
EmbeddedDnsServer dns;
@Inject
Vertx vertx;
@ParameterizedTest
@CsvSource({"internal,A,1,127.0.0.1,false", "internet-facing,A,1,127.0.0.1,false",
"internal,AAAA,28,127.0.0.1,false", "internet-facing,AAAA,28,127.0.0.1,false",
"internal,A,1,127.0.0.2,false", "internet-facing,A,1,127.0.0.2,false",
"internal,AAAA,28,127.0.0.2,false", "internet-facing,AAAA,28,127.0.0.2,false",
"internal,A,1,127.0.0.1,true", "internet-facing,A,1,127.0.0.1,true",
"internal,AAAA,28,127.0.0.1,true", "internet-facing,AAAA,28,127.0.0.1,true",
"internal,A,1,127.0.0.2,true", "internet-facing,A,1,127.0.0.2,true",
"internal,AAAA,28,127.0.0.2,true", "internet-facing,AAAA,28,127.0.0.2,true"})
void publicAliasValidatesItsTargetAcrossAccounts(
String scheme, String type, int queryType, String listenerAddress, boolean evaluateTargetHealth)
throws Exception {
try (Ec2Client ec2 = AwsTestClients.create(Ec2Client.builder(), "730000000001", Region.EU_WEST_1);
ElasticLoadBalancingV2Client elb = AwsTestClients.create(
ElasticLoadBalancingV2Client.builder(), "730000000001", Region.EU_WEST_1);
ElasticLoadBalancingV2Client other = AwsTestClients.create(
ElasticLoadBalancingV2Client.builder(), "730000000002", Region.EU_WEST_1);
Route53Client route53 = AwsTestClients.create(
Route53Client.builder(), "730000000002", Region.EU_WEST_1)) {
String name = "api." + UUID.randomUUID() + ".example.test";
String vpc = ec2.createVpc(r -> r.cidrBlock("10.73.0.0/16")).vpc().vpcId();
List<String> subnets = new ArrayList<>();
String zone = null;
String arn = null;
ResourceRecordSet installed = null;
DatagramSocket listener = null;
try {
listener = dns.bind(vertx, listenerAddress, 0, false)
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
assertTrue(dns.getServerIp().isEmpty(), "A host listener must not be handed to containers");
subnets.add(ec2.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.73.1.0/24")
.availabilityZone("eu-west-1a")).subnet().subnetId());
subnets.add(ec2.createSubnet(r -> r.vpcId(vpc).cidrBlock("10.73.2.0/24")
.availabilityZone("eu-west-1b")).subnet().subnetId());
LoadBalancer target = elb.createLoadBalancer(
r -> r.name("dns-" + UUID.randomUUID().toString().substring(0, 20))
.type("application").scheme(scheme).subnets(subnets)).loadBalancers().getFirst();
arn = target.loadBalancerArn();
assertTrue(arn.contains(":730000000001:"));
assertTrue(other.describeLoadBalancers().loadBalancers().stream()
.noneMatch(lb -> lb.loadBalancerArn().equals(target.loadBalancerArn())));
zone = route53.createHostedZone(r -> r.name(name).callerReference(UUID.randomUUID().toString()))
.hostedZone().id();
installed = alias(name, type, target.dnsName(), target.canonicalHostedZoneId(), evaluateTargetHealth);
change(route53, zone, ChangeAction.CREATE, installed);
assertValidTarget(query(listener, name, queryType), queryType, listenerAddress);
installed = alias(name, type, "dualstack." + target.dnsName().toUpperCase(Locale.ROOT),
target.canonicalHostedZoneId(), evaluateTargetHealth);
change(route53, zone, ChangeAction.UPSERT, installed);
assertValidTarget(query(listener, name.toUpperCase(Locale.ROOT) + ".", queryType),
queryType, listenerAddress);
installed = alias(name, type, target.dnsName(), "WRONG", evaluateTargetHealth);
change(route53, zone, ChangeAction.UPSERT, installed);
assertEquals(5, rcode(query(listener, name, queryType)));
installed = alias(name, type, target.dnsName(), target.canonicalHostedZoneId(), evaluateTargetHealth);
change(route53, zone, ChangeAction.UPSERT, installed);
assertValidTarget(query(listener, name, queryType), queryType, listenerAddress);
elb.deleteLoadBalancer(r -> r.loadBalancerArn(target.loadBalancerArn()));
arn = null;
assertEquals(5, rcode(query(listener, name, queryType)),
"A deleted target must not resolve through the emulator suffix or upstream DNS");
change(route53, zone, ChangeAction.DELETE, installed);
installed = null;
byte[] removed = query(listener, name, queryType);
assertEquals(0, rcode(removed));
assertEquals(0, ByteBuffer.wrap(removed).getShort(6));
assertEquals(1, ByteBuffer.wrap(removed).getShort(8));
} finally {
if (listener != null) {
listener.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
if (installed != null) {
change(route53, zone, ChangeAction.DELETE, installed);
}
if (zone != null) {
route53.deleteHostedZone(DeleteHostedZoneRequest.builder().id(zone).build());
}
if (arn != null) {
elb.deleteLoadBalancer(DeleteLoadBalancerRequest.builder().loadBalancerArn(arn).build());
}
for (String subnet : subnets) {
ec2.deleteSubnet(r -> r.subnetId(subnet));
}
ec2.deleteVpc(r -> r.vpcId(vpc));
}
}
}
private static ResourceRecordSet alias(String name, String type, String target, String zone,
boolean evaluateTargetHealth) {
return ResourceRecordSet.builder().name(name).type(type).aliasTarget(AliasTarget.builder()
.dnsName(target + ".").hostedZoneId(zone).evaluateTargetHealth(evaluateTargetHealth).build()).build();
}
private static void change(Route53Client client, String zone, ChangeAction action, ResourceRecordSet record) {
client.changeResourceRecordSets(r -> r.hostedZoneId(zone).changeBatch(b -> b.changes(
Change.builder().action(action).resourceRecordSet(record).build())));
}
private static byte[] query(DatagramSocket listener, String name, int type) throws Exception {
byte[] request = DnsTestQuery.query(name, type, 1234);
// Vert.x and the JDK both name their UDP socket DatagramSocket.
try (java.net.DatagramSocket client = new java.net.DatagramSocket(
0, InetAddress.getByName("127.0.0.1"))) {
client.connect(InetAddress.getByName(listener.localAddress().host()), listener.localAddress().port());
client.setSoTimeout(5000);
client.send(new DatagramPacket(request, request.length));
DatagramPacket reply = new DatagramPacket(new byte[4096], 4096);
client.receive(reply);
return Arrays.copyOf(reply.getData(), reply.getLength());
}
}
private static int rcode(byte[] answer) {
return ByteBuffer.wrap(answer).getShort(2) & 15;
}
private static void assertValidTarget(byte[] answer, int type, String listenerAddress) {
ByteBuffer packet = ByteBuffer.wrap(answer);
assertEquals(0, rcode(answer), "A known stored alias target must resolve authoritatively");
assertEquals(0x0400, packet.getShort(2) & 0x0400);
assertEquals(0, packet.getShort(2) & 0x0080);
assertEquals(type == 1 ? 1 : 0, packet.getShort(6));
if (type == 28) {
assertEquals(1, packet.getShort(8));
return;
}
packet.position(12);
EmbeddedDnsServer.readName(packet, answer);
packet.getInt();
EmbeddedDnsServer.readName(packet, answer);
assertEquals(1, packet.getShort());
assertEquals(1, packet.getShort());
assertEquals(60, packet.getInt());
assertEquals(4, packet.getShort());
byte[] value = new byte[4];
packet.get(value);
assertArrayEquals(new DnsRecord.Address(1, listenerAddress).data(), value);
}
}
@@ -0,0 +1,52 @@
package io.floci.aws.core.common.dns;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class EmbeddedDnsAliasTargetTest {
private static final String TARGET = "owned.example.test";
@Test
void anUnclaimedAliasTargetHasNoSuffixOrRecursiveFallback() {
EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of("example.test"), List.of());
assertEquals(Optional.empty(), dns.resolveAliasTarget(TARGET, "ZOWNED", 1, "192.0.2.10"));
}
@Test
void aUniqueResourceRetainsItsAddressAndTtl() {
DnsAnswer answer = DnsAnswer.records(List.of("192.0.2.10"), 37);
EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of(), List.of(source(Optional.empty()),
source(Optional.of(answer))));
assertEquals(Optional.of(answer), dns.resolveAliasTarget(TARGET, "ZOWNED", 1, "192.0.2.10"));
}
@Test
void twoResourceClaimsAreRefusedEvenIfOneHasNoAddress() {
EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of(), List.of(source(Optional.of(DnsAnswer.noData())),
source(Optional.of(DnsAnswer.records(List.of("192.0.2.10"), 37)))));
assertEquals(Optional.of(DnsAnswer.refused()), dns.resolveAliasTarget(TARGET, "ZOWNED", 1, "192.0.2.10"));
}
@Test
void aBrokenResourceSourceCannotFallThroughToAnotherOwner() {
DnsRecordSource broken = mock(DnsRecordSource.class);
DnsRecordSource next = mock(DnsRecordSource.class);
when(broken.resolveAliasTarget(TARGET, "ZOWNED", 1, "192.0.2.10")).thenThrow(new IllegalStateException("unavailable"));
EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of(), List.of(broken, next));
assertEquals(Optional.of(DnsAnswer.refused()), dns.resolveAliasTarget(TARGET, "ZOWNED", 1, "192.0.2.10"));
verifyNoInteractions(next);
}
private static DnsRecordSource source(Optional<DnsAnswer> answer) {
DnsRecordSource source = mock(DnsRecordSource.class);
when(source.resolveAliasTarget(TARGET, "ZOWNED", 1, "192.0.2.10")).thenReturn(answer);
return source;
}
}
@@ -0,0 +1,73 @@
package io.floci.aws.services.elbv2;
import io.floci.aws.core.common.dns.DnsAnswer;
import io.floci.aws.services.elbv2.model.LoadBalancer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class ElbV2DnsRecordSourceTest {
private static final String NAME = "owned.elb.example.test";
private final ElbV2Service service = mock(ElbV2Service.class);
private final ElbV2DnsRecordSource source = new ElbV2DnsRecordSource(service);
@ParameterizedTest
@ValueSource(strings = {"internal", "internet-facing"})
void aValidatedApplicationBalancerUsesItsListenerAddress(String scheme) {
LoadBalancer target = balancer("application");
target.setScheme(scheme);
when(service.findByDnsName(NAME)).thenReturn(List.of(target));
assertEquals(Optional.of(DnsAnswer.records(List.of("192.0.2.10"), 60)),
source.resolveAliasTarget(NAME, "ZOWNED", 1, "192.0.2.10"));
}
@ParameterizedTest
@ValueSource(strings = {"network", "gateway"})
void unsupportedBalancerTypesRemainRefused(String type) {
when(service.findByDnsName(NAME)).thenReturn(List.of(balancer(type)));
assertEquals(Optional.of(DnsAnswer.refused()), source.resolveAliasTarget(NAME, "ZOWNED", 1, "192.0.2.10"));
}
@Test
void mismatchedOwnershipAndUnsupportedQueryTypesCannotReachTheListener() {
when(service.findByDnsName(NAME)).thenReturn(List.of(balancer("application")));
assertEquals(Optional.of(DnsAnswer.refused()), source.resolveAliasTarget(NAME, "WRONG", 1, "192.0.2.10"));
assertEquals(Optional.of(DnsAnswer.refused()), source.resolveAliasTarget(NAME, null, 1, "192.0.2.10"));
assertEquals(Optional.of(DnsAnswer.refused()), source.resolveAliasTarget(NAME, "ZOWNED", 16, "192.0.2.10"));
}
@Test
void ambiguousResourcesAreRefused() {
when(service.findByDnsName(NAME)).thenReturn(List.of(balancer("application"), balancer("application")));
assertEquals(Optional.of(DnsAnswer.refused()), source.resolveAliasTarget(NAME, "ZOWNED", 1, "192.0.2.10"));
}
@Test
void missingResourcesAreUnclaimedAndRawNamesAreNotClaimed() {
when(service.findByDnsName(NAME)).thenReturn(List.of());
assertEquals(Optional.empty(), source.resolveAliasTarget(NAME, "ZOWNED", 1, "192.0.2.10"));
assertEquals(Optional.empty(), source.resolveIpv4(NAME));
}
@Test
void validIpv6TargetsAndUnavailableListenerAddressesReturnNoData() {
when(service.findByDnsName(NAME)).thenReturn(List.of(balancer("application")));
assertEquals(Optional.of(DnsAnswer.noData()), source.resolveAliasTarget(NAME, "ZOWNED", 28, "192.0.2.10"));
assertEquals(Optional.of(DnsAnswer.noData()), source.resolveAliasTarget(NAME, "ZOWNED", 1, null));
assertEquals(Optional.of(DnsAnswer.noData()), source.resolveAliasTarget(NAME, "ZOWNED", 1, " "));
}
private static LoadBalancer balancer(String type) {
LoadBalancer target = new LoadBalancer();
target.setType(type);
target.setCanonicalHostedZoneId("ZOWNED");
return target;
}
}
@@ -0,0 +1,108 @@
package io.floci.aws.services.route53;
import io.floci.aws.core.common.dns.DnsAnswer;
import io.floci.aws.core.common.dns.DnsLookupHelper;
import io.floci.aws.core.common.dns.DnsRecord;
import io.floci.aws.core.common.dns.EmbeddedDnsServer;
import io.floci.aws.services.route53.model.AliasTarget;
import io.floci.aws.services.route53.model.ResourceRecord;
import io.floci.aws.services.route53.model.ResourceRecordSet;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class Route53PublicAliasAnswerTest {
private static final String NAME = "api.example.test.";
private final EmbeddedDnsServer dns = mock(EmbeddedDnsServer.class);
private final DnsLookupHelper lookup = mock(DnsLookupHelper.class);
@ParameterizedTest
@ValueSource(strings = {"identifier", "weight", "region", "failover", "healthCheck",
"multivalue", "ttl", "values", "type", "multiple"})
void unsupportedOrMalformedStoredAliasesAreRefusedBeforeTargetLookup(String invalid) {
ResourceRecordSet record = alias();
int type = 1;
switch (invalid) {
case "identifier" -> record.setSetIdentifier("weighted");
case "weight" -> record.setWeight(1L);
case "region" -> record.setRegion("eu-west-1");
case "failover" -> record.setFailover("PRIMARY");
case "healthCheck" -> record.setHealthCheckId("health-check");
case "multivalue" -> record.setMultiValueAnswer(true);
case "ttl" -> record.setTtl(60L);
case "values" -> record.setRecords(List.of(new ResourceRecord("192.0.2.1")));
case "type" -> {
record.setType("TXT");
type = 16;
}
case "multiple" -> record.getAliasTarget().setDnsName("other.example.test.");
default -> throw new AssertionError(invalid);
}
List<ResourceRecordSet> records = "multiple".equals(invalid) ? List.of(record, alias()) : List.of(record);
for (boolean evaluateTargetHealth : new boolean[]{false, true}) {
record.getAliasTarget().setEvaluateTargetHealth(evaluateTargetHealth);
assertEquals(5, source(records).resolveAuthoritative(NAME, type, "192.0.2.20").orElseThrow().responseCode());
}
verifyNoInteractions(dns, lookup);
}
@ParameterizedTest
@CsvSource({"false,false", "false,true", "true,false", "true,true"})
void validTargetsRetainTheirTtlAndZoneAuthority(boolean explicitSimpleRecord, boolean evaluateTargetHealth) {
when(dns.resolveAliasTarget("target.example.test.", "ZOWNED", 1, "192.0.2.20"))
.thenReturn(Optional.of(DnsAnswer.records(List.of("192.0.2.20"), 73)));
ResourceRecordSet record = alias();
record.getAliasTarget().setEvaluateTargetHealth(evaluateTargetHealth);
if (explicitSimpleRecord) {
record.setMultiValueAnswer(false);
}
DnsAnswer answer = source(List.of(record)).resolveAuthoritative(NAME, 1, "192.0.2.20").orElseThrow();
assertEquals(List.of("192.0.2.20"), answer.addresses());
assertEquals(73, answer.ttlSeconds());
assertNotNull(answer.authority());
verifyNoInteractions(lookup);
}
@Test
void missingTargetsAndWrongAddressFamiliesRemainRefused() {
when(dns.resolveAliasTarget("target.example.test.", "ZOWNED", 1, "192.0.2.20")).thenReturn(Optional.empty());
assertEquals(5, source(List.of(alias())).resolveAuthoritative(NAME, 1, "192.0.2.20").orElseThrow().responseCode());
when(dns.resolveAliasTarget("target.example.test.", "ZOWNED", 1, "192.0.2.20")).thenReturn(
Optional.of(DnsAnswer.typedRecords(List.of(new DnsRecord.Address(28, "2001:db8::1")), 60)));
assertEquals(5, source(List.of(alias())).resolveAuthoritative(NAME, 1, "192.0.2.20").orElseThrow().responseCode());
verifyNoInteractions(lookup);
}
private Route53DnsRecordSource source(List<ResourceRecordSet> records) {
Route53Service zones = mock(Route53Service.class);
ResourceRecordSet soa = new ResourceRecordSet();
soa.setName("example.test.");
soa.setType("SOA");
soa.setTtl(60L);
soa.setRecords(List.of(new ResourceRecord("ns.example.test. hostmaster.example.test. 1 60 60 60 60")));
when(zones.publicDnsZones(NAME)).thenReturn(
List.of(new Route53Service.PublicDnsZone("example.test.", records, List.of(soa))));
return new Route53DnsRecordSource(zones, null, lookup, dns);
}
private static ResourceRecordSet alias() {
ResourceRecordSet record = new ResourceRecordSet();
record.setName(NAME);
record.setType("A");
AliasTarget target = new AliasTarget();
target.setDnsName("target.example.test.");
target.setHostedZoneId("ZOWNED");
record.setAliasTarget(target);
return record;
}
}