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

+16 -5
View File
@@ -32,13 +32,24 @@ unhealthy still resolves rather than disappearing from DNS. At most eight record
go back either way, as Route 53 answers a service discovery query.
Names inside a DNS namespace stay local when no instance has a usable address:
the resolver answers negatively instead of forwarding them to upstream DNS.
An absent service name receives NXDOMAIN; a service with registered instances
and only other record types receives NOERROR with no A answers. DNS service
names are unique without regard to case, as in AWS Cloud Map.
A records carry the TTL of the service's `A` entry in `DnsConfig.DnsRecords`.
A service configured for SRV also answers A queries at
`<InstanceId>.<service>.<namespace>` when that instance has `AWS_INSTANCE_IPV4`.
Those answers use the service's SRV TTL. The SRV service name itself has no A
answer. Floci uses a 60-second fallback for older stored services without a
usable A record TTL.
New `CreateService` requests reject TTL values outside AWS's 0 to 2147483647
range. Names owned by Floci's embedded DNS server also use 60 seconds.
Three limits are worth knowing. `HTTP` namespaces do not resolve, matching AWS,
where they are reachable only through `DiscoverInstances`. Only A records are
served, so a name that AWS would answer with an `SRV` record answers with the
address alone. And the embedded DNS server only runs when Floci itself runs
inside Docker, so name resolution is available to containers, not to processes on
the host.
served; SRV queries are not yet answered. The embedded DNS server only runs
when Floci itself runs inside Docker, so name resolution is available to
containers, not to processes on the host.
## Supported Operations
@@ -139,7 +150,7 @@ print(found["Instances"])
## Out of Scope
- Route 53 hosted zone / record set creation.
- SRV, AAAA and CNAME records: `AWS_INSTANCE_PORT` is stored and returned, but only A records are served.
- SRV, AAAA and CNAME record responses: `AWS_INSTANCE_PORT` is stored and returned, but only A records are served, including the companion A record for an SRV instance hostname.
- Route 53 health checks backing `HealthCheckConfig` (custom health status is stored, not actively probed).
- `AWS_INIT_HEALTH_STATUS` and `AWS_EC2_INSTANCE_ID` on `RegisterInstance`. Every instance registers `HEALTHY`, which is AWS's own initial status when `AWS_INIT_HEALTH_STATUS` is absent, so only a caller that explicitly asks for `UNHEALTHY` sees a difference.
- Cross-region namespace and service discovery. A DNS query carries no region, so a name resolves through whichever namespace copy holds instances.
+1
View File
@@ -59,6 +59,7 @@ Route53 emulation supporting hosted zones, resource record sets, health checks,
Floci resolves private hosted zone DNS records directly through its embedded DNS server on port 53. Cluster containers (such as EKS k3s containers) and workloads wired to embedded DNS automatically query Floci as their primary resolver.
- **Record Types**: Resolves IPv4 `A` records (including `CNAME` and `ALIAS` target chasing across private zones, EC2 internal names, and external hostnames). When a private CNAME targets a public hostname, Floci resolves the target addresses off the event loop so container stub resolvers succeed. Multiple values are returned as separate answers.
- **TTL and Negative Answers**: Answers carry the record set's `TTL`. A chased `CNAME` chain is flattened to `A` records, so it answers with the shortest TTL in the chain; an alias answers with its target's TTL, and an alias or `CNAME` to a name outside the private zones answers with at most 60 seconds, since Floci cannot see that target's TTL. A name absent from the zone receives NXDOMAIN; a name that exists without an `A` record (only `TXT`, for example, or only records beneath it) receives NOERROR with no answers. A wildcard record such as `*.example.internal` answers only when neither the name nor an ancestor closer than the wildcard exists, so a record at `api.team.example.internal` keeps the wildcard from answering for `team.example.internal` or anything beneath it.
- **Zone Visibility and Fallthrough**: Only private hosted zones (created with a VPC association) are answered by Floci's embedded Route 53 resolver. Public zones and external domains fall through to upstream forwarders. Because the standard DNS wire protocol carries no caller VPC identifier, Floci resolves across private zones without filtering by account or VPC ID.
- **Zero-Restart Propagation**: Record changes via `ChangeResourceRecordSets` take effect immediately without restarts.
- **Kubernetes and external-dns Compatibility**: In-cluster controllers like `external-dns` provisioning Route 53 private records for Services or Ingresses are immediately resolvable.
@@ -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")
@@ -0,0 +1,162 @@
package io.github.hectorvent.floci.core.common.dns;
import io.github.hectorvent.floci.services.cloudmap.CloudMapDnsRecordSource;
import io.github.hectorvent.floci.services.cloudmap.CloudMapService;
import io.github.hectorvent.floci.services.cloudmap.model.Service;
import io.quarkus.test.junit.QuarkusTest;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.datagram.DatagramSocket;
import io.vertx.core.datagram.DatagramSocketOptions;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
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;
@QuarkusTest
class CloudMapDnsPacketIntegrationTest {
private static final String REGION = "us-east-1";
@Inject
CloudMapService cloudMapService;
@Inject
CloudMapDnsRecordSource cloudMapDnsRecordSource;
@Inject
Vertx vertx;
@Test
void configuredTtlReachesTheDnsPacket() throws Exception {
String namespace = uniqueNamespace();
String namespaceId = privateDnsNamespace(namespace);
Service service = cloudMapService.createService("api", namespaceId, null, null,
"{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":15}]}", null, null, null, Map.of(), REGION);
cloudMapService.registerInstance(service.getId(), "task-1", null,
Map.of("AWS_INSTANCE_IPV4", "172.31.0.6"), REGION);
byte[] request = buildQuery("api." + namespace, (short) 1);
byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request);
ByteBuffer packet = ByteBuffer.wrap(response);
assertEquals(0, packet.getShort(2) & 0x000F);
assertEquals(1, packet.getShort(6));
assertEquals(15, packet.getInt(request.length + 6));
assertArrayEquals(new byte[]{(byte) 172, 31, 0, 6},
Arrays.copyOfRange(response, request.length + 12, request.length + 16));
}
@Test
void srvOnlyNameReturnsNoDataForAQuery() throws Exception {
String namespace = uniqueNamespace();
String namespaceId = privateDnsNamespace(namespace);
Service service = cloudMapService.createService("srvonly", namespaceId, null, null,
"{\"DnsRecords\":[{\"Type\":\"SRV\",\"TTL\":300}]}", null, null, null, Map.of(), REGION);
cloudMapService.registerInstance(service.getId(), "task-1", null,
Map.of("AWS_INSTANCE_IPV4", "172.31.0.6", "AWS_INSTANCE_PORT", "8080"), REGION);
byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)),
buildQuery("srvonly." + namespace, (short) 1));
ByteBuffer packet = ByteBuffer.wrap(response);
assertEquals(0, packet.getShort(2) & 0x000F);
assertTrue((packet.getShort(2) & 0x0400) != 0);
assertEquals(0, packet.getShort(6));
}
@Test
void srvInstanceHostnameAnswersAQueryWithConfiguredTtl() throws Exception {
String namespace = uniqueNamespace();
String namespaceId = privateDnsNamespace(namespace);
Service service = cloudMapService.createService("backend", namespaceId, null, null,
"{\"DnsRecords\":[{\"Type\":\"SRV\",\"TTL\":300}]}", null, null, null, Map.of(), REGION);
cloudMapService.registerInstance(service.getId(), "task-1", null,
Map.of("AWS_INSTANCE_IPV4", "172.31.0.6", "AWS_INSTANCE_PORT", "8080"), REGION);
byte[] request = buildQuery("task-1.backend." + namespace, (short) 1);
byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request);
ByteBuffer packet = ByteBuffer.wrap(response);
assertEquals(0, packet.getShort(2) & 0x000F);
assertEquals(1, packet.getShort(6));
assertEquals(300, packet.getInt(request.length + 6));
assertArrayEquals(new byte[]{(byte) 172, 31, 0, 6},
Arrays.copyOfRange(response, request.length + 12, request.length + 16));
}
@Test
void absentServiceNameStillReturnsNxDomain() throws Exception {
String namespace = uniqueNamespace();
privateDnsNamespace(namespace);
byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)),
buildQuery("missing." + namespace, (short) 1));
assertEquals(3, ByteBuffer.wrap(response).getShort(2) & 0x000F);
}
private String privateDnsNamespace(String name) {
return cloudMapService.createPrivateDnsNamespace(name, "vpc-dns", null, null,
Map.of(), REGION).getTargets().get("NAMESPACE");
}
private static String uniqueNamespace() {
return "dnspacket" + UUID.randomUUID().toString().substring(0, 8) + ".internal";
}
private byte[] query(EmbeddedDnsServer dns, byte[] request) throws Exception {
DatagramSocket server = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false));
DatagramSocket client = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false));
try {
server.listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
server.handler(packet -> dns.handleQuery(vertx, server, packet.data().getBytes(),
packet.sender().host(), packet.sender().port(), "127.0.0.1"));
client.listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
CompletableFuture<byte[]> received = new CompletableFuture<>();
client.handler(packet -> received.complete(packet.data().getBytes()));
client.send(Buffer.buffer(request), server.localAddress().port(), "127.0.0.1")
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
return received.get(5, TimeUnit.SECONDS);
} finally {
server.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
client.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
}
}
private static byte[] buildQuery(String name, short type) {
String[] labels = name.split("\\.");
int nameLength = 1;
for (String label : labels) {
nameLength += label.length() + 1;
}
ByteBuffer query = ByteBuffer.allocate(12 + nameLength + 4);
query.putShort((short) 0x1234);
query.putShort((short) 0x0100);
query.putShort((short) 1);
query.putShort((short) 0);
query.putShort((short) 0);
query.putShort((short) 0);
for (String label : labels) {
byte[] bytes = label.getBytes(StandardCharsets.US_ASCII);
query.put((byte) bytes.length);
query.put(bytes);
}
query.put((byte) 0);
query.putShort(type);
query.putShort((short) 1);
return query.array();
}
}
@@ -0,0 +1,53 @@
package io.github.hectorvent.floci.core.common.dns;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class DnsAnswerTest {
@Test
void negativeAnswersCarryNoAddresses() {
assertTrue(DnsAnswer.nxDomain().isEmpty());
assertFalse(DnsAnswer.nxDomain().nameExists());
assertTrue(DnsAnswer.noData().isEmpty());
assertTrue(DnsAnswer.noData().nameExists());
}
@Test
void recordsMarkTheNameAsExisting() {
DnsAnswer answer = DnsAnswer.records(List.of("10.0.0.1"), 15);
assertFalse(answer.isEmpty());
assertTrue(answer.nameExists());
assertEquals(15, answer.ttlSeconds());
}
@Test
void keepsATtlInsideTheRangeAnARecordCanCarry() {
assertEquals(0, DnsAnswer.records(List.of("10.0.0.1"), 0).ttlSeconds());
assertEquals(Integer.MAX_VALUE,
DnsAnswer.records(List.of("10.0.0.1"), Integer.MAX_VALUE).ttlSeconds());
}
@Test
void rejectsATtlNoResolverCouldActOn() {
assertThrows(IllegalArgumentException.class, () -> DnsAnswer.records(List.of("10.0.0.1"), -1));
}
@Test
void doesNotShareTheCallersList() {
List<String> addresses = new ArrayList<>(List.of("10.0.0.1"));
DnsAnswer answer = DnsAnswer.records(addresses, 15);
addresses.add("10.0.0.2");
assertEquals(List.of("10.0.0.1"), answer.addresses());
assertThrows(UnsupportedOperationException.class, () -> answer.addresses().add("10.0.0.3"));
}
}
@@ -141,8 +141,8 @@ class EmbeddedDnsServerTest {
EmbeddedDnsServer withSource = new EmbeddedDnsServer(
List.of(), List.of(source("empty.sapphire.internal", List.of())));
assertEquals(Optional.of(List.of()),
withSource.resolveARecordWithOwnership("empty.sapphire.internal", "172.31.0.2"));
assertEquals(List.of(), withSource.resolveARecordWithOwnership(
"empty.sapphire.internal", "172.31.0.2").orElseThrow().addresses());
}
@Test
@@ -179,7 +179,42 @@ class EmbeddedDnsServerTest {
}
private static DnsRecordSource source(String owned, List<String> addresses) {
return name -> owned.equals(name) ? Optional.of(addresses) : Optional.empty();
return source(owned, addresses, DnsAnswer.DEFAULT_TTL_SECONDS);
}
private static DnsRecordSource source(String owned, List<String> addresses, int ttlSeconds) {
return name -> owned.equals(name)
? Optional.of(DnsAnswer.records(addresses, ttlSeconds)) : Optional.empty();
}
private static DnsAnswer answer(String... addresses) {
return DnsAnswer.records(List.of(addresses), DnsAnswer.DEFAULT_TTL_SECONDS);
}
@Test
void buildAResponse_usesTheDefaultTtlForFlociNames() {
DnsAnswer answer = dns.resolveARecordWithOwnership(
"bucket.localhost.floci.io", "172.31.0.2").orElseThrow();
byte[] query = buildQuery("bucket.localhost.floci.io", (short) 10);
byte[] response = dns.buildAResponse(query, (short) 10, 12, query.length, answer);
assertEquals(DnsAnswer.DEFAULT_TTL_SECONDS,
ByteBuffer.wrap(response).getInt(query.length + 6));
}
@Test
void buildAResponse_writesTheAnswerTtlOnEveryRecord() {
EmbeddedDnsServer withSource = new EmbeddedDnsServer(List.of(),
List.of(source("api.sapphire.internal", List.of("172.31.0.6", "172.31.0.7"), 15)));
DnsAnswer answer = withSource.resolveARecordWithOwnership(
"api.sapphire.internal", "172.31.0.2").orElseThrow();
byte[] query = buildQuery("api.sapphire.internal", (short) 9);
byte[] response = dns.buildAResponse(query, (short) 9, 12, query.length, answer);
int firstTtl = 12 + (query.length - 12) + 6;
ByteBuffer buffer = ByteBuffer.wrap(response);
assertEquals(15, buffer.getInt(firstTtl));
assertEquals(15, buffer.getInt(firstTtl + 16));
}
// ── matchesSuffix — built-in emulator domains ─────────────────────────────
@@ -267,7 +302,7 @@ class EmbeddedDnsServerTest {
@Test
void buildAResponse_hasCorrectTransactionId() {
byte[] query = buildQuery("my-bucket.localhost.floci.io", (short) 0x1234);
byte[] response = dns.buildAResponse(query, (short) 0x1234, 12, query.length, List.of("172.19.0.2"));
byte[] response = dns.buildAResponse(query, (short) 0x1234, 12, query.length, answer("172.19.0.2"));
short txId = ByteBuffer.wrap(response).getShort(0);
assertEquals((short) 0x1234, txId);
}
@@ -275,7 +310,7 @@ class EmbeddedDnsServerTest {
@Test
void buildAResponse_flagsIndicateResponse() {
byte[] query = buildQuery("bucket.localhost.floci.io", (short) 1);
byte[] response = dns.buildAResponse(query, (short) 1, 12, query.length, List.of("10.0.0.1"));
byte[] response = dns.buildAResponse(query, (short) 1, 12, query.length, answer("10.0.0.1"));
short flags = ByteBuffer.wrap(response).getShort(2);
assertTrue((flags & 0x8000) != 0, "QR bit must be set");
}
@@ -284,7 +319,7 @@ class EmbeddedDnsServerTest {
void buildAResponse_answerCountMatchesTheAddressCount() {
byte[] query = buildQuery("api.sapphire.internal", (short) 9);
byte[] response = dns.buildAResponse(query, (short) 9, 12, query.length,
List.of("172.31.0.6", "172.31.0.7"));
answer("172.31.0.6", "172.31.0.7"));
int questionLength = query.length - 12;
ByteBuffer resp = ByteBuffer.wrap(response);
@@ -301,7 +336,7 @@ class EmbeddedDnsServerTest {
@Test
void buildAResponse_answerCountIsOne() {
byte[] query = buildQuery("bucket.localhost.floci.io", (short) 2);
byte[] response = dns.buildAResponse(query, (short) 2, 12, query.length, List.of("10.0.0.1"));
byte[] response = dns.buildAResponse(query, (short) 2, 12, query.length, answer("10.0.0.1"));
short ancount = ByteBuffer.wrap(response).getShort(6);
assertEquals(1, ancount);
}
@@ -309,7 +344,7 @@ class EmbeddedDnsServerTest {
@Test
void buildAResponse_ipAddressIsCorrect() {
byte[] query = buildQuery("bucket.localhost.floci.io", (short) 3);
byte[] response = dns.buildAResponse(query, (short) 3, 12, query.length, List.of("172.19.0.42"));
byte[] response = dns.buildAResponse(query, (short) 3, 12, query.length, answer("172.19.0.42"));
// IP starts at offset: 12 (header) + questionLength + 2+2+2+4+2 = questionLength + 24
int questionLength = query.length - 12;
ByteBuffer resp = ByteBuffer.wrap(response);
@@ -1,5 +1,7 @@
package io.github.hectorvent.floci.services.cloudmap;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.dns.DnsAnswer;
import io.github.hectorvent.floci.services.cloudmap.model.Operation;
import io.github.hectorvent.floci.services.cloudmap.model.Service;
import io.quarkus.test.junit.QuarkusTest;
@@ -7,11 +9,14 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* Cloud Map's control plane always accepted namespaces, services and instances, but nothing
@@ -69,6 +74,27 @@ class CloudMapDnsResolutionTest {
cloudMapService.resolveDnsName("VALKEY." + namespace.toUpperCase() + "."));
}
@Test
void dnsNamespaceRejectsServiceNamesThatDifferOnlyByCase() {
String namespaceId = privateDnsNamespace(uniqueNamespace());
createService(namespaceId, "Api", dnsConfig("{\"Type\":\"A\",\"TTL\":15}"));
AwsException error = assertThrows(AwsException.class, () -> createService(
namespaceId, "api", dnsConfig("{\"Type\":\"A\",\"TTL\":300}")));
assertEquals("ServiceAlreadyExists", error.getErrorCode());
}
@Test
void httpNamespaceAllowsServiceNamesThatDifferOnlyByCase() {
String namespaceId = cloudMapService.createHttpNamespace(uniqueNamespace(), null, null,
Map.of(), REGION).getTargets().get("NAMESPACE");
createService(namespaceId, "Api");
createService(namespaceId, "api");
assertEquals(2, cloudMapService.listServices(REGION, namespaceId).size());
}
@Test
void resolvesAPublicDnsNamespaceToo() {
String namespace = uniqueNamespace();
@@ -109,7 +135,7 @@ class CloudMapDnsResolutionTest {
createService(privateDnsNamespace(namespace), "empty");
assertTrue(cloudMapService.resolveDnsName("empty." + namespace).isEmpty());
assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned("empty." + namespace).orElseThrow());
assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned("empty." + namespace).orElseThrow().addresses());
}
@Test
@@ -127,7 +153,7 @@ class CloudMapDnsResolutionTest {
registerInstance(service.getId(), "task-1", "172.31.0.6");
assertTrue(cloudMapService.resolveDnsName(namespace).isEmpty());
assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned(namespace).orElseThrow());
assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned(namespace).orElseThrow().addresses());
}
@Test
@@ -139,18 +165,162 @@ class CloudMapDnsResolutionTest {
Service parentService = createService(parentId, "nested");
registerInstance(parentService.getId(), "task-1", "172.31.0.6");
assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned(childName).orElseThrow());
assertEquals(List.of(), cloudMapService.resolveDnsNameIfOwned(childName).orElseThrow().addresses());
assertTrue(cloudMapService.resolveDnsName(childName).isEmpty());
}
// ── TTL ───────────────────────────────────────────────────────────────────
@Test
void answersWithTheTtlTheServicesARecordDeclares() {
String namespace = uniqueNamespace();
Service service = createService(privateDnsNamespace(namespace), "valkey",
dnsConfig("{\"Type\":\"A\",\"TTL\":15}"));
registerInstance(service.getId(), "task-1", "172.31.0.6");
assertEquals(15, cloudMapService.resolveDnsNameIfOwned("valkey." + namespace).orElseThrow().ttlSeconds());
}
@Test
void prefersTheARecordsTtlOverAnotherRecordTypes() {
String namespace = uniqueNamespace();
Service service = createService(privateDnsNamespace(namespace), "api",
dnsConfig("{\"Type\":\"AAAA\",\"TTL\":300}", "{\"Type\":\"A\",\"TTL\":15}"));
registerInstance(service.getId(), "task-1", "172.31.0.6");
assertEquals(15, cloudMapService.resolveDnsNameIfOwned("api." + namespace).orElseThrow().ttlSeconds());
}
@Test
void srvOnlyServiceDoesNotPublishAnARecord() {
// Cloud Map creates SRV records for the service name, not an A record there.
String namespace = uniqueNamespace();
Service service = createService(privateDnsNamespace(namespace), "srvonly",
dnsConfig("{\"Type\":\"SRV\",\"TTL\":300}"));
registerInstance(service.getId(), "task-1", "172.31.0.6");
assertTrue(cloudMapService.resolveDnsName("srvonly." + namespace).isEmpty());
DnsAnswer answer = cloudMapService.resolveDnsNameIfOwned("srvonly." + namespace).orElseThrow();
assertTrue(answer.isEmpty());
assertTrue(answer.nameExists());
}
@Test
void srvInstanceHostnamePublishesItsOwnIpv4Address() {
String namespace = uniqueNamespace();
Service service = createService(privateDnsNamespace(namespace), "backend",
dnsConfig("{\"Type\":\"SRV\",\"TTL\":300}"));
cloudMapService.registerInstance(service.getId(), "task.one", null,
Map.of("AWS_INSTANCE_IPV4", "172.31.0.6", "AWS_INSTANCE_PORT", "8080"), REGION);
cloudMapService.registerInstance(service.getId(), "task-two", null,
Map.of("AWS_INSTANCE_IPV4", "172.31.0.7", "AWS_INSTANCE_PORT", "8080"), REGION);
DnsAnswer answer = cloudMapService.resolveDnsNameIfOwned(
"TASK.ONE.BACKEND." + namespace.toUpperCase() + ".").orElseThrow();
assertEquals(List.of("172.31.0.6"), answer.addresses());
assertEquals(300, answer.ttlSeconds());
assertFalse(cloudMapService.resolveDnsNameIfOwned("missing.backend." + namespace)
.orElseThrow().nameExists());
cloudMapService.deregisterInstance(service.getId(), "task.one", REGION);
assertFalse(cloudMapService.resolveDnsNameIfOwned("task.one.backend." + namespace)
.orElseThrow().nameExists());
}
@Test
void resolvesNamesWithAnIRegardlessOfTheDefaultLocale() {
String namespace = uniqueNamespace();
String namespaceId = privateDnsNamespace(namespace);
Service srv = createService(namespaceId, "Inventory", dnsConfig("{\"Type\":\"SRV\",\"TTL\":300}"));
registerInstance(srv.getId(), "task", "172.31.0.6");
Service a = createService(namespaceId, "Billing");
registerInstance(a.getId(), "i-1", "172.31.0.7");
Locale previous = Locale.getDefault();
Locale.setDefault(Locale.forLanguageTag("tr-TR"));
try {
assertEquals(List.of("172.31.0.6"), cloudMapService.resolveDnsName("task.inventory." + namespace));
assertEquals(List.of("172.31.0.6"), cloudMapService.resolveDnsName("TASK.INVENTORY." + namespace));
assertEquals(List.of("172.31.0.7"), cloudMapService.resolveDnsName("BILLING." + namespace));
} finally {
Locale.setDefault(previous);
}
}
@Test
void fallsBackToTheDefaultTtlWhenTheServiceHasNoDnsConfig() {
String namespace = uniqueNamespace();
Service service = createService(privateDnsNamespace(namespace), "plain");
registerInstance(service.getId(), "task-1", "172.31.0.6");
assertEquals(DnsAnswer.DEFAULT_TTL_SECONDS,
cloudMapService.resolveDnsNameIfOwned("plain." + namespace).orElseThrow().ttlSeconds());
}
@Test
void rejectsTtlValuesOutsideTheAwsRange() {
String namespaceId = privateDnsNamespace(uniqueNamespace());
for (String ttl : List.of("-1", "2147483648", "1.5", "\"15\"")) {
AwsException error = assertThrows(AwsException.class, () -> createService(
namespaceId, "invalid", dnsConfig("{\"Type\":\"A\",\"TTL\":" + ttl + "}")));
assertEquals("InvalidInput", error.getErrorCode());
}
}
@Test
void rejectsDnsRecordsWithoutATtl() {
String namespaceId = privateDnsNamespace(uniqueNamespace());
AwsException error = assertThrows(AwsException.class, () -> createService(
namespaceId, "missing", dnsConfig("{\"Type\":\"A\"}")));
assertEquals("InvalidInput", error.getErrorCode());
}
@Test
void acceptsATtlOfZero() {
// Cloud Map's range starts at 0, and a resolver told 0 must not cache the answer at all.
String namespace = uniqueNamespace();
Service service = createService(privateDnsNamespace(namespace), "nocache",
dnsConfig("{\"Type\":\"A\",\"TTL\":0}"));
registerInstance(service.getId(), "task-1", "172.31.0.6");
assertEquals(0, cloudMapService.resolveDnsNameIfOwned("nocache." + namespace).orElseThrow().ttlSeconds());
}
@Test
void acceptsTheMaximumAwsTtl() {
String namespace = uniqueNamespace();
Service service = createService(privateDnsNamespace(namespace), "longcache",
dnsConfig("{\"Type\":\"A\",\"TTL\":2147483647}"));
registerInstance(service.getId(), "task-1", "172.31.0.6");
assertEquals(Integer.MAX_VALUE,
cloudMapService.resolveDnsNameIfOwned("longcache." + namespace).orElseThrow().ttlSeconds());
}
@Test
void rejectsMalformedDnsConfig() {
String namespaceId = privateDnsNamespace(uniqueNamespace());
AwsException error = assertThrows(AwsException.class,
() -> createService(namespaceId, "malformed", "{not json"));
assertEquals("InvalidInput", error.getErrorCode());
}
private static String dnsConfig(String... records) {
return "{\"DnsRecords\":[" + String.join(",", records) + "]}";
}
private String privateDnsNamespace(String name) {
return cloudMapService.createPrivateDnsNamespace(name, "vpc-dns", null, null, Map.of(), REGION)
.getTargets().get("NAMESPACE");
}
private Service createService(String namespaceId, String serviceName) {
return createService(namespaceId, serviceName, null);
}
private Service createService(String namespaceId, String serviceName, String dnsConfig) {
return cloudMapService.createService(serviceName, namespaceId, null, null,
null, null, null, null, Map.of(), REGION);
dnsConfig, null, null, null, Map.of(), REGION);
}
private void registerInstance(String serviceId, String instanceId, String ipv4) {
@@ -70,6 +70,10 @@ class CloudMapIntegrationTest {
@Test
@Order(3)
void createService() {
call("CreateService", "{\"Name\":\"invalid-ttl\",\"NamespaceId\":\"" + namespaceId
+ "\",\"DnsConfig\":{\"DnsRecords\":[{\"Type\":\"A\",\"TTL\":2147483648}]}}")
.then().statusCode(400);
serviceId = call("CreateService",
"{\"Name\":\"floci-cm-svc\",\"NamespaceId\":\"" + namespaceId + "\"}")
.then().statusCode(200)
@@ -1,5 +1,6 @@
package io.github.hectorvent.floci.services.route53;
import io.github.hectorvent.floci.core.common.dns.DnsAnswer;
import io.github.hectorvent.floci.core.common.dns.DnsLookupHelper;
import io.github.hectorvent.floci.services.route53.model.AliasTarget;
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
@@ -62,9 +63,46 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "api." + zone, "A", "10.0.1.100");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("api." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("api." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.1.100"), result.get());
assertEquals(List.of("10.0.1.100"), result.get().addresses());
}
@Test
void answersWithTheRecordSetTtl() {
String zone = uniqueZone();
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "api." + zone, "A", "10.0.1.100", 42L);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("api." + zone);
assertTrue(result.isPresent());
assertEquals(42, result.get().ttlSeconds());
}
@Test
void cnameChainAnswersWithTheShortestTtlInTheChain() {
String zone = uniqueZone();
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "api." + zone, "A", "10.0.3.50", 600L);
addRecord(zoneId, "short." + zone, "CNAME", "api." + zone + ".", 30L);
addRecord(zoneId, "long." + zone, "CNAME", "short." + zone + ".", 900L);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("long." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.3.50"), result.get().addresses());
assertEquals(30, result.get().ttlSeconds());
}
@Test
void aliasAnswersWithTheTargetTtl() {
String zone = uniqueZone();
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "target." + zone, "A", "10.0.4.99", 120L);
addAlias(zoneId, "alias." + zone, "A", "target." + zone + ".");
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("alias." + zone);
assertTrue(result.isPresent());
assertEquals(120, result.get().ttlSeconds());
}
@Test
@@ -73,11 +111,11 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addRecords(zoneId, "api." + zone, "A", List.of("10.0.1.101", "10.0.1.102"));
Optional<List<String>> result = dnsRecordSource.resolveIpv4("api." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("api." + zone);
assertTrue(result.isPresent());
assertEquals(2, result.get().size());
assertTrue(result.get().contains("10.0.1.101"));
assertTrue(result.get().contains("10.0.1.102"));
assertEquals(2, result.get().addresses().size());
assertTrue(result.get().addresses().contains("10.0.1.101"));
assertTrue(result.get().addresses().contains("10.0.1.102"));
}
@Test
@@ -90,9 +128,9 @@ class Route53DnsResolutionTest {
}
addRecords(zoneId, "fleet." + zone, "A", ips);
Optional<List<String>> result = dnsRecordSource.resolveIpv4("fleet." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("fleet." + zone);
assertTrue(result.isPresent());
assertEquals(8, result.get().size());
assertEquals(8, result.get().addresses().size());
}
@Test
@@ -101,9 +139,9 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "api." + zone, "A", "10.0.1.200");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("API." + zone.toUpperCase() + ".");
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("API." + zone.toUpperCase() + ".");
assertTrue(result.isPresent());
assertEquals(List.of("10.0.1.200"), result.get());
assertEquals(List.of("10.0.1.200"), result.get().addresses());
}
@Test
@@ -114,7 +152,7 @@ class Route53DnsResolutionTest {
createdZoneIds.add(zoneId);
addRecord(zoneId, "api." + zone, "A", "1.2.3.4");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("api." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("api." + zone);
assertTrue(result.isEmpty());
}
@@ -131,9 +169,9 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "*." + zone, "A", "10.0.2.1");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("app." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("app." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.2.1"), result.get());
assertEquals(List.of("10.0.2.1"), result.get().addresses());
}
@Test
@@ -144,9 +182,42 @@ class Route53DnsResolutionTest {
addRecord(zoneId, "b." + zone, "TXT", "\"text-record\"");
// Wildcard should not match a.b.zone because b.zone exists
Optional<List<String>> result = dnsRecordSource.resolveIpv4("a.b." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("a.b." + zone);
assertTrue(result.isPresent());
assertEquals(List.of(), result.get());
assertEquals(DnsAnswer.nxDomain(), result.get());
}
@Test
void wildcardDoesNotMatchAnEmptyNonTerminal() {
String zone = uniqueZone();
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "*." + zone, "A", "10.0.2.1");
addRecord(zoneId, "api.team." + zone, "A", "10.0.2.2");
Optional<DnsAnswer> team = dnsRecordSource.resolveIpv4("team." + zone);
assertTrue(team.isPresent());
assertTrue(team.get().isEmpty());
assertTrue(team.get().nameExists());
Optional<DnsAnswer> web = dnsRecordSource.resolveIpv4("web.team." + zone);
assertTrue(web.isPresent());
assertEquals(DnsAnswer.nxDomain(), web.get());
Optional<DnsAnswer> other = dnsRecordSource.resolveIpv4("other." + zone);
assertTrue(other.isPresent());
assertEquals(List.of("10.0.2.1"), other.get().addresses());
}
@Test
void closerWildcardTakesPrecedenceOverParentWildcard() {
String zone = uniqueZone();
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "*." + zone, "A", "10.0.2.1");
addRecord(zoneId, "*.team." + zone, "A", "10.0.2.3");
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("web.team." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.2.3"), result.get().addresses());
}
@Test
@@ -156,9 +227,9 @@ class Route53DnsResolutionTest {
addRecord(zoneId, "api." + zone, "A", "10.0.3.50");
addRecord(zoneId, "service." + zone, "CNAME", "api." + zone + ".");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("service." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("service." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.3.50"), result.get());
assertEquals(List.of("10.0.3.50"), result.get().addresses());
}
@Test
@@ -168,9 +239,9 @@ class Route53DnsResolutionTest {
addRecord(zoneId, "cname1." + zone, "CNAME", "cname2." + zone);
addRecord(zoneId, "cname2." + zone, "CNAME", "cname1." + zone);
Optional<List<String>> result = dnsRecordSource.resolveIpv4("cname1." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("cname1." + zone);
assertTrue(result.isPresent());
assertEquals(List.of(), result.get());
assertEquals(List.of(), result.get().addresses());
}
@Test
@@ -179,9 +250,9 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "ec2host." + zone, "CNAME", "ip-10-0-5-88.ec2.internal.");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("ec2host." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("ec2host." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.5.88"), result.get());
assertEquals(List.of("10.0.5.88"), result.get().addresses());
}
@Test
@@ -193,9 +264,9 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "ext." + zone, "CNAME", "external.example.com.");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("ext." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("ext." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("93.184.216.34"), result.get());
assertEquals(List.of("93.184.216.34"), result.get().addresses());
}
@Test
@@ -205,30 +276,58 @@ class Route53DnsResolutionTest {
addRecord(zoneId, "target." + zone, "A", "10.0.4.99");
addAlias(zoneId, "alias." + zone, "A", "target." + zone + ".");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("alias." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("alias." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.4.99"), result.get());
assertEquals(List.of("10.0.4.99"), result.get().addresses());
}
@Test
void returnsEmptyListForNonExistentNameInPrivateZone() {
void answersNxDomainForNonExistentNameInPrivateZone() {
String zone = uniqueZone();
createPrivateZone(zone);
Optional<List<String>> result = dnsRecordSource.resolveIpv4("nonexistent." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("nonexistent." + zone);
assertTrue(result.isPresent());
assertEquals(List.of(), result.get());
assertEquals(DnsAnswer.nxDomain(), result.get());
}
@Test
void returnsEmptyListForExistingNameWithoutARecord() {
void answersNoDataForEmptyNonTerminalName() {
String zone = uniqueZone();
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "api.team." + zone, "A", "10.0.6.1");
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("team." + zone);
assertTrue(result.isPresent());
assertTrue(result.get().isEmpty());
assertTrue(result.get().nameExists());
}
@Test
void cnameToExternalHostnameCapsTheTtlForTheUnseenTarget() {
Mockito.when(dnsLookupHelper.resolveIpv4("external-ttl.example.com"))
.thenReturn(List.of("93.184.216.35"));
String zone = uniqueZone();
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "ext." + zone, "CNAME", "external-ttl.example.com.", 3600L);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("ext." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("93.184.216.35"), result.get().addresses());
assertEquals(DnsAnswer.DEFAULT_TTL_SECONDS, result.get().ttlSeconds());
}
@Test
void answersNoDataForExistingNameWithoutARecord() {
String zone = uniqueZone();
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "txtonly." + zone, "TXT", "\"only text here\"");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("txtonly." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("txtonly." + zone);
assertTrue(result.isPresent());
assertEquals(List.of(), result.get());
assertTrue(result.get().isEmpty());
assertTrue(result.get().nameExists());
}
@Test
@@ -241,9 +340,9 @@ class Route53DnsResolutionTest {
addRecord(parentId, "api.sub." + parentZone, "A", "10.0.10.1");
addRecord(childId, "api." + childZone, "A", "10.0.20.1");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("api.sub." + parentZone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("api.sub." + parentZone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.20.1"), result.get());
assertEquals(List.of("10.0.20.1"), result.get().addresses());
}
@Test
@@ -252,10 +351,10 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "floci-cname." + zone, "CNAME", "s3.localhost.localstack.cloud");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("floci-cname." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("floci-cname." + zone);
assertTrue(result.isPresent());
String expectedIp = InetAddress.getLocalHost().getHostAddress();
assertEquals(List.of(expectedIp), result.get());
assertEquals(List.of(expectedIp), result.get().addresses());
}
@Test
@@ -264,10 +363,10 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addRecord(zoneId, "floci-cname2." + zone, "CNAME", "sqs.localhost.floci.io");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("floci-cname2." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("floci-cname2." + zone);
assertTrue(result.isPresent());
String expectedIp = InetAddress.getLocalHost().getHostAddress();
assertEquals(List.of(expectedIp), result.get());
assertEquals(List.of(expectedIp), result.get().addresses());
}
@Test
@@ -276,10 +375,10 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addAlias(zoneId, "floci-alias." + zone, "A", "s3.localhost.localstack.cloud");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("floci-alias." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("floci-alias." + zone);
assertTrue(result.isPresent());
String expectedIp = InetAddress.getLocalHost().getHostAddress();
assertEquals(List.of(expectedIp), result.get());
assertEquals(List.of(expectedIp), result.get().addresses());
}
@Test
@@ -291,11 +390,11 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addAlias(zoneId, "bare-alias." + zone, "A", "s3.localstack.cloud");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("bare-alias." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("bare-alias." + zone);
assertTrue(result.isPresent());
String localIp = InetAddress.getLocalHost().getHostAddress();
assertFalse(result.get().contains(localIp));
assertEquals(List.of("192.0.2.1"), result.get());
assertFalse(result.get().addresses().contains(localIp));
assertEquals(List.of("192.0.2.1"), result.get().addresses());
}
@Test
@@ -304,9 +403,9 @@ class Route53DnsResolutionTest {
String zoneId = createPrivateZone(zone);
addAlias(zoneId, "ec2-alias." + zone, "A", "ip-10-0-0-5.ec2.internal");
Optional<List<String>> result = dnsRecordSource.resolveIpv4("ec2-alias." + zone);
Optional<DnsAnswer> result = dnsRecordSource.resolveIpv4("ec2-alias." + zone);
assertTrue(result.isPresent());
assertEquals(List.of("10.0.0.5"), result.get());
assertEquals(List.of("10.0.0.5"), result.get().addresses());
}
private String createPrivateZone(String name) {
@@ -321,10 +420,14 @@ class Route53DnsResolutionTest {
}
private void addRecord(String zoneId, String name, String type, String value) {
addRecord(zoneId, name, type, value, 300L);
}
private void addRecord(String zoneId, String name, String type, String value, long ttl) {
ResourceRecordSet rrs = new ResourceRecordSet();
rrs.setName(name);
rrs.setType(type);
rrs.setTtl(300L);
rrs.setTtl(ttl);
rrs.setRecords(List.of(new ResourceRecord(value)));
route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", rrs)), null);
}