Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(route53): serve stored public TXT and delegation records (#6034)

Andre Kurait0e6db1f2b386
diff --git a/docs/services/route53.md b/docs/services/route53.md
index dabb4d2b25..9b00f7480e 100644
--- a/docs/services/route53.md
+++ b/docs/services/route53.md
@@ -61,11 +61,21 @@ Floci resolves private hosted zone DNS records directly through its embedded DNS
- **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.
+- **Zone Visibility and Fallthrough**: Private hosted zones (created with a VPC association) retain IPv4 resolution. Public zones support the authoritative record types described below; unowned 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.
- **Resolver Rule Precedence**: A Route 53 Resolver rule associated with the querying container's VPC takes precedence over a private hosted zone that matches the same name, as it does in AWS: the query is forwarded to the rule's targets instead of answered from the zone. See [Route 53 Resolver](route53resolver.md#resolver-rules-and-dns-resolution).
- **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.
+## Public Authoritative DNS
+
+The same embedded UDP server serves stored public `TXT`, `NS`, and `SOA` records with authoritative answers and their configured TTLs. DNS clients must be able to reach Floci on UDP port 53. The HTTP endpoint published by Testcontainers wrappers does not publish this UDP listener. Host clients need an explicit UDP port mapping; containers on the same network can query Floci's container address directly.
+
+For a Docker host client, publish UDP separately from HTTP, for example `-p 5353:53/udp`, then query `dig @127.0.0.1 -p 5353 example.com TXT`. Configure the equivalent UDP binding explicitly when using a Testcontainers wrapper; its standard HTTP port mapping is insufficient.
+
+The longest matching public zone answers. Missing names return NXDOMAIN; existing names without the requested supported type return NOERROR with no answers. Both include the zone SOA with the smaller of its TTL and minimum field for negative caching. Changes and deletes affect DNS through the same stored record sets as the Route 53 API.
+
+Public address routing, aliases, CNAME chasing, health-based or weighted record selection, and delegation referrals are not implemented. Queries for supported types that require these features, ambiguous duplicate public zones, or malformed stored records return REFUSED without claiming authority. Other query types retain the existing emulator-name and upstream resolution paths. Private-zone and VPC forwarding-rule precedence remains unchanged. UDP responses honor legacy/EDNS size limits and set truncation when necessary; TCP fallback is not implemented.
+
## Default Nameservers
New zones use these nameservers (configurable via `floci.services.route53.*`):
@@ -163,4 +173,4 @@ aws route53 delete-hosted-zone --id Z1PA6795UKMFR9
- Query logging configs
- DNSSEC (key signing keys, enabling/disabling)
- `TestDNSAnswer`
-- Public hosted zone authoritative DNS serving (queries for public zones fall through to upstream forwarders)
+- Public authoritative record types other than simple TXT, NS, and SOA; public routing policies, delegation referrals, and DNS-over-TCP
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 ddaddf5c91..c90ec64d3e 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
@@ -10,7 +10,15 @@ import java.util.List;
* <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<DnsRecord> records, int ttlSeconds, boolean nameExists) {
+public record DnsAnswer(List<DnsRecord> records, int ttlSeconds, boolean nameExists,
+ Authority authority, int responseCode) {
+
+ /** The zone's SOA supplies the authority section and cache lifetime of negative answers. */
+ public record Authority(String name, DnsRecord.Soa soa, int ttlSeconds) {}
+
+ public DnsAnswer(List<DnsRecord> records, int ttlSeconds, boolean nameExists) {
+ this(records, ttlSeconds, nameExists, null, nameExists ? 0 : 3);
+ }
/** What the DNS server publishes for a name whose zone declares no TTL of its own. */
public static final int DEFAULT_TTL_SECONDS = 60;
@@ -37,6 +45,21 @@ public record DnsAnswer(List<DnsRecord> records, int ttlSeconds, boolean nameExi
return new DnsAnswer(records, ttlSeconds, true);
}
+ public DnsAnswer withAuthority(String zoneName, DnsRecord.Soa soa, int soaTtl) {
+ int negativeTtl = (int) Math.min(soaTtl, soa.minimum());
+ return new DnsAnswer(records, ttlSeconds, nameExists,
+ new Authority(zoneName, soa, negativeTtl), responseCode);
+ }
+
+ /** An owned public query whose type, routing policy, or zone identity cannot be served. */
+ public static DnsAnswer refused() {
+ return new DnsAnswer(List.of(), DEFAULT_TTL_SECONDS, true, null, 5);
+ }
+
+ public boolean isPublicAuthorityAnswer() {
+ return authority != null || responseCode == 5;
+ }
+
/** 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)
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
index cb4b743059..947879c462 100644
--- 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
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.core.common.dns;
import io.netty.util.NetUtil;
+import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
@@ -36,6 +37,126 @@ public sealed interface DnsRecord {
}
}
+ record Ns(String target) implements DnsRecord {
+ @Override
+ public int type() {
+ return 2;
+ }
+
+ @Override
+ public byte[] data() {
+ return encodeName(target);
+ }
+ }
+
+ /** Route 53 TXT values use DNS presentation syntax, including multiple quoted strings. */
+ record Txt(String value) implements DnsRecord {
+ @Override
+ public int type() {
+ return 16;
+ }
+
+ @Override
+ public byte[] data() {
+ ByteArrayOutputStream result = new ByteArrayOutputStream();
+ int index = 0;
+ while (index < value.length()) {
+ if (Character.isWhitespace(value.charAt(index))) {
+ index++;
+ continue;
+ }
+ if (value.charAt(index++) != '"') {
+ throw new IllegalArgumentException("TXT strings must be quoted");
+ }
+ ByteArrayOutputStream text = new ByteArrayOutputStream();
+ boolean closed = false;
+ while (index < value.length()) {
+ char character = value.charAt(index++);
+ if (character == '"') {
+ closed = true;
+ break;
+ }
+ if (character == '\\') {
+ if (index == value.length()) {
+ throw new IllegalArgumentException("Incomplete TXT escape");
+ }
+ character = value.charAt(index++);
+ if (character >= '0' && character <= '9') {
+ if (character > '7' || index + 1 >= value.length()
+ || value.charAt(index) < '0' || value.charAt(index) > '7'
+ || value.charAt(index + 1) < '0' || value.charAt(index + 1) > '7') {
+ throw new IllegalArgumentException("TXT octal escapes require three octal digits");
+ }
+ int octet = (character - '0') * 64 + (value.charAt(index) - '0') * 8
+ + value.charAt(index + 1) - '0';
+ if (octet > 255) {
+ throw new IllegalArgumentException("TXT escape exceeds one byte");
+ }
+ text.write(octet);
+ index += 2;
+ continue;
+ }
+ }
+ int codePoint = character;
+ if (Character.isHighSurrogate(character) && index < value.length()
+ && Character.isLowSurrogate(value.charAt(index))) {
+ codePoint = Character.toCodePoint(character, value.charAt(index++));
+ }
+ text.writeBytes(new String(Character.toChars(codePoint)).getBytes(StandardCharsets.UTF_8));
+ }
+ if (!closed || text.size() > 255) {
+ throw new IllegalArgumentException("TXT character strings must close and contain at most 255 bytes");
+ }
+ result.write(text.size());
+ result.writeBytes(text.toByteArray());
+ }
+ if (result.size() == 0) {
+ throw new IllegalArgumentException("TXT requires at least one character string");
+ }
+ return result.toByteArray();
+ }
+ }
+
+ record Soa(String value) implements DnsRecord {
+ @Override
+ public int type() {
+ return 6;
+ }
+
+ private String[] fields() {
+ String[] fields = value.trim().split("\\s+");
+ if (fields.length != 7) {
+ throw new IllegalArgumentException("SOA requires two names and five unsigned integers");
+ }
+ return fields;
+ }
+
+ public long minimum() {
+ return unsignedInteger(fields()[6]);
+ }
+
+ @Override
+ public byte[] data() {
+ String[] fields = fields();
+ byte[] primary = encodeName(fields[0]);
+ byte[] mailbox = encodeName(fields[1]);
+ ByteBuffer result = ByteBuffer.allocate(primary.length + mailbox.length + 20);
+ result.put(primary).put(mailbox);
+ for (int i = 2; i < fields.length; i++) {
+ result.putInt((int) unsignedInteger(fields[i]));
+ }
+ return result.array();
+ }
+
+ private static long unsignedInteger(String value) {
+ long number = Long.parseLong(value);
+ if (number < 0 || number > 0xFFFFFFFFL) {
+ throw new IllegalArgumentException("SOA integer must fit an unsigned 32-bit field");
+ }
+ return number;
+ }
+ }
+
record Srv(int port, String target) implements DnsRecord {
public Srv {
if (port < 0 || port > 65535) {
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 efd28fa759..684b1d8285 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
@@ -13,6 +13,11 @@ import java.util.Optional;
*/
public interface DnsRecordSource {
+ /** Stored public authority data only; this lookup must not perform recursive resolution. */
+ default Optional<DnsAnswer> resolveAuthoritative(String name, int type) {
+ return Optional.empty();
+ }
+
/**
* Resolves a query name to IPv4 addresses and their TTL. An empty optional means this
* source does not own the name. The name arrives without a trailing dot and in the case the client sent.
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 8bb457325a..5c41ae94c4 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
@@ -208,7 +208,7 @@ public class EmbeddedDnsServer {
int questionOffset = buf.position(); // always 12 for a standard query
String qname = readName(buf, data);
short qtype = buf.getShort();
- buf.getShort(); // qclass
+ short qclass = buf.getShort();
int questionEnd = buf.position();
vertx.<QueryPlan>executeBlocking(() -> planQuery(qname, senderHost, myIp, qtype), false)
@@ -223,7 +223,13 @@ public class EmbeddedDnsServer {
return;
}
DnsAnswer records = plan.answer().orElseThrow();
- byte[] response = !records.isEmpty()
+ if (records.isPublicAuthorityAnswer()
+ && (qdCount != 1 || qclass != 1 || (flags & 0x7840) != 0)) {
+ records = DnsAnswer.refused();
+ }
+ byte[] response = records.isPublicAuthorityAnswer()
+ ? buildPublicResponse(data, txId, questionOffset, questionEnd, records)
+ : !records.isEmpty()
? buildAResponse(data, txId, questionOffset, questionEnd, records)
: buildEmptyResponse(data, txId, questionOffset, questionEnd,
records.nameExists() ? 0 : 3);
@@ -261,6 +267,10 @@ public class EmbeddedDnsServer {
}
private Optional<DnsAnswer> resolveRecordWithOwnership(String name, String myIp, int type) {
+ Optional<DnsAnswer> stored = resolveFromRecordSources(name, type, true);
+ if (stored.isPresent()) {
+ return stored;
+ }
Optional<DnsAnswer> emulatorName = resolveEmulatorName(name, myIp, type);
return emulatorName.isPresent() ? emulatorName : resolveFromRecordSources(name, type);
}
@@ -284,7 +294,8 @@ public class EmbeddedDnsServer {
}
/**
- * Names the emulator itself owns come first, whatever the rules say. Route 53 Resolver does
+ * Stored public authority answers take precedence over broad emulator suffix spoofing.
+ * Other names the emulator itself owns come first, whatever the rules say. Route 53 Resolver does
* the same for the AWS-internal domains it autodefines system rules for, so that a rule for a
* broad domain (or for "." itself) cannot send the platform's own names off to a resolver that
* knows nothing about them.
@@ -294,8 +305,9 @@ public class EmbeddedDnsServer {
* hosted zone that matches the same name.
*/
QueryPlan planQuery(String name, String clientAddress, String myIp, int type) {
+ Optional<DnsAnswer> stored = resolveFromRecordSources(name, type, true);
Optional<DnsAnswer> emulatorName = resolveEmulatorName(name, myIp, type);
- if (emulatorName.isPresent()) {
+ if (emulatorName.isPresent() && stored.isEmpty()) {
return QueryPlan.answering(emulatorName.orElseThrow());
}
// A rule steers the name whatever the query asks about it, so this is deliberately not
@@ -304,7 +316,8 @@ public class EmbeddedDnsServer {
if (rule.isPresent() && rule.orElseThrow().forwards()) {
return QueryPlan.forwardingTo(rule.orElseThrow().targets());
}
- return resolveFromRecordSources(name, type).map(QueryPlan::answering).orElse(QueryPlan.UPSTREAM);
+ return stored.or(() -> resolveFromRecordSources(name, type))
+ .map(QueryPlan::answering).orElse(QueryPlan.UPSTREAM);
}
private Optional<DnsAnswer> resolveEmulatorName(String name, String myIp, int type) {
@@ -385,12 +398,17 @@ public class EmbeddedDnsServer {
* through to the upstream resolvers, which is what happened before any source existed.
*/
private Optional<DnsAnswer> resolveFromRecordSources(String name, int type) {
+ return resolveFromRecordSources(name, type, false);
+ }
+
+ private Optional<DnsAnswer> resolveFromRecordSources(String name, int type, boolean authoritative) {
if (recordSources == null) {
return Optional.empty();
}
for (DnsRecordSource source : recordSources) {
try {
- Optional<DnsAnswer> answer = source.resolve(name, type);
+ Optional<DnsAnswer> answer = authoritative ? source.resolveAuthoritative(name, type)
+ : source.resolve(name, type);
if (answer != null && answer.isPresent()) {
return answer;
}
@@ -522,7 +540,8 @@ public class EmbeddedDnsServer {
// header
resp.putShort(txId);
- resp.putShort((short) (0x8180 | (truncated ? 0x0200 : 0))); // QR=1, RD=1, RCODE=0
+ int flags = answer.authority() == null ? 0x8180 : 0x8400 | (query[2] & 1) << 8;
+ resp.putShort((short) (flags | (truncated ? 0x0200 : 0)));
resp.putShort((short) 1); // qdcount
resp.putShort((short) answerCount); // ancount
resp.putShort((short) 0); // nscount
@@ -544,6 +563,34 @@ public class EmbeddedDnsServer {
return resp.array();
}
+ byte[] buildPublicResponse(byte[] query, short txId, int questionOffset, int questionEnd, DnsAnswer answer) {
+ if (!answer.isEmpty()) {
+ return buildAResponse(query, txId, questionOffset, questionEnd, answer);
+ }
+ int flags = 0x8000 | (query[2] & 0x79) << 8 | answer.responseCode();
+ DnsAnswer.Authority authority = answer.authority();
+ if (authority == null) {
+ return buildAnswerlessResponse(query, txId, questionOffset, questionEnd, (short) flags);
+ }
+ byte[] owner = DnsRecord.encodeName(authority.name());
+ byte[] soa = authority.soa().data();
+ UdpPayload payload = udpPayload(query, questionEnd);
+ int questionLength = questionEnd - questionOffset;
+ int length = 12 + questionLength + (payload.edns() ? 11 : 0);
+ boolean fits = length + owner.length + 10 + soa.length <= payload.size();
+ ByteBuffer response = ByteBuffer.allocate(length + (fits ? owner.length + 10 + soa.length : 0));
+ response.putShort(txId).putShort((short) (flags | 0x0400 | (fits ? 0 : 0x0200)));
+ response.putShort((short) 1).putShort((short) 0).putShort((short) (fits ? 1 : 0))
+ .putShort((short) (payload.edns() ? 1 : 0));
+ response.put(query, questionOffset, questionLength);
+ if (fits) {
+ response.put(owner).putShort((short) 6).putShort((short) 1).putInt(authority.ttlSeconds())
+ .putShort((short) soa.length).put(soa);
+ }
+ appendOpt(response, payload);
+ return response.array();
+ }
+
private record UdpPayload(int size, boolean edns) {}
private static UdpPayload udpPayload(byte[] query, int questionEnd) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53DnsRecordSource.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53DnsRecordSource.java
index b6b1880904..501003c7ce 100644
--- a/src/main/java/io/github/hectorvent/floci/services/route53/Route53DnsRecordSource.java
+++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53DnsRecordSource.java
@@ -5,6 +5,7 @@ import io.github.hectorvent.floci.config.LocalStackParity;
import io.github.hectorvent.floci.core.common.DomainNames;
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.DnsRecord;
import io.github.hectorvent.floci.core.common.dns.DnsRecordSource;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import io.github.hectorvent.floci.services.route53.model.AliasTarget;
@@ -15,6 +16,7 @@ import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.net.InetAddress;
+import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
@@ -25,7 +27,7 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
- * Resolves Route 53 private hosted zone records for the embedded DNS server.
+ * Resolves private IPv4 records and public TXT/NS/SOA records for the embedded DNS server.
*
* <p>Discovered via CDI as a {@link DnsRecordSource} implementation, keeping
* the embedded DNS server decoupled from Route 53 service classes.
@@ -66,6 +68,88 @@ public class Route53DnsRecordSource implements DnsRecordSource {
}
}
+ @Override
+ public Optional<DnsAnswer> resolveAuthoritative(String name, int type) {
+ if (name == null || name.isBlank() || (type != 2 && type != 6 && type != 16)) {
+ return Optional.empty();
+ }
+ if (route53Service.isCoveredByPrivateZone(name)) {
+ return Optional.empty();
+ }
+ List<Route53Service.PublicDnsZone> zones = route53Service.publicDnsZones(name);
+ if (zones.isEmpty()) {
+ return Optional.empty();
+ }
+ if (zones.size() != 1) {
+ return Optional.of(DnsAnswer.refused());
+ }
+ Route53Service.PublicDnsZone zone = zones.getFirst();
+ String normalized = Route53Service.normalizeName(name).toLowerCase(Locale.ROOT);
+ String apex = Route53Service.normalizeName(zone.name()).toLowerCase(Locale.ROOT);
+ // A delegation ends this zone's authority. Serving the parent's negative answer below
+ // that cut, or flattening an unsupported CNAME/routing policy, would hide real records.
+ boolean delegated = zone.records().stream().anyMatch(record -> "NS".equals(record.getType())
+ && !Route53Service.normalizeName(record.getName()).equalsIgnoreCase(apex)
+ && DomainNames.isWithin(normalized, Route53Service.normalizeName(record.getName())));
+ if (delegated || zone.matchingRecords().stream().anyMatch(record -> "CNAME".equals(record.getType()))) {
+ return Optional.of(DnsAnswer.refused());
+ }
+ ResourceRecordSet soaSet = zone.records().stream()
+ .filter(record -> "SOA".equals(record.getType())
+ && Route53Service.normalizeName(record.getName()).equalsIgnoreCase(apex))
+ .findFirst().orElse(null);
+ if (soaSet == null || soaSet.getRecords() == null || soaSet.getRecords().size() != 1) {
+ return Optional.of(DnsAnswer.refused());
+ }
+ List<DnsRecord> answers = new ArrayList<>();
+ int ttl = Integer.MAX_VALUE;
+ try {
+ for (ResourceRecordSet record : zone.matchingRecords()) {
+ if (!record.getType().equals(switch (type) {
+ case 2 -> "NS";
+ case 6 -> "SOA";
+ default -> "TXT";
+ })) {
+ continue;
+ }
+ if (record.getSetIdentifier() != null || record.getAliasTarget() != null
+ || record.getWeight() != null || record.getRegion() != null
+ || record.getFailover() != null || record.getHealthCheckId() != null
+ || record.getRecords() == null) {
+ return Optional.of(DnsAnswer.refused());
+ }
+ for (ResourceRecord value : record.getRecords()) {
+ if (value == null || value.getValue() == null) {
+ return Optional.of(DnsAnswer.refused());
+ }
+ DnsRecord answer = switch (type) {
+ case 2 -> new DnsRecord.Ns(value.getValue());
+ case 6 -> new DnsRecord.Soa(value.getValue());
+ default -> new DnsRecord.Txt(value.getValue());
+ };
+ answer.data();
+ answers.add(answer);
+ }
+ ttl = Math.min(ttl, publicTtlOf(record));
+ }
+ boolean exists = !zone.matchingRecords().isEmpty() || zone.records().stream()
+ .anyMatch(record -> Route53Service.normalizeName(record.getName()).toLowerCase(Locale.ROOT)
+ .endsWith("." + normalized));
+ DnsAnswer answer = answers.isEmpty() ? (exists ? DnsAnswer.noData() : DnsAnswer.nxDomain())
+ : DnsAnswer.typedRecords(answers, ttl);
+ ResourceRecord soaValue = soaSet.getRecords().getFirst();
+ if (soaValue == null || soaValue.getValue() == null) {
+ return Optional.of(DnsAnswer.refused());
+ }
+ DnsRecord.Soa soa = new DnsRecord.Soa(soaValue.getValue());
+ soa.data();
+ return Optional.of(answer.withAuthority(apex, soa, publicTtlOf(soaSet)));
+ } catch (IllegalArgumentException e) {
+ LOG.debugv("Cannot encode public DNS records for {0}: {1}", name, e.getMessage());
+ return Optional.of(DnsAnswer.refused());
+ }
+ }
+
@Override
public Optional<DnsAnswer> resolveIpv4(String name) {
if (name == null || name.isBlank()) {
@@ -175,6 +259,14 @@ public class Route53DnsRecordSource implements DnsRecordSource {
return dnsLookupHelper.resolveIpv4(name);
}
+ private static int publicTtlOf(ResourceRecordSet record) {
+ Long ttl = record.getTtl();
+ if (ttl == null || ttl < 0 || ttl > Integer.MAX_VALUE) {
+ throw new IllegalArgumentException("Invalid public record TTL");
+ }
+ return ttl.intValue();
+ }
+
private static int ttlOf(ResourceRecordSet rrs) {
Long ttl = rrs.getTtl();
if (ttl == null || ttl < 0) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java
index d11291b29f..49fced477b 100644
--- a/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/route53/Route53Service.java
@@ -59,6 +59,7 @@ public class Route53Service implements Resettable {
private final Map<String, Long> hostedZoneMutationBusyUntilNanos = new ConcurrentHashMap<>();
private final Map<String, Long> authorizationMutationBusyUntilNanos = new ConcurrentHashMap<>();
private final Map<String, Integer> privateZoneNameCounts = new ConcurrentHashMap<>();
+ private final Map<String, Integer> publicZoneNameCounts = new ConcurrentHashMap<>();
@Inject
public Route53Service(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,
@@ -88,9 +89,8 @@ public class Route53Service implements Resettable {
this.ec2Service = ec2Service;
this.vpcAssociationControlPlaneDelayMs = Math.max(0, r53.vpcAssociationControlPlaneDelayMs());
for (OwnedZone owned : allHostedZonesAcrossAccounts()) {
- if (owned.zone().isPrivateZone()) {
- privateZoneNameCounts.merge(normalizeName(owned.zone().getName()).toLowerCase(), 1, Integer::sum);
- }
+ zoneNameCounts(owned.zone().isPrivateZone()).merge(
+ normalizeName(owned.zone().getName()).toLowerCase(), 1, Integer::sum);
}
}
@@ -114,8 +114,8 @@ public class Route53Service implements Resettable {
zone.setOwnerAccountId(callerAccountId);
if (vpcAssociation != null) {
vpcAssociation.setOwnerAccountId(callerAccountId);
- privateZoneNameCounts.merge(normalizedName.toLowerCase(), 1, Integer::sum);
}
+ zoneNameCounts(zone.isPrivateZone()).merge(normalizedName.toLowerCase(), 1, Integer::sum);
zoneStore.put(id, zone);
recordStore.put(id, buildDefaultRecords(normalizedName));
ChangeInfo change = newChange(null);
@@ -144,10 +144,8 @@ public class Route53Service implements Resettable {
recordStore.delete(id);
tagStore.delete("hostedzone/" + id);
vpcAuthorizationStore.delete(id);
- if (zone.isPrivateZone()) {
- privateZoneNameCounts.computeIfPresent(normalizeName(zone.getName()).toLowerCase(),
- (k, v) -> v > 1 ? v - 1 : null);
- }
+ zoneNameCounts(zone.isPrivateZone()).computeIfPresent(normalizeName(zone.getName()).toLowerCase(),
+ (k, v) -> v > 1 ? v - 1 : null);
return newChange(null);
}
@@ -623,12 +621,18 @@ public class Route53Service implements Resettable {
if (qname == null || qname.isBlank()) {
return List.of();
}
- String normalizedQname = normalizeName(qname).toLowerCase();
+ return findRecordsForName(normalizeName(qname).toLowerCase(),
+ mostSpecificZones(normalizeName(qname).toLowerCase(), true).stream()
+ .map(owned -> getRecordsForZoneAcrossAccounts(owned.accountId(), owned.zone().getId()))
+ .toList());
+ }
+
+ private static List<ResourceRecordSet> findRecordsForName(String normalizedQname,
+ List<List<ResourceRecordSet>> zoneRecords) {
List<ResourceRecordSet> nameMatches = new ArrayList<>();
List<ResourceRecordSet> wildcardMatches = new ArrayList<>();
- for (OwnedZone owned : mostSpecificPrivateZones(normalizedQname)) {
- List<ResourceRecordSet> records = getRecordsForZoneAcrossAccounts(owned.accountId(), owned.zone().getId());
+ for (List<ResourceRecordSet> records : zoneRecords) {
List<ResourceRecordSet> zoneWildcards = new ArrayList<>();
for (ResourceRecordSet rrs : records) {
String rName = normalizeName(rrs.getName()).toLowerCase();
@@ -684,7 +688,7 @@ public class Route53Service implements Resettable {
}
String normalizedQname = normalizeName(qname).toLowerCase();
String suffix = "." + normalizedQname;
- for (OwnedZone owned : mostSpecificPrivateZones(normalizedQname)) {
+ for (OwnedZone owned : mostSpecificZones(normalizedQname, true)) {
for (ResourceRecordSet rrs : getRecordsForZoneAcrossAccounts(owned.accountId(), owned.zone().getId())) {
if (normalizeName(rrs.getName()).toLowerCase().endsWith(suffix)) {
return true;
@@ -694,17 +698,35 @@ public class Route53Service implements Resettable {
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 -> DomainNames.isWithin(normalizedQname, z))) {
+ record PublicDnsZone(String name, List<ResourceRecordSet> matchingRecords, List<ResourceRecordSet> records) {}
+
+ List<PublicDnsZone> publicDnsZones(String qname) {
+ String normalized = normalizeName(qname).toLowerCase();
+ return mostSpecificZones(normalized, false).stream()
+ .map(owned -> {
+ List<ResourceRecordSet> records = getRecordsForZoneAcrossAccounts(
+ owned.accountId(), owned.zone().getId());
+ return new PublicDnsZone(owned.zone().getName(),
+ findRecordsForName(normalized, List.of(records)), records);
+ })
+ .toList();
+ }
+
+ private Map<String, Integer> zoneNameCounts(boolean privateZone) {
+ return privateZone ? privateZoneNameCounts : publicZoneNameCounts;
+ }
+
+ /** The longest containing zones, so a parent never answers for a more specific child. */
+ private List<OwnedZone> mostSpecificZones(String normalizedQname, boolean privateZone) {
+ Map<String, Integer> names = zoneNameCounts(privateZone);
+ if (names.isEmpty() || names.keySet().stream().noneMatch(z -> DomainNames.isWithin(normalizedQname, z))) {
return List.of();
}
List<OwnedZone> matchingZones = new ArrayList<>();
int maxZoneLength = -1;
for (OwnedZone owned : allHostedZonesAcrossAccounts()) {
HostedZone zone = owned.zone();
- if (!zone.isPrivateZone()) {
+ if (zone.isPrivateZone() != privateZone) {
continue;
}
String zoneName = normalizeName(zone.getName()).toLowerCase();
@@ -1026,5 +1048,6 @@ public class Route53Service implements Resettable {
hostedZoneMutationBusyUntilNanos.clear();
authorizationMutationBusyUntilNanos.clear();
privateZoneNameCounts.clear();
+ publicZoneNameCounts.clear();
}
}
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
index 7ec3b0d61e..80d8d0e689 100644
--- 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
@@ -47,4 +47,29 @@ class DnsRecordTest {
assertEquals(1, answer.records().size());
assertFalse(answer.isEmpty());
}
+
+ @Test
+ void txtPreservesQuotedSegmentsEscapesAndEmptyStrings() {
+ assertArrayEquals(new byte[]{3, 'a', ' ', 'b', 2, '"', '\\', 1, (byte) 255, 0},
+ new DnsRecord.Txt("\"a b\" \"\\\"\\\\\" \"\\377\" \"\"").data());
+ assertEquals(256, new DnsRecord.Txt("\"" + "x".repeat(255) + "\"").data().length);
+ assertThrows(IllegalArgumentException.class,
+ () -> new DnsRecord.Txt("\"" + "x".repeat(256) + "\"").data());
+ assertThrows(IllegalArgumentException.class, () -> new DnsRecord.Txt("\"\\400\"").data());
+ assertThrows(IllegalArgumentException.class, () -> new DnsRecord.Txt("\"unclosed").data());
+ }
+
+ @Test
+ void soaEncodesNamesAndUnsignedFields() {
+ byte[] bytes = new DnsRecord.Soa("ns.example. host.example. 4294967295 7200 900 1209600 30").data();
+ ByteBuffer packet = ByteBuffer.wrap(bytes);
+ assertEquals("ns.example", EmbeddedDnsServer.readName(packet, bytes));
+ assertEquals("host.example", EmbeddedDnsServer.readName(packet, bytes));
+ assertEquals(4294967295L, Integer.toUnsignedLong(packet.getInt()));
+ assertEquals(7200, packet.getInt());
+ assertEquals(900, packet.getInt());
+ assertEquals(1209600, packet.getInt());
+ assertEquals(30, packet.getInt());
+ assertArrayEquals(DnsRecord.encodeName("ns.example."), new DnsRecord.Ns("ns.example.").data());
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java
index 722f94c52c..9f70ae7381 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java
@@ -15,6 +15,7 @@ import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
@@ -316,14 +317,20 @@ class EmbeddedDnsServerTest {
@Test
void planQuery_aMatchingRuleTakesPrecedenceOverAPrivateHostedZoneRecord() {
+ AtomicInteger privateLookups = new AtomicInteger();
+ DnsRecordSource privateSource = name -> {
+ privateLookups.incrementAndGet();
+ return Optional.of(DnsAnswer.records(List.of("10.0.0.7"), 60));
+ };
EmbeddedDnsServer dns = withRules(
- List.of(source("db.corp.internal", List.of("10.0.0.7"))),
+ List.of(privateSource),
rules("vpc-a", forward("corp.internal", "10.1.0.53")), clientVpc("vpc-a"));
EmbeddedDnsServer.QueryPlan plan = dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1);
assertTrue(plan.answer().isEmpty(), "the rule decides the name, not the zone record");
assertEquals(List.of(new DnsForwardingRule.Target("10.1.0.53", 53)), plan.ruleTargets());
+ assertEquals(0, privateLookups.get(), "a winning rule must not trigger private CNAME resolution");
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/Route53DnsPacketIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/Route53DnsPacketIntegrationTest.java
new file mode 100644
index 0000000000..f333c46ccf
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/Route53DnsPacketIntegrationTest.java
@@ -0,0 +1,305 @@
+package io.github.hectorvent.floci.core.common.dns;
+
+import io.github.hectorvent.floci.services.route53.Route53DnsRecordSource;
+import io.github.hectorvent.floci.services.route53.Route53Service;
+import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
+import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
+import io.github.hectorvent.floci.services.route53.model.VpcAssociation;
+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.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+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 io.restassured.RestAssured.given;
+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.assertTrue;
+
+@QuarkusTest
+class Route53DnsPacketIntegrationTest {
+ @Inject
+ Route53Service route53;
+ @Inject
+ Route53DnsRecordSource source;
+ @Inject
+ Vertx vertx;
+
+ private final List<String> zoneIds = new ArrayList<>();
+
+ @AfterEach
+ void deleteOwnedZones() {
+ for (String id : zoneIds.reversed()) {
+ String apex = route53.getHostedZone(id).getName();
+ List<Map<String, Object>> deletes = route53.listResourceRecordSets(id, null, null, 100).stream()
+ .filter(record -> !(record.getName().equals(apex)
+ && ("NS".equals(record.getType()) || "SOA".equals(record.getType()))))
+ .map(record -> Map.<String, Object>of("action", "DELETE", "rrs", record)).toList();
+ if (!deletes.isEmpty()) {
+ route53.changeResourceRecordSets(id, deletes, null);
+ }
+ route53.deleteHostedZone(id);
+ }
+ }
+
+ @Test
+ void apiChangesAndDeletesReachAuthoritativeTxtDespiteAwsEndpointSpoofing() throws Exception {
+ String name = uniqueName() + ".amazonaws.com";
+ String id = createZone(name);
+ String endpoint = "version." + name;
+ for (String value : List.of("first", "second")) {
+ given().contentType("application/xml").body("""
+ <ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
+ <ChangeBatch><Changes><Change><Action>UPSERT</Action><ResourceRecordSet>
+ <Name>%s</Name><Type>TXT</Type><TTL>17</TTL>
+ <ResourceRecords><ResourceRecord><Value>"%s"</Value></ResourceRecord></ResourceRecords>
+ </ResourceRecordSet></Change></Changes></ChangeBatch>
+ </ChangeResourceRecordSetsRequest>
+ """.formatted(endpoint, value))
+ .post("/2013-04-01/hostedzone/" + id + "/rrset").then().statusCode(200);
+ byte[] request = request(endpoint, 16);
+ byte[] response = query(request);
+ assertHeader(response, 0, true, 1, 0);
+ assertEquals(17, ByteBuffer.wrap(response).getInt(request.length + 6));
+ assertArrayEquals(new DnsRecord.Txt("\"" + value + "\"").data(),
+ Arrays.copyOfRange(response, request.length + 12, response.length));
+ }
+ change(id, "DELETE", record(endpoint, "TXT", 17, "\"second\""));
+ assertNegative(query(request(endpoint, 16)), name, 3, 900);
+ }
+
+ @Test
+ void delegationNamesAndSoaUseTheStoredZone() throws Exception {
+ String name = uniqueName() + ".example";
+ String id = createZone(name);
+ List<String> expected = route53.getNameServers();
+ byte[] request = request(name, 2);
+ byte[] response = query(request);
+ assertHeader(response, 0, true, 4, 0);
+ ByteBuffer packet = ByteBuffer.wrap(response);
+ packet.position(request.length);
+ List<String> actual = new ArrayList<>();
+ for (int i = 0; i < 4; i++) {
+ EmbeddedDnsServer.readName(packet, response);
+ assertEquals(2, packet.getShort());
+ assertEquals(1, packet.getShort());
+ packet.getInt();
+ packet.getShort();
+ actual.add(EmbeddedDnsServer.readName(packet, response));
+ }
+ assertEquals(expected, actual);
+ ResourceRecordSet soa = route53.listResourceRecordSets(id, null, null, 100).stream()
+ .filter(record -> "SOA".equals(record.getType())).findFirst().orElseThrow();
+ byte[] soaRequest = request(name, 6);
+ byte[] soaResponse = query(soaRequest);
+ assertHeader(soaResponse, 0, true, 1, 0);
+ assertArrayEquals(new DnsRecord.Soa(soa.getRecords().getFirst().getValue()).data(),
+ Arrays.copyOfRange(soaResponse, soaRequest.length + 12, soaResponse.length));
+ }
+
+ @Test
+ void negativeAnswersDistinguishNamesEmptyNonterminalsAndWildcardMatches() throws Exception {
+ String name = uniqueName() + ".example";
+ String id = createZone(name);
+ change(id, "UPSERT", record(name, "SOA", 120,
+ "ns.example. host.example. 1 7200 900 1209600 30"));
+ change(id, "CREATE", record("address." + name, "A", 60, "192.0.2.1"));
+ change(id, "CREATE", record("leaf.branch." + name, "TXT", 60, "\"leaf\""));
+ assertNegative(query(request("address." + name, 16)), name, 0, 30);
+ assertNegative(query(request("branch." + name, 16)), name, 0, 30);
+ assertNegative(query(request("absent." + name, 16)), name, 3, 30);
+ change(id, "CREATE", record("*." + name, "TXT", 45, "\"wildcard\""));
+ assertHeader(query(request("other." + name, 16)), 0, true, 1, 0);
+ assertNegative(query(request("missing.branch." + name, 16)), name, 3, 30);
+ }
+
+ @Test
+ void mostSpecificZoneWinsAndDuplicateZoneIdentityIsRefused() throws Exception {
+ String parent = uniqueName() + ".example";
+ String child = "child." + parent;
+ String parentId = createZone(parent);
+ change(parentId, "CREATE", record("marker." + child, "TXT", 60, "\"parent\""));
+ createZone(child);
+ assertNegative(query(request("marker." + child, 16)), child, 3, 900);
+ createZone(child);
+ assertHeader(query(request("marker." + child, 16)), 5, false, 0, 0);
+ }
+
+ @Test
+ void unsupportedTypesRoutingAndDelegationDoNotBecomeAuthoritativeNoData() throws Exception {
+ String name = uniqueName() + ".example";
+ String id = createZone(name);
+ ResourceRecordSet weighted = record("weighted." + name, "TXT", 60, "\"one\"");
+ weighted.setSetIdentifier("one");
+ weighted.setWeight(1L);
+ change(id, "CREATE", weighted);
+ change(id, "CREATE", record("alias." + name, "CNAME", 60, "target.example."));
+ change(id, "CREATE", record("delegated." + name, "NS", 60, "other.example."));
+ for (int type : List.of(1, 28, 15, 5)) {
+ assertTrue(source.resolveAuthoritative(name, type).isEmpty());
+ }
+ String awsName = uniqueName() + ".amazonaws.com";
+ createZone(awsName);
+ byte[] address = query(request(awsName, 1));
+ assertArrayEquals(new byte[]{127, 0, 0, 1},
+ Arrays.copyOfRange(address, address.length - 4, address.length));
+ for (String label : List.of("weighted", "alias", "leaf.delegated")) {
+ assertHeader(query(request(label + "." + name, 16)), 5, false, 0, 0);
+ }
+ }
+
+ @Test
+ void privateZonePrecedenceAndPublicQueryShapeRemainExplicit() throws Exception {
+ String name = uniqueName() + ".example";
+ String id = createZone(name);
+ change(id, "CREATE", record("marker." + name, "TXT", 60, "\"public\""));
+ for (int field : List.of(2, 4, -1, -2)) {
+ byte[] request = request("marker." + name, 16);
+ ByteBuffer packet = ByteBuffer.wrap(request);
+ if (field == -2) {
+ packet.putShort(2, (short) 0x0140);
+ } else if (field == -1) {
+ packet.putShort(request.length - 2, (short) 3);
+ } else {
+ packet.putShort(field, (short) (field == 2 ? 0x0900 : 2));
+ }
+ assertHeader(query(request), 5, false, 0, 0);
+ }
+ String privateId = route53.createHostedZone(name, UUID.randomUUID().toString(), null,
+ new VpcAssociation("vpc-dns-packet", "us-east-1")).zone().getId();
+ zoneIds.add(privateId);
+ change(privateId, "CREATE", record("address." + name, "A", 60, "192.0.2.9"));
+ assertEquals(List.of("192.0.2.9"), source.resolve("address." + name, 1).orElseThrow().addresses());
+ assertFalse(source.resolve("marker." + name, 16).orElseThrow().isPublicAuthorityAnswer());
+ }
+
+ @Test
+ void malformedStoredValuesAndTtlsStayRefused() throws Exception {
+ String name = uniqueName() + ".example";
+ String id = createZone(name);
+ for (String type : List.of("TXT", "NS", "SOA")) {
+ String owner = "bad-" + type.toLowerCase() + "." + name;
+ change(id, "UPSERT", record(owner, type, 60, null));
+ int queryType = switch (type) {
+ case "NS" -> 2;
+ case "SOA" -> 6;
+ default -> 16;
+ };
+ assertHeader(query(request(owner, queryType)), 5, false, 0, 0);
+ }
+ for (long ttl : List.of(-1L, 2147483648L)) {
+ change(id, "UPSERT", record("ttl." + name, "TXT", ttl, "\"value\""));
+ assertHeader(query(request("ttl." + name, 16)), 5, false, 0, 0);
+ }
+ change(id, "UPSERT", record(name, "SOA", 60, null));
+ assertHeader(query(request("missing." + name, 16)), 5, false, 0, 0);
+ }
+
+ @Test
+ void txtSegmentsAndTruncationRetainCompleteWireRecords() throws Exception {
+ String name = uniqueName() + ".example";
+ String id = createZone(name);
+ String value = "\"a b\" \"\\\"\\\\\\377\" \"\"";
+ change(id, "CREATE", record("text." + name, "TXT", 90, value));
+ byte[] request = request("text." + name, 16);
+ byte[] response = query(request);
+ assertArrayEquals(new byte[]{3, 'a', ' ', 'b', 3, '"', '\\', (byte) 255, 0},
+ Arrays.copyOfRange(response, request.length + 12, response.length));
+ change(id, "UPSERT", record("text." + name, "TXT", 90,
+ "\"" + "x".repeat(255) + "\" \"" + "y".repeat(255) + "\""));
+ byte[] truncated = query(request);
+ assertTrue(truncated.length <= 512);
+ assertTrue((ByteBuffer.wrap(truncated).getShort(2) & 0x0200) != 0);
+ assertEquals(0, ByteBuffer.wrap(truncated).getShort(6));
+ ByteBuffer edns = ByteBuffer.allocate(request.length + 11).put(request);
+ edns.putShort(10, (short) 1).put((byte) 0).putShort((short) 41).putShort((short) 1232)
+ .putInt(0).putShort((short) 0);
+ assertHeader(query(edns.array()), 0, true, 1, 0);
+ }
+
+ private String createZone(String name) {
+ String id = route53.createHostedZone(name, UUID.randomUUID().toString(), null, null).zone().getId();
+ zoneIds.add(id);
+ return id;
+ }
+
+ private void change(String id, String action, ResourceRecordSet record) {
+ route53.changeResourceRecordSets(id, List.of(Map.of("action", action, "rrs", record)), null);
+ }
+
+ private static ResourceRecordSet record(String name, String type, long ttl, String value) {
+ ResourceRecordSet record = new ResourceRecordSet();
+ record.setName(name);
+ record.setType(type);
+ record.setTtl(ttl);
+ record.setRecords(List.of(new ResourceRecord(value)));
+ return record;
+ }
+
+ private static String uniqueName() {
+ return "dns-" + UUID.randomUUID().toString().substring(0, 8);
+ }
+
+ private static byte[] request(String name, int type) {
+ byte[] encoded = DnsRecord.encodeName(name);
+ return ByteBuffer.allocate(16 + encoded.length).putShort((short) 0x1234).putShort((short) 0x0100)
+ .putShort((short) 1).putShort((short) 0).putShort((short) 0).putShort((short) 0)
+ .put(encoded).putShort((short) type).putShort((short) 1).array();
+ }
+
+ private static void assertHeader(byte[] response, int rcode, boolean authoritative, int answers, int authorities) {
+ ByteBuffer packet = ByteBuffer.wrap(response);
+ assertEquals(rcode, packet.getShort(2) & 15);
+ assertEquals(authoritative, (packet.getShort(2) & 0x0400) != 0);
+ assertEquals(0, packet.getShort(2) & 0x0080, "public authority does not advertise recursion");
+ assertEquals(answers, packet.getShort(6));
+ assertEquals(authorities, packet.getShort(8));
+ }
+
+ private static void assertNegative(byte[] response, String zone, int rcode, int ttl) {
+ assertHeader(response, rcode, true, 0, 1);
+ ByteBuffer packet = ByteBuffer.wrap(response);
+ packet.position(12);
+ EmbeddedDnsServer.readName(packet, response);
+ packet.getInt();
+ assertEquals(zone, EmbeddedDnsServer.readName(packet, response));
+ assertEquals(6, packet.getShort());
+ assertEquals(1, packet.getShort());
+ assertEquals(ttl, packet.getInt());
+ int length = Short.toUnsignedInt(packet.getShort());
+ assertEquals(length, packet.remaining());
+ }
+
+ private byte[] query(byte[] request) throws Exception {
+ EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of("amazonaws.com"), List.of(source));
+ 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);
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java
index e12de5be20..cc21c1524a 100644
--- a/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/route53/Route53ServiceTest.java
@@ -39,7 +39,7 @@ class Route53ServiceTest {
StorageFactory storageFactory = Mockito.mock(StorageFactory.class);
Mockito.when(storageFactory.create(Mockito.anyString(), Mockito.anyString(), Mockito.any()))
.thenAnswer(invocation -> {
- AccountAwareStorageBackend<Object> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
+ AccountAwareStorageBackend<Object> store = Mockito.spy(AccountAwareStorageBackend.inMemory(ACCOUNT));
stores.put(invocation.getArgument(1), store);
return store;
});
@@ -64,6 +64,27 @@ class Route53ServiceTest {
return new Route53Service(storageFactory, config, regionResolver, ec2Service);
}
+ @Test
+ void publicZoneIndexAvoidsStorageScansOutsideOwnedNamesAndTracksDeletion() {
+ Route53Service service = newService();
+ AccountAwareStorageBackend<?> zones = stores.get("route53-zones.json");
+ Mockito.clearInvocations(zones);
+ assertTrue(service.publicDnsZones("outside.example").isEmpty());
+ Mockito.verifyNoInteractions(zones);
+ String first = service.createHostedZone("owned.example", "first", null, null).zone().getId();
+ String second = service.createHostedZone("owned.example", "second", null, null).zone().getId();
+ Mockito.clearInvocations(zones);
+ assertTrue(service.publicDnsZones("outside.example").isEmpty());
+ Mockito.verifyNoInteractions(zones);
+ assertEquals(2, service.publicDnsZones("text.owned.example").size());
+ service.deleteHostedZone(first);
+ assertEquals(1, service.publicDnsZones("text.owned.example").size());
+ service.deleteHostedZone(second);
+ Mockito.clearInvocations(zones);
+ assertTrue(service.publicDnsZones("text.owned.example").isEmpty());
+ Mockito.verifyNoInteractions(zones);
+ }
+
private static Map<String, Object> change(String action, ResourceRecordSet rrs) {
Map<String, Object> m = new HashMap<>();
m.put("action", action);