feat(cloudmap): honor service TTL in DNS A answers (#4448)

* feat(cloudmap): honor service TTL in DNS A answers

* fix(cloudmap): distinguish DNS no-data and reject case collisions

* fix(cloudmap): resolve SRV instance A hostnames

* refactor(cloudmap): simplify DNS answer states and resolver

Give DnsAnswer explicit records, noData and nxDomain factories, drop the
test-only buildAResponse overload, split Cloud Map name resolution into
service and instance-hostname lookups, and parse DnsConfig once on
CreateService.

* fix(cloudmap): lowercase DNS names independent of the default locale

* fix(route53): answer private zone DNS with the record set TTL

Port Route53DnsRecordSource to DnsAnswer after rebasing onto #4353. Answers
carry the record set TTL, a flattened CNAME chain uses the shortest TTL in
the chain, and an alias uses its target's. A name absent from the zone gets
NXDOMAIN; a name with records but no A gets NOERROR with no answers.

* fix(route53): answer empty non-terminals with no data and cap external CNAME TTL

A private zone name with records only beneath it exists in DNS, so it now
answers NOERROR with no A records instead of NXDOMAIN. A CNAME to a name
outside the private zones answers with at most 60 seconds, matching the
alias path, since the target's own TTL is not visible.

* fix(route53): stop wildcards matching at or beneath empty non-terminals

A name with records only beneath it exists, so under RFC 4592 a wildcard
from a farther ancestor must not answer for it or for names below it. The
closer-name check now counts any record sharing an ancestor with the query
name, including wildcard owners, so a closer wildcard also shadows a
parent wildcard.
This commit is contained in:
Abhigya authored and GitHub committed 2026-09-26 23:08:56 -04:00
1 parent c530d1f705
commit 53de56f487
15 files changed
+951 -189

No files matched your search

@@ -0,0 +1,48 @@
package io.github.hectorvent.floci.core.common.dns;
import java.util.List;
/**
* What a {@link DnsRecordSource} answers for a name inside a zone it owns: the A records with the
* TTL the zone publishes for them, an existing name without A records, or an absent name. A name
* the source does not own is an empty optional, not an answer.
*
* <p>The TTL is per answer rather than per record: every address behind one Cloud Map service
* shares that service's TTL, which is how Route 53 publishes a record set.
*/
public record DnsAnswer(List<String> addresses, int ttlSeconds, boolean nameExists) {
/** What the DNS server publishes for a name whose zone declares no TTL of its own. */
public static final int DEFAULT_TTL_SECONDS = 60;
private static final DnsAnswer NX_DOMAIN = new DnsAnswer(List.of(), DEFAULT_TTL_SECONDS, false);
private static final DnsAnswer NO_DATA = new DnsAnswer(List.of(), DEFAULT_TTL_SECONDS, true);
public DnsAnswer {
// A TTL is an unsigned 31-bit field; RFC 2181 has a resolver read anything with the top
// bit set as zero. A source picks its own fallback rather than putting one on the wire.
if (ttlSeconds < 0) {
throw new IllegalArgumentException("DNS TTL must not be negative: " + ttlSeconds);
}
addresses = List.copyOf(addresses);
}
/** A records for an existing name, all published with the same TTL. */
public static DnsAnswer records(List<String> addresses, int ttlSeconds) {
return new DnsAnswer(addresses, ttlSeconds, true);
}
/** An existing name without A records: NOERROR with no answers. */
public static DnsAnswer noData() {
return NO_DATA;
}
/** An absent name inside an owned zone: NXDOMAIN. */
public static DnsAnswer nxDomain() {
return NX_DOMAIN;
}
public boolean isEmpty() {
return addresses.isEmpty();
}
}
@@ -1,6 +1,5 @@
package io.github.hectorvent.floci.core.common.dns;
import java.util.List;
import java.util.Optional;
/**
@@ -9,14 +8,14 @@ import java.util.Optional;
* independent of them: it discovers implementations through CDI rather than importing one.
*
* <p>An implementation answers only for names inside a zone it owns. An empty optional leaves
* the query to the next source or the upstream resolvers; a present empty list means the name
* is owned but has no A records. It runs outside any request context.
* the query to the next source or the upstream resolvers; a present answer with no addresses
* means the name is owned but has no A records. It runs outside any request context.
*/
public interface DnsRecordSource {
/**
* Resolves a query name to IPv4 addresses. 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.
* 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.
*/
Optional<List<String>> resolveIpv4(String name);
Optional<DnsAnswer> resolveIpv4(String name);
}
@@ -52,7 +52,6 @@ public class EmbeddedDnsServer {
private static final Logger LOG = Logger.getLogger(EmbeddedDnsServer.class);
static final int DNS_PORT = 53;
private static final int TTL = 60;
private static final String FALLBACK_UPSTREAM = "127.0.0.11";
// EDNS0-capable resolvers (Node/c-ares, glibc) advertise UDP payloads well above the
// legacy 512-byte limit; CDN-backed public names return larger responses. Receiving into
@@ -67,7 +66,7 @@ public class EmbeddedDnsServer {
Pattern.compile("^ip-(\\d{1,3})-(\\d{1,3})-(\\d{1,3})-(\\d{1,3})\\.ec2\\.internal$", Pattern.CASE_INSENSITIVE);
// Well-known emulator wildcard DNS domains that always resolve to Floci's IP.
// The suffix "localhost.X" covers "localhost.X" itself and "*.localhost.X" — it does
// The suffix "localhost.X" covers "localhost.X" itself and "*.localhost.X"; it does
// NOT cover "*.X" (e.g. "localhost.floci.io" does NOT resolve bare "*.floci.io").
// localhost.localstack.cloud → localhost.localstack.cloud, *.localhost.localstack.cloud
// localhost.floci.io → localhost.floci.io, *.localhost.floci.io
@@ -129,7 +128,7 @@ public class EmbeddedDnsServer {
// ── packet handling ───────────────────────────────────────────────────────
private void handleQuery(Vertx vertx, DatagramSocket socket, byte[] data,
void handleQuery(Vertx vertx, DatagramSocket socket, byte[] data,
String senderHost, int senderPort, String myIp) {
try {
ByteBuffer buf = ByteBuffer.wrap(data);
@@ -150,17 +149,17 @@ public class EmbeddedDnsServer {
buf.getShort(); // qclass
int questionEnd = buf.position();
vertx.<Optional<List<String>>>executeBlocking(() -> resolveARecordWithOwnership(qname, myIp), false)
vertx.<Optional<DnsAnswer>>executeBlocking(() -> resolveARecordWithOwnership(qname, myIp), false)
.onSuccess(answer -> {
if (answer.isEmpty()) {
forwardAsync(vertx, socket, data, senderHost, senderPort);
return;
}
List<String> addresses = answer.orElseThrow();
byte[] response = qtype == 1 && !addresses.isEmpty()
? buildAResponse(data, txId, questionOffset, questionEnd, addresses)
DnsAnswer records = answer.orElseThrow();
byte[] response = qtype == 1 && !records.isEmpty()
? buildAResponse(data, txId, questionOffset, questionEnd, records)
: buildEmptyResponse(data, txId, questionOffset, questionEnd,
addresses.isEmpty() ? 3 : 0);
records.nameExists() ? 0 : 3);
socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {});
})
.onFailure(e -> LOG.warnv("DNS record lookup failed for {0}: {1}", qname, e.getMessage()));
@@ -186,15 +185,17 @@ public class EmbeddedDnsServer {
}
List<String> resolveARecord(String name, String myIp) {
return resolveARecordWithOwnership(name, myIp).orElse(List.of());
return resolveARecordWithOwnership(name, myIp)
.map(DnsAnswer::addresses).orElse(List.of());
}
Optional<List<String>> resolveARecordWithOwnership(String name, String myIp) {
Optional<DnsAnswer> resolveARecordWithOwnership(String name, String myIp) {
if (matchesSuffix(name)) {
return Optional.of(List.of(myIp));
return Optional.of(DnsAnswer.records(List.of(myIp), DnsAnswer.DEFAULT_TTL_SECONDS));
}
Optional<String> ec2PrivateDnsName = resolveEc2PrivateDnsName(name);
return ec2PrivateDnsName.<List<String>>map(List::of)
return ec2PrivateDnsName
.map(address -> DnsAnswer.records(List.of(address), DnsAnswer.DEFAULT_TTL_SECONDS))
.map(Optional::of).orElseGet(() -> resolveFromRecordSources(name));
}
@@ -203,15 +204,15 @@ public class EmbeddedDnsServer {
* today. A source that throws must not take the DNS server down with it: the query falls
* through to the upstream resolvers, which is what happened before any source existed.
*/
private Optional<List<String>> resolveFromRecordSources(String name) {
private Optional<DnsAnswer> resolveFromRecordSources(String name) {
if (recordSources == null) {
return Optional.empty();
}
for (DnsRecordSource source : recordSources) {
try {
Optional<List<String>> addresses = source.resolveIpv4(name);
if (addresses != null && addresses.isPresent()) {
return addresses;
Optional<DnsAnswer> answer = source.resolveIpv4(name);
if (answer != null && answer.isPresent()) {
return answer;
}
} catch (Exception e) {
LOG.debugv("DNS record source {0} failed to resolve {1}: {2}",
@@ -302,7 +303,8 @@ public class EmbeddedDnsServer {
return sb.toString();
}
byte[] buildAResponse(byte[] query, short txId, int questionOffset, int questionEnd, List<String> ips) {
byte[] buildAResponse(byte[] query, short txId, int questionOffset, int questionEnd, DnsAnswer answer) {
List<String> ips = answer.addresses();
int questionLength = questionEnd - questionOffset;
// header(12) + question + per answer(name-ptr(2) + type(2) + class(2) + ttl(4) + rdlen(2) + rdata(4))
ByteBuffer resp = ByteBuffer.allocate(12 + questionLength + 16 * ips.size());
@@ -324,7 +326,7 @@ public class EmbeddedDnsServer {
resp.putShort((short) 0xC00C); // name pointer to offset 12 (start of question name)
resp.putShort((short) 1); // type A
resp.putShort((short) 1); // class IN
resp.putInt(TTL);
resp.putInt(answer.ttlSeconds());
resp.putShort((short) 4); // rdlength
for (String octet : ip.split("\\.")) {
@@ -1,10 +1,10 @@
package io.github.hectorvent.floci.services.cloudmap;
import io.github.hectorvent.floci.core.common.dns.DnsAnswer;
import io.github.hectorvent.floci.core.common.dns.DnsRecordSource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.List;
import java.util.Optional;
/**
@@ -27,7 +27,7 @@ public class CloudMapDnsRecordSource implements DnsRecordSource {
}
@Override
public Optional<List<String>> resolveIpv4(String name) {
public Optional<DnsAnswer> resolveIpv4(String name) {
return cloudMapService.resolveDnsNameIfOwned(name);
}
}
@@ -1,9 +1,14 @@
package io.github.hectorvent.floci.services.cloudmap;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.MissingNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.dns.DnsAnswer;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -22,7 +27,9 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Executors;
@@ -50,12 +57,13 @@ public class CloudMapService {
private final StorageBackend<String, Instance> instanceStore;
private final StorageBackend<String, Operation> operationStore;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
private final int completionDelaySeconds;
private final ScheduledExecutorService scheduler;
@Inject
public CloudMapService(StorageFactory storageFactory, EmulatorConfig config,
RegionResolver regionResolver) {
RegionResolver regionResolver, ObjectMapper objectMapper) {
this.namespaceStore = storageFactory.create("cloudmap", "cloudmap-namespaces.json",
new TypeReference<Map<String, Namespace>>() {});
this.serviceStore = storageFactory.create("cloudmap", "cloudmap-services.json",
@@ -65,6 +73,7 @@ public class CloudMapService {
this.operationStore = storageFactory.create("cloudmap", "cloudmap-operations.json",
new TypeReference<Map<String, Operation>>() {});
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
this.completionDelaySeconds = config.services().cloudmap().operationCompletionDelaySeconds();
this.scheduler = completionDelaySeconds > 0
? Executors.newSingleThreadScheduledExecutor(r -> {
@@ -173,18 +182,19 @@ public class CloudMapService {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidInput", "Service name is required.", 400);
}
JsonNode dnsConfigNode = dnsConfig == null ? null : parseDnsConfig(dnsConfig);
String resolvedNamespaceId = namespaceId;
if (dnsConfig != null && resolvedNamespaceId == null) {
if (dnsConfigNode != null && resolvedNamespaceId == null) {
// DnsConfig may carry the namespace id when the top-level field is absent.
resolvedNamespaceId = dnsConfigNamespaceId(dnsConfig);
}
if (resolvedNamespaceId != null) {
requireNamespace(resolvedNamespaceId);
resolvedNamespaceId = dnsConfigNode.path("NamespaceId").textValue();
}
Namespace namespace = resolvedNamespaceId == null ? null : requireNamespace(resolvedNamespaceId);
boolean dnsNamespace = namespace != null && ("DNS_PRIVATE".equals(namespace.getType())
|| "DNS_PUBLIC".equals(namespace.getType()));
final String nsId = resolvedNamespaceId;
boolean exists = scan(serviceStore).stream()
.anyMatch(s -> region.equals(s.getRegion()) && name.equals(s.getName())
&& java.util.Objects.equals(nsId, s.getNamespaceId()));
.anyMatch(s -> region.equals(s.getRegion()) && Objects.equals(nsId, s.getNamespaceId())
&& (dnsNamespace ? name.equalsIgnoreCase(s.getName()) : name.equals(s.getName())));
if (exists) {
throw new AwsException("ServiceAlreadyExists",
"A service named \"" + name + "\" already exists.", 400);
@@ -377,23 +387,24 @@ public class CloudMapService {
* either way.
*/
public List<String> resolveDnsName(String queryName) {
return resolveDnsNameIfOwned(queryName).orElse(List.of());
return resolveDnsNameIfOwned(queryName)
.map(DnsAnswer::addresses).orElse(List.of());
}
/** Keeps zone ownership distinct from the list of A records. */
public Optional<List<String>> resolveDnsNameIfOwned(String queryName) {
/** Keeps zone ownership distinct from the A records and their TTL. */
public Optional<DnsAnswer> resolveDnsNameIfOwned(String queryName) {
if (queryName == null || queryName.isBlank()) {
return Optional.empty();
}
String name = queryName.toLowerCase();
String name = queryName.toLowerCase(Locale.ROOT);
if (name.endsWith(".")) {
name = name.substring(0, name.length() - 1);
}
List<String> addresses = new ArrayList<>();
String matchedNamespaceName = null;
boolean nameExists = false;
for (Namespace namespace : dnsNamespacesByLongestName()) {
String namespaceName = namespace.getName().toLowerCase();
String namespaceName = namespace.getName().toLowerCase(Locale.ROOT);
String suffix = "." + namespaceName;
boolean apex = name.equals(namespaceName);
if (!apex && !name.endsWith(suffix)) {
@@ -404,27 +415,142 @@ public class CloudMapService {
}
matchedNamespaceName = namespaceName;
if (apex) {
nameExists = true;
continue;
}
String serviceName = name.substring(0, name.length() - suffix.length());
for (Service service : scan(serviceStore)) {
if (!namespace.getId().equals(service.getNamespaceId())
|| !serviceName.equalsIgnoreCase(service.getName())) {
continue;
}
for (Instance instance : applyHealthFilter(scanInstances(service.getId()), "HEALTHY_OR_ELSE_ALL")) {
String ipv4 = instance.getAttributes().get("AWS_INSTANCE_IPV4");
if (isIpv4(ipv4)) {
addresses.add(ipv4);
}
String label = name.substring(0, name.length() - suffix.length());
List<Service> services = scan(serviceStore).stream()
.filter(service -> namespace.getId().equals(service.getNamespaceId()))
.toList();
Optional<DnsAnswer> byService = resolveServiceName(services, label);
if (byService.filter(answer -> !answer.isEmpty()).isPresent()) {
return byService;
}
Optional<DnsAnswer> byInstance = resolveInstanceHostname(services, label);
if (byInstance.filter(answer -> !answer.isEmpty()).isPresent()) {
return byInstance;
}
nameExists |= byService.isPresent() || byInstance.isPresent();
}
return matchedNamespaceName != null
? Optional.of(nameExists ? DnsAnswer.noData() : DnsAnswer.nxDomain()) : Optional.empty();
}
/**
* The A records at {@code <service>.<namespace>}. A service without an A record still owns its
* name while it has instances, since its SRV record lives there, so it answers no-data.
*/
private Optional<DnsAnswer> resolveServiceName(List<Service> services, String label) {
boolean exists = false;
for (Service service : services) {
if (!label.equalsIgnoreCase(service.getName())) {
continue;
}
int ttl = dnsRecordTtl(service, "A");
if (ttl < 0) {
exists |= !scanInstances(service.getId()).isEmpty();
continue;
}
List<String> addresses = new ArrayList<>();
for (Instance instance : applyHealthFilter(scanInstances(service.getId()), "HEALTHY_OR_ELSE_ALL")) {
String ipv4 = instance.getAttributes().get("AWS_INSTANCE_IPV4");
if (isIpv4(ipv4)) {
addresses.add(ipv4);
}
}
if (!addresses.isEmpty()) {
return Optional.of(addresses.size() > MAX_DNS_ANSWERS
? addresses.subList(0, MAX_DNS_ANSWERS) : addresses);
return Optional.of(DnsAnswer.records(addresses.size() > MAX_DNS_ANSWERS
? addresses.subList(0, MAX_DNS_ANSWERS) : addresses, ttl));
}
}
return matchedNamespaceName != null ? Optional.of(List.of()) : Optional.empty();
return exists ? Optional.of(DnsAnswer.noData()) : Optional.empty();
}
/**
* The A record Cloud Map creates at an SRV record's target, {@code <InstanceId>.<service>.<namespace>},
* published with the service's SRV TTL.
*/
private Optional<DnsAnswer> resolveInstanceHostname(List<Service> services, String label) {
boolean exists = false;
for (Service service : services) {
String serviceSuffix = "." + service.getName().toLowerCase(Locale.ROOT);
if (!label.endsWith(serviceSuffix)) {
continue;
}
int ttl = dnsRecordTtl(service, "SRV");
if (ttl < 0) {
continue;
}
String instanceId = label.substring(0, label.length() - serviceSuffix.length());
for (Instance instance : scanInstances(service.getId())) {
if (!instanceId.equalsIgnoreCase(instance.getInstanceId())) {
continue;
}
exists = true;
String ipv4 = instance.getAttributes().get("AWS_INSTANCE_IPV4");
if (isIpv4(ipv4)) {
return Optional.of(DnsAnswer.records(List.of(ipv4), ttl));
}
}
}
return exists ? Optional.of(DnsAnswer.noData()) : Optional.empty();
}
private JsonNode parseDnsConfig(String dnsConfig) {
JsonNode config;
try {
config = objectMapper.readTree(dnsConfig);
} catch (JacksonException e) {
throw new AwsException("InvalidInput", "DnsConfig must be valid JSON.", 400);
}
JsonNode records = config == null ? MissingNode.getInstance() : config.path("DnsRecords");
if (!records.isArray()) {
throw new AwsException("InvalidInput", "DnsConfig.DnsRecords is required.", 400);
}
for (JsonNode record : records) {
if (ttlSeconds(record.path("TTL")) < 0) {
throw new AwsException("InvalidInput",
"DnsRecords TTL must be an integer from 0 to 2147483647.", 400);
}
}
return config;
}
/** Returns -1 when the service has no record of the requested type. */
private int dnsRecordTtl(Service service, String type) {
JsonNode records = dnsConfigNode(service).path("DnsRecords");
if (!records.isArray()) {
return "A".equals(type) ? DnsAnswer.DEFAULT_TTL_SECONDS : -1;
}
for (JsonNode record : records) {
if (type.equalsIgnoreCase(record.path("Type").asText())) {
int ttl = ttlSeconds(record.path("TTL"));
return ttl >= 0 ? ttl : DnsAnswer.DEFAULT_TTL_SECONDS;
}
}
return -1;
}
private static int ttlSeconds(JsonNode ttl) {
if (!ttl.isIntegralNumber() || !ttl.canConvertToInt()) {
return -1;
}
int value = ttl.intValue();
return value >= 0 ? value : -1;
}
private JsonNode dnsConfigNode(Service service) {
String dnsConfig = service.getDnsConfig();
if (dnsConfig == null || dnsConfig.isBlank()) {
return MissingNode.getInstance();
}
try {
return objectMapper.readTree(dnsConfig);
} catch (JacksonException e) {
LOG.debugv("Could not read the DnsConfig of Cloud Map service {0}: {1}",
service.getId(), e.getMessage());
return MissingNode.getInstance();
}
}
/**
@@ -649,17 +775,6 @@ public class CloudMapService {
return dnsConfig != null ? "DNS_HTTP" : "HTTP";
}
private String dnsConfigNamespaceId(String dnsConfig) {
// Best-effort extraction of a NamespaceId embedded in the DnsConfig JSON.
int idx = dnsConfig.indexOf("\"NamespaceId\"");
if (idx < 0) {
return null;
}
int start = dnsConfig.indexOf('"', dnsConfig.indexOf(':', idx) + 1);
int end = dnsConfig.indexOf('"', start + 1);
return (start > 0 && end > start) ? dnsConfig.substring(start + 1, end) : null;
}
private String randomId(int length) {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.route53;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.dns.DnsAnswer;
import io.github.hectorvent.floci.core.common.dns.DnsLookupHelper;
import io.github.hectorvent.floci.core.common.dns.DnsRecordSource;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
@@ -15,6 +16,7 @@ import java.net.InetAddress;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
@@ -63,36 +65,37 @@ public class Route53DnsRecordSource implements DnsRecordSource {
}
@Override
public Optional<List<String>> resolveIpv4(String name) {
public Optional<DnsAnswer> resolveIpv4(String name) {
if (name == null || name.isBlank()) {
return Optional.empty();
}
if (!route53Service.isCoveredByPrivateZone(name)) {
return Optional.empty();
}
List<String> addresses = resolveAddresses(name, new HashSet<>(), 0);
if (addresses.size() > MAX_DNS_ANSWERS) {
addresses = addresses.subList(0, MAX_DNS_ANSWERS);
DnsAnswer answer = resolveAddresses(name, new HashSet<>(), 0);
if (answer.addresses().size() > MAX_DNS_ANSWERS) {
answer = DnsAnswer.records(answer.addresses().subList(0, MAX_DNS_ANSWERS), answer.ttlSeconds());
}
return Optional.of(addresses);
return Optional.of(answer);
}
private List<String> resolveAddresses(String qname, Set<String> visited, int depth) {
private DnsAnswer resolveAddresses(String qname, Set<String> visited, int depth) {
if (depth > MAX_CNAME_DEPTH) {
return List.of();
return DnsAnswer.noData();
}
String normalized = Route53Service.normalizeName(qname).toLowerCase();
String normalized = Route53Service.normalizeName(qname).toLowerCase(Locale.ROOT);
if (!visited.add(normalized)) {
return List.of();
return DnsAnswer.noData();
}
List<ResourceRecordSet> recordSets = route53Service.findPrivateRecordsForName(qname);
if (recordSets.isEmpty()) {
return List.of();
return route53Service.hasPrivateRecordsBeneath(qname) ? DnsAnswer.noData() : DnsAnswer.nxDomain();
}
// 1. Direct A records
Set<String> addresses = new LinkedHashSet<>();
int ttl = Integer.MAX_VALUE;
for (ResourceRecordSet rrs : recordSets) {
if ("A".equalsIgnoreCase(rrs.getType())) {
if (rrs.getRecords() != null) {
@@ -100,6 +103,7 @@ public class Route53DnsRecordSource implements DnsRecordSource {
String val = rr.getValue();
if (isIpv4(val)) {
addresses.add(val.trim());
ttl = Math.min(ttl, ttlOf(rrs));
}
}
}
@@ -109,23 +113,25 @@ public class Route53DnsRecordSource implements DnsRecordSource {
if (cleanAlias.endsWith(".")) {
cleanAlias = cleanAlias.substring(0, cleanAlias.length() - 1);
}
// An alias record has no TTL of its own; Route 53 answers with the target's.
if (route53Service.isCoveredByPrivateZone(cleanAlias)) {
addresses.addAll(resolveAddresses(cleanAlias, visited, depth + 1));
} else if (matchesFlociSuffix(cleanAlias)) {
getLocalFlociAddress().ifPresent(addresses::add);
DnsAnswer target = resolveAddresses(cleanAlias, visited, depth + 1);
if (!target.isEmpty()) {
addresses.addAll(target.addresses());
ttl = Math.min(ttl, target.ttlSeconds());
}
} else {
Optional<String> ec2Ip = resolveEc2PrivateDnsName(cleanAlias);
if (ec2Ip.isPresent()) {
addresses.add(ec2Ip.get());
} else {
addresses.addAll(dnsLookupHelper.resolveIpv4(cleanAlias));
List<String> resolved = resolveOutsidePrivateZones(cleanAlias);
if (!resolved.isEmpty()) {
addresses.addAll(resolved);
ttl = Math.min(ttl, DnsAnswer.DEFAULT_TTL_SECONDS);
}
}
}
}
}
if (!addresses.isEmpty()) {
return List.copyOf(addresses);
return DnsAnswer.records(List.copyOf(addresses), ttl);
}
// 2. CNAME records
@@ -138,23 +144,41 @@ public class Route53DnsRecordSource implements DnsRecordSource {
if (cleanTarget.endsWith(".")) {
cleanTarget = cleanTarget.substring(0, cleanTarget.length() - 1);
}
// The answer is flattened to A records, so it can be cached only as long
// as the shortest-lived record in the chain.
int cnameTtl = ttlOf(rrs);
if (route53Service.isCoveredByPrivateZone(cleanTarget)) {
return resolveAddresses(cleanTarget, visited, depth + 1);
DnsAnswer targetAnswer = resolveAddresses(cleanTarget, visited, depth + 1);
return DnsAnswer.records(targetAnswer.addresses(),
Math.min(cnameTtl, targetAnswer.ttlSeconds()));
}
if (matchesFlociSuffix(cleanTarget)) {
return getLocalFlociAddress().map(List::of).orElse(List.of());
}
Optional<String> ec2Ip = resolveEc2PrivateDnsName(cleanTarget);
if (ec2Ip.isPresent()) {
return List.of(ec2Ip.get());
}
return dnsLookupHelper.resolveIpv4(cleanTarget);
return DnsAnswer.records(resolveOutsidePrivateZones(cleanTarget),
Math.min(cnameTtl, DnsAnswer.DEFAULT_TTL_SECONDS));
}
}
}
}
return List.of();
return DnsAnswer.noData();
}
private List<String> resolveOutsidePrivateZones(String name) {
if (matchesFlociSuffix(name)) {
return getLocalFlociAddress().map(List::of).orElse(List.of());
}
Optional<String> ec2Ip = resolveEc2PrivateDnsName(name);
if (ec2Ip.isPresent()) {
return List.of(ec2Ip.get());
}
return dnsLookupHelper.resolveIpv4(name);
}
private static int ttlOf(ResourceRecordSet rrs) {
Long ttl = rrs.getTtl();
if (ttl == null || ttl < 0) {
return DnsAnswer.DEFAULT_TTL_SECONDS;
}
return (int) Math.min(ttl, Integer.MAX_VALUE);
}
private boolean matchesFlociSuffix(String name) {
@@ -614,38 +614,10 @@ public class Route53Service implements Resettable {
return List.of();
}
String normalizedQname = normalizeName(qname).toLowerCase();
if (privateZoneNameCounts.isEmpty()
|| privateZoneNameCounts.keySet().stream().noneMatch(z -> normalizedQname.equals(z) || normalizedQname.endsWith("." + z))) {
return List.of();
}
List<OwnedZone> matchingZones = new ArrayList<>();
for (OwnedZone owned : allHostedZonesAcrossAccounts()) {
HostedZone zone = owned.zone();
if (!zone.isPrivateZone()) {
continue;
}
String zoneName = normalizeName(zone.getName()).toLowerCase();
if (normalizedQname.equals(zoneName) || normalizedQname.endsWith("." + zoneName)) {
matchingZones.add(owned);
}
}
matchingZones.sort((a, b) -> Integer.compare(
normalizeName(b.zone().getName()).length(),
normalizeName(a.zone().getName()).length()));
if (matchingZones.isEmpty()) {
return List.of();
}
// Only search the most-specific matching zone(s) to avoid leaking parent zone records
int maxZoneLength = normalizeName(matchingZones.get(0).zone().getName()).length();
List<ResourceRecordSet> nameMatches = new ArrayList<>();
List<ResourceRecordSet> wildcardMatches = new ArrayList<>();
for (OwnedZone owned : matchingZones) {
if (normalizeName(owned.zone().getName()).length() < maxZoneLength) {
break;
}
for (OwnedZone owned : mostSpecificPrivateZones(normalizedQname)) {
List<ResourceRecordSet> records = getRecordsForZoneAcrossAccounts(owned.accountId(), owned.zone().getId());
List<ResourceRecordSet> zoneWildcards = new ArrayList<>();
for (ResourceRecordSet rrs : records) {
@@ -661,12 +633,11 @@ public class Route53Service implements Resettable {
String rName = normalizeName(rrs.getName()).toLowerCase();
String wildcardSuffix = rName.substring(2); // e.g. "corp.internal."
if (normalizedQname.endsWith("." + wildcardSuffix)) {
// Wildcard cannot match beneath an existing closer name in the same zone (RFC 1034 4.3.3)
// A wildcard cannot match when the name or an ancestor closer than the wildcard's
// parent exists, and a name with records only beneath it exists too (RFC 4592 2.2)
boolean closerNameExists = records.stream()
.map(r -> normalizeName(r.getName()).toLowerCase())
.filter(n -> !n.startsWith("*."))
.anyMatch(n -> n.length() > wildcardSuffix.length()
&& (normalizedQname.equals(n) || normalizedQname.endsWith("." + n)));
.anyMatch(n -> sharedSuffixLength(n, normalizedQname) > wildcardSuffix.length());
if (!closerNameExists) {
wildcardMatches.add(rrs);
}
@@ -677,6 +648,70 @@ public class Route53Service implements Resettable {
return !nameMatches.isEmpty() ? nameMatches : wildcardMatches;
}
/** Length of the longest whole-label suffix two normalized names share, trailing dot included. */
private static int sharedSuffixLength(String a, String b) {
int i = a.length();
int j = b.length();
int shared = 0;
while (i > 0 && j > 0 && a.charAt(i - 1) == b.charAt(j - 1)) {
i--;
j--;
boolean labelStart = (i == 0 || a.charAt(i - 1) == '.') && (j == 0 || b.charAt(j - 1) == '.');
if (labelStart) {
shared = a.length() - i;
}
}
return shared;
}
/**
* Whether a private zone holds records beneath {@code qname} although none at it: an empty
* non-terminal, which exists in DNS and so answers NOERROR rather than NXDOMAIN.
*/
public boolean hasPrivateRecordsBeneath(String qname) {
if (qname == null || qname.isBlank()) {
return false;
}
String normalizedQname = normalizeName(qname).toLowerCase();
String suffix = "." + normalizedQname;
for (OwnedZone owned : mostSpecificPrivateZones(normalizedQname)) {
for (ResourceRecordSet rrs : getRecordsForZoneAcrossAccounts(owned.accountId(), owned.zone().getId())) {
if (normalizeName(rrs.getName()).toLowerCase().endsWith(suffix)) {
return true;
}
}
}
return false;
}
/** The private zones with the longest name containing {@code normalizedQname}, so a parent zone never answers for a child. */
private List<OwnedZone> mostSpecificPrivateZones(String normalizedQname) {
if (privateZoneNameCounts.isEmpty()
|| privateZoneNameCounts.keySet().stream().noneMatch(z -> normalizedQname.equals(z) || normalizedQname.endsWith("." + z))) {
return List.of();
}
List<OwnedZone> matchingZones = new ArrayList<>();
int maxZoneLength = -1;
for (OwnedZone owned : allHostedZonesAcrossAccounts()) {
HostedZone zone = owned.zone();
if (!zone.isPrivateZone()) {
continue;
}
String zoneName = normalizeName(zone.getName()).toLowerCase();
if (!normalizedQname.equals(zoneName) && !normalizedQname.endsWith("." + zoneName)) {
continue;
}
if (zoneName.length() > maxZoneLength) {
matchingZones.clear();
maxZoneLength = zoneName.length();
}
if (zoneName.length() == maxZoneLength) {
matchingZones.add(owned);
}
}
return matchingZones;
}
private List<ResourceRecordSet> getRecordsForZoneAcrossAccounts(String accountId, String zoneId) {
if (recordStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")