Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudmap): answer typed DNS records and honor routing policy (#4534)

Aniket Shuklac7492ce0f42e
diff --git a/compatibility-tests/sdk-test-python/tests/test_cloudmap_dns_configuration.py b/compatibility-tests/sdk-test-python/tests/test_cloudmap_dns_configuration.py
new file mode 100644
index 0000000000..87bb61f44e
--- /dev/null
+++ b/compatibility-tests/sdk-test-python/tests/test_cloudmap_dns_configuration.py
@@ -0,0 +1,89 @@
+"""Cloud Map DNS configuration and instance attributes through the AWS SDK."""
+
+import time
+import uuid
+
+import boto3
+import pytest
+from botocore.exceptions import ClientError
+
+
+def operation_target(client, operation_id):
+ for _ in range(20):
+ operation = client.get_operation(OperationId=operation_id)["Operation"]
+ if operation["Status"] == "SUCCESS":
+ return operation.get("Targets", {})
+ assert operation["Status"] != "FAIL", operation
+ time.sleep(0.1)
+ pytest.fail("Cloud Map operation did not complete")
+
+
[email protected]("record_type,attributes", [
+ ("A", {"AWS_INSTANCE_IPV4": "192.0.2.1"}),
+ ("AAAA", {"AWS_INSTANCE_IPV6": "2001:db8::1"}),
+ ("CNAME", {"AWS_INSTANCE_CNAME": "backend.example.com"}),
+ ("SRV", {"AWS_INSTANCE_PORT": "8080", "AWS_INSTANCE_IPV6": "2001:db8::2"}),
+])
+def test_dns_configuration_and_instance_attributes_round_trip(aws_config, record_type, attributes):
+ client = boto3.client("servicediscovery", **aws_config)
+ namespace_id = None
+ service_id = None
+ registered = False
+ try:
+ created = client.create_private_dns_namespace(Name=f"dns-{uuid.uuid4().hex}.internal", Vpc="vpc-dns")
+ namespace_id = operation_target(client, created["OperationId"])["NAMESPACE"]
+ configuration = {"RoutingPolicy": "WEIGHTED", "DnsRecords": [{"Type": record_type, "TTL": 45}]}
+ service = client.create_service(Name="backend", NamespaceId=namespace_id,
+ DnsConfig=configuration)["Service"]
+ service_id = service["Id"]
+ stored = client.get_service(Id=service_id)["Service"]["DnsConfig"]
+ assert stored["RoutingPolicy"] == "WEIGHTED"
+ assert stored["DnsRecords"] == configuration["DnsRecords"]
+ result = client.register_instance(ServiceId=service_id, InstanceId="task-1", Attributes=attributes)
+ registered = True
+ operation_target(client, result["OperationId"])
+ assert client.get_instance(ServiceId=service_id, InstanceId="task-1")["Instance"]["Attributes"] == attributes
+ finally:
+ if registered:
+ result = client.deregister_instance(ServiceId=service_id, InstanceId="task-1")
+ operation_target(client, result["OperationId"])
+ if service_id:
+ client.delete_service(Id=service_id)
+ if namespace_id:
+ client.delete_namespace(Id=namespace_id)
+ client.close()
+
+
[email protected]("identifier_length", [63, 64])
+def test_srv_target_label_limit(aws_config, identifier_length):
+ client = boto3.client("servicediscovery", **aws_config)
+ namespace_id = None
+ service_id = None
+ registered = False
+ instance_id = "a" * identifier_length
+ try:
+ created = client.create_private_dns_namespace(Name=f"srv-{uuid.uuid4().hex}.internal", Vpc="vpc-dns")
+ namespace_id = operation_target(client, created["OperationId"])["NAMESPACE"]
+ service_id = client.create_service(Name="backend", NamespaceId=namespace_id, DnsConfig={
+ "RoutingPolicy": "MULTIVALUE", "DnsRecords": [{"Type": "SRV", "TTL": 45}],
+ })["Service"]["Id"]
+ arguments = {"ServiceId": service_id, "InstanceId": instance_id,
+ "Attributes": {"AWS_INSTANCE_PORT": "8080", "AWS_INSTANCE_IPV4": "192.0.2.1"}}
+ if identifier_length == 64:
+ with pytest.raises(ClientError) as error:
+ client.register_instance(**arguments)
+ assert error.value.response["Error"]["Code"] == "InvalidInput"
+ assert client.list_instances(ServiceId=service_id)["Instances"] == []
+ else:
+ result = client.register_instance(**arguments)
+ registered = True
+ operation_target(client, result["OperationId"])
+ finally:
+ if registered:
+ result = client.deregister_instance(ServiceId=service_id, InstanceId=instance_id)
+ operation_target(client, result["OperationId"])
+ if service_id:
+ client.delete_service(Id=service_id)
+ if namespace_id:
+ client.delete_namespace(Id=namespace_id)
+ client.close()
diff --git a/docs/services/cloudmap.md b/docs/services/cloudmap.md
index 0ca68b8925..a0996b3dbb 100644
--- a/docs/services/cloudmap.md
+++ b/docs/services/cloudmap.md
@@ -28,26 +28,41 @@ as its resolver reaches its peers by name. Instances registered directly through
Which instances answer follows Route 53: the healthy ones while any instance is
healthy, and all of them when none is, so a service whose instances have all gone
-unhealthy still resolves rather than disappearing from DNS. At most eight records
-go back either way, as Route 53 answers a service discovery query.
+unhealthy still resolves rather than disappearing from DNS. `MULTIVALUE` returns up to
+eight instances; `WEIGHTED` returns one randomly selected instance, with equal weights.
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
+A and AAAA records use `AWS_INSTANCE_IPV4` and `AWS_INSTANCE_IPV6`, respectively,
+and carry the TTL of the corresponding `DnsConfig.DnsRecords` entry. CNAME services
+answer with `AWS_INSTANCE_CNAME`, including when queried for A or AAAA. SRV queries
+return priority 1, weight 1, `AWS_INSTANCE_PORT`, and
+`<InstanceId>.<service>.<namespace>`. The SRV target also answers A and/or AAAA
+queries when those address attributes are registered, using the SRV TTL. The SRV
+service name itself has no address 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; SRV queries are not yet answered. The embedded DNS server only runs
+SRV registrations must produce an encodable DNS target: ASCII labels of at most
+63 bytes and a full name of at most 253 characters. Floci returns `InvalidInput`
+before storing an unencodable target, rather than accepting a registration that
+cannot resolve. The API's general 64-character instance identifier limit is not
+a guarantee that an identifier can be used as a single DNS label; non-SRV
+registrations are unaffected. This early validation is an emulator behavior,
+not a verified claim about AWS's error timing. Older mixed A/CNAME configurations
+still resolve their explicitly configured A records.
+
+UDP replies respect the legacy 512-byte limit or the client's EDNS payload size,
+capped at 4096 bytes. Oversized answers are truncated at whole-record boundaries
+and carry the DNS truncation flag. The embedded server remains UDP-only; TCP
+retry is not implemented.
+
+Two limits are worth knowing. `HTTP` namespaces do not resolve, matching AWS,
+where they are reachable only through `DiscoverInstances`. 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.
@@ -150,7 +165,6 @@ print(found["Instances"])
## Out of Scope
- Route 53 hosted zone / record set creation.
-- 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.
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsAnswer.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsAnswer.java
index c8eea59485..ddaddf5c91 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsAnswer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsAnswer.java
@@ -3,14 +3,14 @@ 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
+ * What a {@link DnsRecordSource} answers for a name inside a zone it owns: typed records with the
+ * TTL the zone publishes for them, an existing name without those 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) {
+public record DnsAnswer(List<DnsRecord> records, 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;
@@ -24,15 +24,26 @@ public record DnsAnswer(List<String> addresses, int ttlSeconds, boolean nameExis
if (ttlSeconds < 0) {
throw new IllegalArgumentException("DNS TTL must not be negative: " + ttlSeconds);
}
- addresses = List.copyOf(addresses);
+ records = List.copyOf(records);
}
/** 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);
+ return typedRecords(addresses.stream().map(address -> (DnsRecord) new DnsRecord.Address(1, address)).toList(),
+ ttlSeconds);
}
- /** An existing name without A records: NOERROR with no answers. */
+ public static DnsAnswer typedRecords(List<DnsRecord> records, int ttlSeconds) {
+ return new DnsAnswer(records, ttlSeconds, true);
+ }
+
+ /** IPv4 projection retained for callers that explicitly resolve A records. */
+ public List<String> addresses() {
+ return records.stream().filter(record -> record instanceof DnsRecord.Address && record.type() == 1)
+ .map(record -> ((DnsRecord.Address) record).value()).toList();
+ }
+
+ /** An existing name without records of the requested type: NOERROR with no answers. */
public static DnsAnswer noData() {
return NO_DATA;
}
@@ -43,6 +54,6 @@ public record DnsAnswer(List<String> addresses, int ttlSeconds, boolean nameExis
}
public boolean isEmpty() {
- return addresses.isEmpty();
+ return records.isEmpty();
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecord.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecord.java
new file mode 100644
index 0000000000..cb4b743059
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecord.java
@@ -0,0 +1,73 @@
+package io.github.hectorvent.floci.core.common.dns;
+
+import io.netty.util.NetUtil;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+
+/** A DNS resource record's wire type and uncompressed rdata. */
+public sealed interface DnsRecord {
+ int type();
+ byte[] data();
+
+ record Address(int type, String value) implements DnsRecord {
+ public Address {
+ if (!(type == 1 && NetUtil.isValidIpV4Address(value))
+ && !(type == 28 && NetUtil.isValidIpV6Address(value))) {
+ throw new IllegalArgumentException("Invalid DNS address: " + value);
+ }
+ }
+
+ @Override
+ public byte[] data() {
+ return NetUtil.createByteArrayFromIpAddressString(value);
+ }
+ }
+
+ record Cname(String target) implements DnsRecord {
+ @Override
+ public int type() {
+ return 5;
+ }
+
+ @Override
+ public byte[] data() {
+ return encodeName(target);
+ }
+ }
+
+ record Srv(int port, String target) implements DnsRecord {
+ public Srv {
+ if (port < 0 || port > 65535) {
+ throw new IllegalArgumentException("Invalid SRV port: " + port);
+ }
+ }
+
+ @Override
+ public int type() {
+ return 33;
+ }
+
+ @Override
+ public byte[] data() {
+ byte[] name = encodeName(target);
+ return ByteBuffer.allocate(6 + name.length).putShort((short) 1).putShort((short) 1)
+ .putShort((short) port).put(name).array();
+ }
+ }
+
+ static byte[] encodeName(String name) {
+ String normalized = name.endsWith(".") ? name.substring(0, name.length() - 1) : name;
+ if (normalized.length() > 253 || normalized.isEmpty()) {
+ throw new IllegalArgumentException("Invalid DNS name: " + name);
+ }
+ ByteBuffer buffer = ByteBuffer.allocate(normalized.length() + 2);
+ for (String label : normalized.split("\\.", -1)) {
+ if (label.isEmpty() || label.length() > 63 || !StandardCharsets.US_ASCII.newEncoder().canEncode(label)) {
+ throw new IllegalArgumentException("Invalid DNS label: " + label);
+ }
+ buffer.put((byte) label.length()).put(label.getBytes(StandardCharsets.US_ASCII));
+ }
+ return buffer.put((byte) 0).array();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecordSource.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecordSource.java
index 4c864b2ae5..efd28fa759 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecordSource.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/DnsRecordSource.java
@@ -18,4 +18,10 @@ public interface DnsRecordSource {
* source does not own the name. The name arrives without a trailing dot and in the case the client sent.
*/
Optional<DnsAnswer> resolveIpv4(String name);
+
+ /** A source that only implements IPv4 still preserves name ownership for other query types. */
+ default Optional<DnsAnswer> resolve(String name, int type) {
+ return resolveIpv4(name).map(answer -> type == 1 ? answer
+ : answer.nameExists() ? DnsAnswer.noData() : DnsAnswer.nxDomain());
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
index 8fd5e6048c..3876862c5b 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
@@ -149,14 +149,14 @@ public class EmbeddedDnsServer {
buf.getShort(); // qclass
int questionEnd = buf.position();
- vertx.<Optional<DnsAnswer>>executeBlocking(() -> resolveARecordWithOwnership(qname, myIp), false)
+ vertx.<Optional<DnsAnswer>>executeBlocking(() -> resolveRecordWithOwnership(qname, myIp, qtype), false)
.onSuccess(answer -> {
if (answer.isEmpty()) {
forwardAsync(vertx, socket, data, senderHost, senderPort);
return;
}
DnsAnswer records = answer.orElseThrow();
- byte[] response = qtype == 1 && !records.isEmpty()
+ byte[] response = !records.isEmpty()
? buildAResponse(data, txId, questionOffset, questionEnd, records)
: buildEmptyResponse(data, txId, questionOffset, questionEnd,
records.nameExists() ? 0 : 3);
@@ -190,13 +190,19 @@ public class EmbeddedDnsServer {
}
Optional<DnsAnswer> resolveARecordWithOwnership(String name, String myIp) {
+ return resolveRecordWithOwnership(name, myIp, 1);
+ }
+
+ private Optional<DnsAnswer> resolveRecordWithOwnership(String name, String myIp, int type) {
if (matchesSuffix(name)) {
- return Optional.of(DnsAnswer.records(List.of(myIp), DnsAnswer.DEFAULT_TTL_SECONDS));
+ return Optional.of(type == 1 ? DnsAnswer.records(List.of(myIp), DnsAnswer.DEFAULT_TTL_SECONDS)
+ : DnsAnswer.noData());
}
Optional<String> ec2PrivateDnsName = resolveEc2PrivateDnsName(name);
return ec2PrivateDnsName
- .map(address -> DnsAnswer.records(List.of(address), DnsAnswer.DEFAULT_TTL_SECONDS))
- .map(Optional::of).orElseGet(() -> resolveFromRecordSources(name));
+ .map(address -> type == 1 ? DnsAnswer.records(List.of(address), DnsAnswer.DEFAULT_TTL_SECONDS)
+ : DnsAnswer.noData())
+ .map(Optional::of).orElseGet(() -> resolveFromRecordSources(name, type));
}
/**
@@ -204,13 +210,13 @@ 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<DnsAnswer> resolveFromRecordSources(String name) {
+ private Optional<DnsAnswer> resolveFromRecordSources(String name, int type) {
if (recordSources == null) {
return Optional.empty();
}
for (DnsRecordSource source : recordSources) {
try {
- Optional<DnsAnswer> answer = source.resolveIpv4(name);
+ Optional<DnsAnswer> answer = source.resolve(name, type);
if (answer != null && answer.isPresent()) {
return answer;
}
@@ -223,14 +229,16 @@ public class EmbeddedDnsServer {
}
byte[] buildEmptyResponse(byte[] query, short txId, int questionOffset, int questionEnd, int responseCode) {
- ByteBuffer response = ByteBuffer.allocate(12 + questionEnd - questionOffset);
+ UdpPayload payload = udpPayload(query, questionEnd);
+ ByteBuffer response = ByteBuffer.allocate(12 + questionEnd - questionOffset + (payload.edns() ? 11 : 0));
response.putShort(txId);
response.putShort((short) (0x8580 | responseCode));
response.putShort((short) 1);
response.putShort((short) 0);
response.putShort((short) 0);
- response.putShort((short) 0);
+ response.putShort((short) (payload.edns() ? 1 : 0));
response.put(query, questionOffset, questionEnd - questionOffset);
+ appendOpt(response, payload);
return response.array();
}
@@ -304,37 +312,82 @@ public class EmbeddedDnsServer {
}
byte[] buildAResponse(byte[] query, short txId, int questionOffset, int questionEnd, DnsAnswer answer) {
- List<String> ips = answer.addresses();
+ List<DnsRecord> records = answer.records();
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());
+ List<byte[]> data = records.stream().map(DnsRecord::data).toList();
+ UdpPayload payload = udpPayload(query, questionEnd);
+ int responseLength = 12 + questionLength + (payload.edns() ? 11 : 0);
+ int answerCount = 0;
+ for (byte[] recordData : data) {
+ if (responseLength + 12 + recordData.length > payload.size()) {
+ break;
+ }
+ responseLength += 12 + recordData.length;
+ answerCount++;
+ }
+ boolean truncated = answerCount < records.size();
+ ByteBuffer resp = ByteBuffer.allocate(responseLength);
// header
resp.putShort(txId);
- resp.putShort((short) 0x8180); // QR=1, AA=1, RD=1, RCODE=0
+ resp.putShort((short) (0x8180 | (truncated ? 0x0200 : 0))); // QR=1, RD=1, RCODE=0
resp.putShort((short) 1); // qdcount
- resp.putShort((short) ips.size()); // ancount
+ resp.putShort((short) answerCount); // ancount
resp.putShort((short) 0); // nscount
- resp.putShort((short) 0); // arcount
+ resp.putShort((short) (payload.edns() ? 1 : 0)); // arcount
// question (copied verbatim from query)
resp.put(query, questionOffset, questionLength);
- // answers. A name with several registered addresses gets one A record each, which is
- // what a Cloud Map service backed by more than one instance resolves to on AWS.
- for (String ip : ips) {
+ // Each answer carries its own type and rdata; a CNAME can answer an address query.
+ for (int i = 0; i < answerCount; i++) {
resp.putShort((short) 0xC00C); // name pointer to offset 12 (start of question name)
- resp.putShort((short) 1); // type A
+ resp.putShort((short) records.get(i).type());
resp.putShort((short) 1); // class IN
resp.putInt(answer.ttlSeconds());
- resp.putShort((short) 4); // rdlength
+ resp.putShort((short) data.get(i).length);
+ resp.put(data.get(i));
+ }
+ appendOpt(resp, payload);
+ return resp.array();
+ }
+
+ private record UdpPayload(int size, boolean edns) {}
- for (String octet : ip.split("\\.")) {
- resp.put((byte) Integer.parseInt(octet));
+ private static UdpPayload udpPayload(byte[] query, int questionEnd) {
+ UdpPayload legacy = new UdpPayload(512, false);
+ ByteBuffer packet = ByteBuffer.wrap(query);
+ if (query.length < 12 || packet.getShort(4) != 1
+ || packet.getShort(6) != 0 || packet.getShort(8) != 0) {
+ return legacy;
+ }
+ int additionalCount = Short.toUnsignedInt(packet.getShort(10));
+ packet.position(questionEnd);
+ for (int i = 0; i < additionalCount; i++) {
+ readName(packet, query);
+ if (packet.remaining() < 10) {
+ return legacy;
+ }
+ int type = Short.toUnsignedInt(packet.getShort());
+ int size = Short.toUnsignedInt(packet.getShort());
+ int ttl = packet.getInt();
+ int dataLength = Short.toUnsignedInt(packet.getShort());
+ if (packet.remaining() < dataLength) {
+ return legacy;
+ }
+ packet.position(packet.position() + dataLength);
+ if (type == 41 && ((ttl >>> 16) & 0xFF) == 0) {
+ return new UdpPayload(Math.max(512, Math.min(size, MAX_DNS_UDP_RESPONSE)), true);
}
}
+ return legacy;
+ }
- return resp.array();
+ private static void appendOpt(ByteBuffer response, UdpPayload payload) {
+ if (payload.edns()) {
+ response.put((byte) 0).putShort((short) 41).putShort((short) payload.size())
+ .putInt(0).putShort((short) 0);
+ }
}
private void forwardAsync(Vertx vertx, DatagramSocket socket, byte[] query,
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsRecordSource.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsRecordSource.java
index 285c04f96a..a7eaf44278 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsRecordSource.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsRecordSource.java
@@ -30,4 +30,9 @@ public class CloudMapDnsRecordSource implements DnsRecordSource {
public Optional<DnsAnswer> resolveIpv4(String name) {
return cloudMapService.resolveDnsNameIfOwned(name);
}
+
+ @Override
+ public Optional<DnsAnswer> resolve(String name, int type) {
+ return cloudMapService.resolveDnsNameIfOwned(name, type);
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java
index f9a0b17d30..5335b9b9a5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudmap/CloudMapService.java
@@ -9,6 +9,7 @@ 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.common.dns.DnsRecord;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
@@ -16,6 +17,7 @@ import io.github.hectorvent.floci.services.cloudmap.model.Instance;
import io.github.hectorvent.floci.services.cloudmap.model.Namespace;
import io.github.hectorvent.floci.services.cloudmap.model.Operation;
import io.github.hectorvent.floci.services.cloudmap.model.Service;
+import io.netty.util.NetUtil;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
@@ -34,6 +36,7 @@ import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
/**
@@ -272,6 +275,17 @@ public class CloudMapService {
if (attributes == null || attributes.isEmpty()) {
throw new AwsException("InvalidInput", "Attributes are required.", 400);
}
+ if (dnsRecordTtl(service, "SRV") >= 0 && service.getNamespaceId() != null) {
+ Namespace namespace = requireNamespace(service.getNamespaceId());
+ if ("DNS_PRIVATE".equals(namespace.getType()) || "DNS_PUBLIC".equals(namespace.getType())) {
+ try {
+ DnsRecord.encodeName(instanceId + "." + service.getName() + "." + namespace.getName());
+ } catch (IllegalArgumentException e) {
+ throw new AwsException("InvalidInput",
+ "The SRV target must have ASCII labels of 1 to 63 bytes and at most 253 characters.", 400);
+ }
+ }
+ }
Instance instance = new Instance();
instance.setInstanceId(instanceId);
instance.setServiceId(serviceId);
@@ -393,6 +407,10 @@ public class CloudMapService {
/** Keeps zone ownership distinct from the A records and their TTL. */
public Optional<DnsAnswer> resolveDnsNameIfOwned(String queryName) {
+ return resolveDnsNameIfOwned(queryName, 1);
+ }
+
+ public Optional<DnsAnswer> resolveDnsNameIfOwned(String queryName, int type) {
if (queryName == null || queryName.isBlank()) {
return Optional.empty();
}
@@ -422,11 +440,11 @@ public class CloudMapService {
List<Service> services = scan(serviceStore).stream()
.filter(service -> namespace.getId().equals(service.getNamespaceId()))
.toList();
- Optional<DnsAnswer> byService = resolveServiceName(services, label);
+ Optional<DnsAnswer> byService = resolveServiceName(services, label, namespace.getName(), type);
if (byService.filter(answer -> !answer.isEmpty()).isPresent()) {
return byService;
}
- Optional<DnsAnswer> byInstance = resolveInstanceHostname(services, label);
+ Optional<DnsAnswer> byInstance = resolveInstanceHostname(services, label, type);
if (byInstance.filter(answer -> !answer.isEmpty()).isPresent()) {
return byInstance;
}
@@ -437,40 +455,56 @@ public class CloudMapService {
}
/**
- * 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.
+ * Requested records at {@code <service>.<namespace>}, preserving ownership for other types.
*/
- private Optional<DnsAnswer> resolveServiceName(List<Service> services, String label) {
+ private Optional<DnsAnswer> resolveServiceName(List<Service> services, String label, String namespace, int type) {
boolean exists = false;
for (Service service : services) {
if (!label.equalsIgnoreCase(service.getName())) {
continue;
}
- int ttl = dnsRecordTtl(service, "A");
+ List<Instance> instances = scanInstances(service.getId());
+ exists |= !instances.isEmpty();
+ int recordType = type;
+ String recordName = switch (type) {
+ case 1 -> "A";
+ case 5 -> "CNAME";
+ case 28 -> "AAAA";
+ case 33 -> "SRV";
+ default -> "";
+ };
+ int ttl = dnsRecordTtl(service, recordName);
+ if (ttl < 0 && dnsRecordTtl(service, "CNAME") >= 0) {
+ recordType = 5;
+ ttl = dnsRecordTtl(service, "CNAME");
+ }
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);
+ List<DnsRecord> records = new ArrayList<>();
+ for (Instance instance : applyHealthFilter(instances, "HEALTHY_OR_ELSE_ALL")) {
+ DnsRecord record = instanceDnsRecord(instance, service, namespace, recordType);
+ if (record != null) {
+ records.add(record);
}
}
- if (!addresses.isEmpty()) {
- return Optional.of(DnsAnswer.records(addresses.size() > MAX_DNS_ANSWERS
- ? addresses.subList(0, MAX_DNS_ANSWERS) : addresses, ttl));
+ if (!records.isEmpty()) {
+ if (recordType == 5 || "WEIGHTED".equals(dnsConfigNode(service).path("RoutingPolicy").asText())) {
+ return Optional.of(DnsAnswer.typedRecords(
+ List.of(records.get(ThreadLocalRandom.current().nextInt(records.size()))), ttl));
+ }
+ return Optional.of(DnsAnswer.typedRecords(records.size() > MAX_DNS_ANSWERS
+ ? records.subList(0, MAX_DNS_ANSWERS) : records, ttl));
}
}
return exists ? Optional.of(DnsAnswer.noData()) : Optional.empty();
}
/**
- * The A record Cloud Map creates at an SRV record's target, {@code <InstanceId>.<service>.<namespace>},
+ * The address records 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) {
+ private Optional<DnsAnswer> resolveInstanceHostname(List<Service> services, String label, int type) {
boolean exists = false;
for (Service service : services) {
String serviceSuffix = "." + service.getName().toLowerCase(Locale.ROOT);
@@ -487,15 +521,42 @@ public class CloudMapService {
continue;
}
exists = true;
- String ipv4 = instance.getAttributes().get("AWS_INSTANCE_IPV4");
- if (isIpv4(ipv4)) {
- return Optional.of(DnsAnswer.records(List.of(ipv4), ttl));
+ DnsRecord record = instanceDnsRecord(instance, service, "", type);
+ if ((type == 1 || type == 28) && record != null) {
+ return Optional.of(DnsAnswer.typedRecords(List.of(record), ttl));
}
}
}
return exists ? Optional.of(DnsAnswer.noData()) : Optional.empty();
}
+ private DnsRecord instanceDnsRecord(Instance instance, Service service, String namespace, int type) {
+ Map<String, String> attributes = instance.getAttributes();
+ String ipv4 = attributes.get("AWS_INSTANCE_IPV4");
+ String ipv6 = attributes.get("AWS_INSTANCE_IPV6");
+ try {
+ DnsRecord record = switch (type) {
+ case 1 -> isIpv4(ipv4) ? new DnsRecord.Address(1, ipv4) : null;
+ case 28 -> ipv6 != null && !ipv6.contains("%") && !ipv6.startsWith("[")
+ && NetUtil.isValidIpV6Address(ipv6) ? new DnsRecord.Address(28, ipv6) : null;
+ case 5 -> attributes.get("AWS_INSTANCE_CNAME") != null
+ ? new DnsRecord.Cname(attributes.get("AWS_INSTANCE_CNAME")) : null;
+ case 33 -> attributes.get("AWS_INSTANCE_PORT") != null
+ ? new DnsRecord.Srv(Integer.parseInt(attributes.get("AWS_INSTANCE_PORT")),
+ instance.getInstanceId() + "." + service.getName() + "." + namespace) : null;
+ default -> null;
+ };
+ if (record != null) {
+ record.data();
+ }
+ return record;
+ } catch (IllegalArgumentException e) {
+ LOG.debugv("Invalid DNS attributes for Cloud Map instance {0}: {1}",
+ instance.getInstanceId(), e.getMessage());
+ return null;
+ }
+ }
+
private JsonNode parseDnsConfig(String dnsConfig) {
JsonNode config;
try {
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/CloudMapDnsPacketIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/CloudMapDnsPacketIntegrationTest.java
index 03acca5c55..40e66090d9 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/dns/CloudMapDnsPacketIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/CloudMapDnsPacketIntegrationTest.java
@@ -112,6 +112,135 @@ class CloudMapDnsPacketIntegrationTest {
Map.of(), REGION).getTargets().get("NAMESPACE");
}
+ @Test
+ void ipv6InstanceAnswersAaaaWithConfiguredTtl() throws Exception {
+ String namespace = uniqueNamespace();
+ Service service = typedService(namespace, "AAAA", "MULTIVALUE");
+ cloudMapService.registerInstance(service.getId(), "task-1", null,
+ Map.of("AWS_INSTANCE_IPV6", "2001:db8::1"), REGION);
+ byte[] request = buildQuery("typed." + namespace, (short) 28);
+ byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request);
+ ByteBuffer packet = ByteBuffer.wrap(response);
+ assertEquals(1, packet.getShort(6));
+ assertEquals(28, packet.getShort(request.length + 2));
+ assertEquals(45, packet.getInt(request.length + 6));
+ assertEquals(16, packet.getShort(request.length + 10));
+ assertArrayEquals(new byte[]{0x20, 0x01, 0x0d, (byte) 0xb8, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 1},
+ Arrays.copyOfRange(response, request.length + 12, response.length));
+ }
+
+ @Test
+ void cnameRecordIsReturnedForBothCnameAndAddressQueries() throws Exception {
+ String namespace = uniqueNamespace();
+ Service service = typedService(namespace, "CNAME", "WEIGHTED");
+ cloudMapService.registerInstance(service.getId(), "task-1", null,
+ Map.of("AWS_INSTANCE_CNAME", "backend.example.com"), REGION);
+ for (short type : new short[]{1, 5, 28}) {
+ byte[] request = buildQuery("typed." + namespace, type);
+ byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request);
+ ByteBuffer packet = ByteBuffer.wrap(response);
+ assertEquals(1, packet.getShort(6));
+ assertEquals(5, packet.getShort(request.length + 2));
+ assertEquals(45, packet.getInt(request.length + 6));
+ packet.position(request.length + 12);
+ assertEquals("backend.example.com", EmbeddedDnsServer.readName(packet, response));
+ }
+ }
+
+ @Test
+ void srvRecordCarriesThePortAndInstanceHostname() throws Exception {
+ String namespace = uniqueNamespace();
+ Service service = typedService(namespace, "SRV", "MULTIVALUE");
+ cloudMapService.registerInstance(service.getId(), "task-1", null,
+ Map.of("AWS_INSTANCE_IPV6", "2001:db8::2", "AWS_INSTANCE_PORT", "8080"), REGION);
+ byte[] request = buildQuery("typed." + namespace, (short) 33);
+ byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)), request);
+ ByteBuffer packet = ByteBuffer.wrap(response);
+ assertEquals(1, packet.getShort(6));
+ assertEquals(33, packet.getShort(request.length + 2));
+ packet.position(request.length + 12);
+ assertEquals(1, packet.getShort());
+ assertEquals(1, packet.getShort());
+ assertEquals(8080, packet.getShort());
+ assertEquals("task-1.typed." + namespace, EmbeddedDnsServer.readName(packet, response));
+ byte[] address = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)),
+ buildQuery("task-1.typed." + namespace, (short) 28));
+ assertEquals(1, ByteBuffer.wrap(address).getShort(6));
+ }
+
+ @Test
+ void weightedRoutingReturnsOneInstanceInsteadOfEight() throws Exception {
+ String namespace = uniqueNamespace();
+ Service service = typedService(namespace, "A", "WEIGHTED");
+ for (int i = 1; i <= 10; i++) {
+ cloudMapService.registerInstance(service.getId(), "task-" + i, null,
+ Map.of("AWS_INSTANCE_IPV4", "172.31.0." + i), REGION);
+ }
+ byte[] response = query(new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource)),
+ buildQuery("typed." + namespace, (short) 1));
+ assertEquals(1, ByteBuffer.wrap(response).getShort(6));
+ }
+
+ private Service typedService(String namespace, String type, String routingPolicy) {
+ return cloudMapService.createService("typed", privateDnsNamespace(namespace), null, null,
+ "{\"RoutingPolicy\":\"" + routingPolicy + "\",\"DnsRecords\":[{\"Type\":\""
+ + type + "\",\"TTL\":45}]}", null, null, null, Map.of(), REGION);
+ }
+
+ @Test
+ void largeSrvResponsesRespectLegacyAndEdnsUdpSizes() throws Exception {
+ String namespace = uniqueNamespace();
+ Service service = typedService(namespace, "SRV", "MULTIVALUE");
+ for (int i = 0; i < 8; i++) {
+ cloudMapService.registerInstance(service.getId(), "instance-with-long-name-" + i, null,
+ Map.of("AWS_INSTANCE_IPV4", "192.0.2.1", "AWS_INSTANCE_PORT", "8080"), REGION);
+ }
+ EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of(), List.of(cloudMapDnsRecordSource));
+ byte[] legacyQuery = buildQuery("typed." + namespace, (short) 33);
+ byte[] legacy = query(dns, legacyQuery);
+ ByteBuffer legacyPacket = ByteBuffer.wrap(legacy);
+ assertTrue(legacy.length <= 512);
+ assertTrue((legacyPacket.getShort(2) & 0x0200) != 0);
+ assertTrue(legacyPacket.getShort(6) < 8);
+ assertCompleteRecords(legacy, legacyQuery.length, legacyPacket.getShort(6));
+
+ byte[] ednsQuery = withEdns(legacyQuery, 1232);
+ byte[] edns = query(dns, ednsQuery);
+ ByteBuffer ednsPacket = ByteBuffer.wrap(edns);
+ assertTrue(edns.length <= 1232);
+ assertEquals(0, ednsPacket.getShort(2) & 0x0200);
+ assertEquals(8, ednsPacket.getShort(6));
+ assertEquals(1, ednsPacket.getShort(10));
+ assertEquals(41, ednsPacket.getShort(edns.length - 10));
+
+ byte[] smallEdns = query(dns, withEdns(legacyQuery, 512));
+ assertTrue(smallEdns.length <= 512);
+ assertTrue((ByteBuffer.wrap(smallEdns).getShort(2) & 0x0200) != 0);
+ }
+
+ private static byte[] withEdns(byte[] query, int payloadSize) {
+ ByteBuffer extended = ByteBuffer.allocate(query.length + 11).put(query);
+ extended.putShort(10, (short) 1);
+ extended.put((byte) 0).putShort((short) 41).putShort((short) payloadSize).putInt(0).putShort((short) 0);
+ return extended.array();
+ }
+
+ private static void assertCompleteRecords(byte[] response, int questionEnd, int count) {
+ ByteBuffer packet = ByteBuffer.wrap(response);
+ packet.position(questionEnd);
+ for (int i = 0; i < count; i++) {
+ EmbeddedDnsServer.readName(packet, response);
+ packet.getShort();
+ packet.getShort();
+ packet.getInt();
+ int length = Short.toUnsignedInt(packet.getShort());
+ assertTrue(packet.remaining() >= length);
+ packet.position(packet.position() + length);
+ }
+ assertEquals(response.length, packet.position());
+ }
+
private static String uniqueNamespace() {
return "dnspacket" + UUID.randomUUID().toString().substring(0, 8) + ".internal";
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/DnsRecordTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/DnsRecordTest.java
new file mode 100644
index 0000000000..7ec3b0d61e
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/DnsRecordTest.java
@@ -0,0 +1,50 @@
+package io.github.hectorvent.floci.core.common.dns;
+
+import org.junit.jupiter.api.Test;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class DnsRecordTest {
+ @Test
+ void ipv6MappedIpv4StillEncodesSixteenBytes() {
+ byte[] bytes = new DnsRecord.Address(28, "::ffff:192.0.2.1").data();
+ assertEquals(16, bytes.length);
+ assertArrayEquals(new byte[]{(byte) 192, 0, 2, 1}, new byte[]{bytes[12], bytes[13], bytes[14], bytes[15]});
+ }
+
+ @Test
+ void addressTypeMustMatchItsValue() {
+ assertThrows(IllegalArgumentException.class, () -> new DnsRecord.Address(1, "::1"));
+ assertThrows(IllegalArgumentException.class, () -> new DnsRecord.Address(28, "192.0.2.1"));
+ }
+
+ @Test
+ void srvPortIsAnUnsignedSixteenBitValue() {
+ byte[] bytes = new DnsRecord.Srv(65535, "task.api.internal").data();
+ assertEquals(65535, Short.toUnsignedInt(ByteBuffer.wrap(bytes).getShort(4)));
+ assertThrows(IllegalArgumentException.class, () -> new DnsRecord.Srv(-1, "task.api.internal"));
+ assertThrows(IllegalArgumentException.class, () -> new DnsRecord.Srv(65536, "task.api.internal"));
+ }
+
+ @Test
+ void namesEncodeLabelsAndIgnoreOneTrailingDot() {
+ assertArrayEquals(new byte[]{1, 'a', 1, 'b', 0}, DnsRecord.encodeName("a.b."));
+ assertThrows(IllegalArgumentException.class, () -> DnsRecord.encodeName("a..b"));
+ assertThrows(IllegalArgumentException.class, () -> DnsRecord.encodeName("a".repeat(64) + ".b"));
+ assertThrows(IllegalArgumentException.class, () -> DnsRecord.encodeName("nonascii.\u00e9"));
+ }
+
+ @Test
+ void ipv4ProjectionDoesNotIncludeNamesOrIpv6Values() {
+ DnsAnswer answer = DnsAnswer.typedRecords(List.of(new DnsRecord.Address(28, "::1")), 15);
+ assertEquals(List.of(), answer.addresses());
+ assertEquals(1, answer.records().size());
+ assertFalse(answer.isEmpty());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsResolutionTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsResolutionTest.java
index 5a74d6d636..b7a3bfdbc2 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsResolutionTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudmap/CloudMapDnsResolutionTest.java
@@ -2,15 +2,18 @@ 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.core.common.dns.DnsRecord;
import io.github.hectorvent.floci.services.cloudmap.model.Operation;
import io.github.hectorvent.floci.services.cloudmap.model.Service;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
+import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -331,4 +334,91 @@ class CloudMapDnsResolutionTest {
private static String uniqueNamespace() {
return "dnsres" + UUID.randomUUID().toString().substring(0, 8) + ".internal";
}
+
+ @Test
+ void dualStackRecordsHaveIndependentTtlsAndNoDataForOtherTypes() {
+ String namespace = uniqueNamespace();
+ Service service = createService(privateDnsNamespace(namespace), "dual",
+ dnsConfig("{\"Type\":\"A\",\"TTL\":15},{\"Type\":\"AAAA\",\"TTL\":300}"));
+ cloudMapService.registerInstance(service.getId(), "task-1", null,
+ Map.of("AWS_INSTANCE_IPV4", "172.31.0.6", "AWS_INSTANCE_IPV6", "2001:db8::1"), REGION);
+ DnsAnswer aaaa = cloudMapService.resolveDnsNameIfOwned("dual." + namespace, 28).orElseThrow();
+ assertEquals(300, aaaa.ttlSeconds());
+ assertEquals(List.of(new DnsRecord.Address(28, "2001:db8::1")), aaaa.records());
+ assertEquals(15, cloudMapService.resolveDnsNameIfOwned("dual." + namespace).orElseThrow().ttlSeconds());
+ DnsAnswer txt = cloudMapService.resolveDnsNameIfOwned("dual." + namespace, 16).orElseThrow();
+ assertTrue(txt.nameExists());
+ assertTrue(txt.isEmpty());
+ assertFalse(cloudMapService.resolveDnsNameIfOwned("missing." + namespace, 28).orElseThrow().nameExists());
+ }
+
+ @Test
+ void weightedRoutingSelectsHealthyInstancesAndFallsBackWhenAllAreUnhealthy() {
+ String namespace = uniqueNamespace();
+ Service service = createService(privateDnsNamespace(namespace), "weighted",
+ "{\"RoutingPolicy\":\"WEIGHTED\",\"DnsRecords\":[{\"Type\":\"AAAA\",\"TTL\":15}]}");
+ for (int i = 1; i <= 3; i++) {
+ cloudMapService.registerInstance(service.getId(), "task-" + i, null,
+ Map.of("AWS_INSTANCE_IPV6", "2001:db8::" + i), REGION);
+ }
+ cloudMapService.getInstance(service.getId(), "task-1").setHealthStatus("UNHEALTHY");
+ Set<DnsRecord> sampled = new HashSet<>();
+ for (int i = 0; i < 100; i++) {
+ DnsAnswer answer = cloudMapService.resolveDnsNameIfOwned("weighted." + namespace, 28).orElseThrow();
+ assertEquals(1, answer.records().size());
+ assertFalse(answer.records().contains(new DnsRecord.Address(28, "2001:db8::1")));
+ sampled.addAll(answer.records());
+ }
+ assertEquals(2, sampled.size());
+ cloudMapService.getInstance(service.getId(), "task-2").setHealthStatus("UNHEALTHY");
+ cloudMapService.getInstance(service.getId(), "task-3").setHealthStatus("UNHEALTHY");
+ assertEquals(1, cloudMapService.resolveDnsNameIfOwned("weighted." + namespace, 28).orElseThrow().records().size());
+ }
+
+ @Test
+ void invalidIpv6AndSrvPortsDoNotProduceMalformedPackets() {
+ String namespace = uniqueNamespace();
+ Service service = createService(privateDnsNamespace(namespace), "invalid",
+ dnsConfig("{\"Type\":\"SRV\",\"TTL\":15}"));
+ cloudMapService.registerInstance(service.getId(), "task-1", null,
+ Map.of("AWS_INSTANCE_IPV6", "not-an-address", "AWS_INSTANCE_PORT", "70000"), REGION);
+ assertTrue(cloudMapService.resolveDnsNameIfOwned("invalid." + namespace, 33).orElseThrow().isEmpty());
+ assertTrue(cloudMapService.resolveDnsNameIfOwned("task-1.invalid." + namespace, 28).orElseThrow().isEmpty());
+ }
+
+ @Test
+ void legacyMixedCnameConfigurationDoesNotHideConfiguredAddresses() {
+ String namespace = uniqueNamespace();
+ Service service = createService(privateDnsNamespace(namespace), "mixed",
+ dnsConfig("{\"Type\":\"A\",\"TTL\":15},{\"Type\":\"CNAME\",\"TTL\":45}"));
+ registerInstance(service.getId(), "task-1", "172.31.0.6");
+ DnsAnswer answer = cloudMapService.resolveDnsNameIfOwned("mixed." + namespace, 1).orElseThrow();
+ assertEquals(List.of("172.31.0.6"), answer.addresses());
+ assertEquals(15, answer.ttlSeconds());
+ cloudMapService.registerInstance(service.getId(), "task-1", null,
+ Map.of("AWS_INSTANCE_IPV4", "172.31.0.6", "AWS_INSTANCE_CNAME", "backend.example.com"), REGION);
+ assertEquals(List.of("172.31.0.6"), cloudMapService.resolveDnsName("mixed." + namespace));
+ assertEquals(List.of(new DnsRecord.Cname("backend.example.com")),
+ cloudMapService.resolveDnsNameIfOwned("mixed." + namespace, 5).orElseThrow().records());
+ }
+
+ @Test
+ void srvRegistrationRejectsUnencodableTargetsWithoutChangingInstanceState() {
+ String namespace = uniqueNamespace();
+ Service service = createService(privateDnsNamespace(namespace), "srv",
+ dnsConfig("{\"Type\":\"SRV\",\"TTL\":15}"));
+ Map<String, String> attributes = Map.of("AWS_INSTANCE_PORT", "8080", "AWS_INSTANCE_IPV4", "192.0.2.1");
+ cloudMapService.registerInstance(service.getId(), "a".repeat(63), null, attributes, REGION);
+ long revision = service.getRevision();
+ AwsException error = assertThrows(AwsException.class, () -> cloudMapService.registerInstance(
+ service.getId(), "a".repeat(64), null, attributes, REGION));
+ assertEquals("InvalidInput", error.getErrorCode());
+ assertEquals(1, service.getInstanceCount());
+ assertEquals(revision, service.getRevision());
+ assertEquals(1, cloudMapService.resolveDnsNameIfOwned("srv." + namespace, 33).orElseThrow().records().size());
+ // The DNS target restriction does not shorten the API's general identifier limit.
+ Service aService = createService(service.getNamespaceId(), "addresses");
+ registerInstance(aService.getId(), "a".repeat(64), "192.0.2.2");
+ assertEquals(1, aService.getInstanceCount());
+ }
}