mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 15:49:33 -05:00
feat(route53): resolve private hosted zone records from cluster containers (#4353)
Implement DnsRecordSource SPI via Route53DnsRecordSource to decouple Route 53 resolution from EmbeddedDnsServer. Add DnsLookupHelper in core.common.dns for external IPv4 resolution via upstream forwarders with system fallback, shared by Route53DnsRecordSource for CNAME and ALIAS chasing. Discover private hosted zones via Route53Service and support in-zone chasing, built-in Floci suffixes, and EC2 internal names. Authoritatively resolve A records within private zones to prevent upstream query leakage. Wire EKS cluster containers to embedded DNS via specBuilder.withEmbeddedDns().
This commit is contained in:
1 parent
84363f9570
commit
4032efd9c7
15 files changed
+1401
-52
No files matched your search
@@ -3173,6 +3173,13 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean podIdentityWebhook();
|
||||
|
||||
/**
|
||||
* When true, configures cluster containers with Floci's embedded DNS server so that
|
||||
* Route 53 private hosted zone records resolve from inside cluster pods.
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean embeddedDns();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
package io.github.hectorvent.floci.core.common.dns;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Resolves external hostnames to IPv4 addresses using upstream DNS servers
|
||||
* with fallback to system name resolution.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DnsLookupHelper {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DnsLookupHelper.class);
|
||||
private static final int MAX_CNAME_DEPTH = 8;
|
||||
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private final List<String> upstreamServers;
|
||||
|
||||
public DnsLookupHelper() {
|
||||
this((EmulatorConfig) null);
|
||||
}
|
||||
|
||||
@Inject
|
||||
public DnsLookupHelper(EmulatorConfig config) {
|
||||
List<String> fallbacks = config != null && config.dns() != null
|
||||
? config.dns().containerFallbackServers()
|
||||
: null;
|
||||
this.upstreamServers = EmbeddedDnsServer.composeUpstreams(
|
||||
EmbeddedDnsServer.readResolvConfNameservers(), fallbacks);
|
||||
}
|
||||
|
||||
DnsLookupHelper(List<String> upstreamServers) {
|
||||
this.upstreamServers = upstreamServers != null ? List.copyOf(upstreamServers) : List.of();
|
||||
}
|
||||
|
||||
public List<String> resolveIpv4(String target) {
|
||||
if (target == null || target.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
List<String> forwarderResults = resolveViaForwarders(target);
|
||||
if (!forwarderResults.isEmpty()) {
|
||||
return forwarderResults;
|
||||
}
|
||||
List<String> results = new ArrayList<>();
|
||||
try {
|
||||
for (InetAddress addr : InetAddress.getAllByName(target)) {
|
||||
if (addr instanceof Inet4Address && isIpv4(addr.getHostAddress())) {
|
||||
results.add(addr.getHostAddress());
|
||||
}
|
||||
}
|
||||
} catch (Exception expected) {
|
||||
LOG.debugv("Failed to resolve external target {0}: {1}", target, expected.getMessage());
|
||||
}
|
||||
return List.copyOf(results);
|
||||
}
|
||||
|
||||
private List<String> resolveViaForwarders(String target) {
|
||||
if (upstreamServers.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
short txId = (short) random.nextInt(1 << 16);
|
||||
byte[] query = buildQuery(target, txId, (short) 1);
|
||||
try {
|
||||
byte[] response = EmbeddedDnsServer.forwardToUpstreams(
|
||||
query, upstreamServers, EmbeddedDnsServer.DNS_PORT);
|
||||
return parseARecordsFromDnsResponse(response, response.length, txId, target);
|
||||
} catch (Exception expected) {
|
||||
LOG.debugv("DNS query to upstreams for {0} failed: {1}", target, expected.getMessage());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] buildQuery(String qname, short txId, short qtype) {
|
||||
ByteBuffer buf = ByteBuffer.allocate(512);
|
||||
buf.putShort(txId);
|
||||
buf.putShort((short) 0x0100); // QR=0, RD=1
|
||||
buf.putShort((short) 1); // qdcount=1
|
||||
buf.putShort((short) 0);
|
||||
buf.putShort((short) 0);
|
||||
buf.putShort((short) 0);
|
||||
|
||||
for (String label : qname.split("\\.")) {
|
||||
if (!label.isEmpty()) {
|
||||
byte[] bytes = label.getBytes(StandardCharsets.US_ASCII);
|
||||
buf.put((byte) bytes.length);
|
||||
buf.put(bytes);
|
||||
}
|
||||
}
|
||||
buf.put((byte) 0);
|
||||
buf.putShort(qtype);
|
||||
buf.putShort((short) 1); // class IN
|
||||
|
||||
byte[] query = new byte[buf.position()];
|
||||
System.arraycopy(buf.array(), 0, query, 0, query.length);
|
||||
return query;
|
||||
}
|
||||
|
||||
static List<String> parseARecordsFromDnsResponse(
|
||||
byte[] response, int length, short expectedTxId, String expectedTarget) {
|
||||
if (response == null || length < 12) {
|
||||
return List.of();
|
||||
}
|
||||
ByteBuffer buf = ByteBuffer.wrap(response, 0, length);
|
||||
short txId = buf.getShort();
|
||||
if (txId != expectedTxId) {
|
||||
return List.of();
|
||||
}
|
||||
short flags = buf.getShort();
|
||||
if ((flags & 0x8000) == 0) {
|
||||
return List.of();
|
||||
}
|
||||
int rcode = flags & 0x000F;
|
||||
if (rcode != 0) {
|
||||
return List.of();
|
||||
}
|
||||
int qdCount = buf.getShort() & 0xFFFF;
|
||||
int anCount = buf.getShort() & 0xFFFF;
|
||||
buf.getShort(); // nsCount
|
||||
buf.getShort(); // arCount
|
||||
|
||||
if (qdCount > 0) {
|
||||
String questionName = EmbeddedDnsServer.readName(buf, response);
|
||||
buf.getShort(); // qtype
|
||||
buf.getShort(); // qclass
|
||||
if (!normalizeTarget(questionName).equalsIgnoreCase(normalizeTarget(expectedTarget))) {
|
||||
return List.of();
|
||||
}
|
||||
for (int i = 1; i < qdCount; i++) {
|
||||
EmbeddedDnsServer.readName(buf, response);
|
||||
buf.getShort();
|
||||
buf.getShort();
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> cnames = new HashMap<>();
|
||||
Map<String, List<String>> aRecords = new HashMap<>();
|
||||
|
||||
for (int i = 0; i < anCount && buf.hasRemaining(); i++) {
|
||||
String rName = normalizeTarget(EmbeddedDnsServer.readName(buf, response)).toLowerCase();
|
||||
if (!buf.hasRemaining()) {
|
||||
break;
|
||||
}
|
||||
short rType = buf.getShort();
|
||||
if (!buf.hasRemaining()) {
|
||||
break;
|
||||
}
|
||||
buf.getShort(); // rClass
|
||||
if (buf.remaining() < 6) {
|
||||
break;
|
||||
}
|
||||
buf.getInt(); // ttl
|
||||
int rdLength = buf.getShort() & 0xFFFF;
|
||||
if (buf.remaining() < rdLength) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (rType == 1 && rdLength == 4) {
|
||||
int b1 = buf.get() & 0xFF;
|
||||
int b2 = buf.get() & 0xFF;
|
||||
int b3 = buf.get() & 0xFF;
|
||||
int b4 = buf.get() & 0xFF;
|
||||
String ip = b1 + "." + b2 + "." + b3 + "." + b4;
|
||||
aRecords.computeIfAbsent(rName, k -> new ArrayList<>()).add(ip);
|
||||
} else if (rType == 5) {
|
||||
ByteBuffer rdataBuf = buf.slice();
|
||||
rdataBuf.limit(rdLength);
|
||||
String cnameTarget = normalizeTarget(EmbeddedDnsServer.readName(rdataBuf, response)).toLowerCase();
|
||||
if (!cnameTarget.isEmpty()) {
|
||||
cnames.put(rName, cnameTarget);
|
||||
}
|
||||
buf.position(buf.position() + rdLength);
|
||||
} else {
|
||||
buf.position(buf.position() + rdLength);
|
||||
}
|
||||
}
|
||||
|
||||
String current = normalizeTarget(expectedTarget).toLowerCase();
|
||||
Set<String> visited = new HashSet<>();
|
||||
for (int depth = 0; depth < MAX_CNAME_DEPTH && visited.add(current); depth++) {
|
||||
List<String> directA = aRecords.get(current);
|
||||
if (directA != null && !directA.isEmpty()) {
|
||||
return directA;
|
||||
}
|
||||
String next = cnames.get(current);
|
||||
if (next == null) {
|
||||
break;
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private static String normalizeTarget(String s) {
|
||||
if (s == null) {
|
||||
return "";
|
||||
}
|
||||
String trimmed = s.trim();
|
||||
return trimmed.endsWith(".") ? trimmed.substring(0, trimmed.length() - 1) : trimmed;
|
||||
}
|
||||
|
||||
private static boolean isIpv4(String s) {
|
||||
if (s == null || s.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String[] parts = s.split("\\.");
|
||||
if (parts.length != 4) {
|
||||
return false;
|
||||
}
|
||||
for (String part : parts) {
|
||||
try {
|
||||
int n = Integer.parseInt(part);
|
||||
if (n < 0 || n > 255) {
|
||||
return false;
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
@@ -50,7 +51,7 @@ import java.util.regex.Pattern;
|
||||
public class EmbeddedDnsServer {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EmbeddedDnsServer.class);
|
||||
private static final int DNS_PORT = 53;
|
||||
static final int DNS_PORT = 53;
|
||||
private static final int TTL = 60;
|
||||
private static final String FALLBACK_UPSTREAM = "127.0.0.11";
|
||||
// EDNS0-capable resolvers (Node/c-ares, glibc) advertise UDP payloads well above the
|
||||
@@ -255,7 +256,14 @@ public class EmbeddedDnsServer {
|
||||
return Optional.of(address.toString());
|
||||
}
|
||||
|
||||
String readName(ByteBuffer buf, byte[] data) {
|
||||
static String readName(ByteBuffer buf, byte[] data) {
|
||||
return readName(buf, data, 0);
|
||||
}
|
||||
|
||||
private static String readName(ByteBuffer buf, byte[] data, int depth) {
|
||||
if (depth > 16) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int safety = 0;
|
||||
while (buf.hasRemaining() && safety++ < 128) {
|
||||
@@ -265,21 +273,31 @@ public class EmbeddedDnsServer {
|
||||
}
|
||||
if ((len & 0xC0) == 0xC0) {
|
||||
// compression pointer
|
||||
if (!buf.hasRemaining()) {
|
||||
break;
|
||||
}
|
||||
int offset = ((len & 0x3F) << 8) | (buf.get() & 0xFF);
|
||||
if (offset >= data.length) {
|
||||
break;
|
||||
}
|
||||
ByteBuffer ptr = ByteBuffer.wrap(data);
|
||||
ptr.position(offset);
|
||||
if (sb.length() > 0) {
|
||||
sb.append('.');
|
||||
}
|
||||
sb.append(readName(ptr, data));
|
||||
sb.append(readName(ptr, data, depth + 1));
|
||||
return sb.toString();
|
||||
}
|
||||
if (buf.remaining() < len) {
|
||||
buf.position(buf.limit());
|
||||
break;
|
||||
}
|
||||
if (sb.length() > 0) {
|
||||
sb.append('.');
|
||||
}
|
||||
byte[] label = new byte[len];
|
||||
buf.get(label);
|
||||
sb.append(new String(label));
|
||||
sb.append(new String(label, StandardCharsets.US_ASCII));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
@@ -336,7 +354,7 @@ public class EmbeddedDnsServer {
|
||||
* Throws if every upstream times out or errors, so the caller can log a single warning.
|
||||
* The {@code upstreamPort} is parameterised for tests; production always uses {@link #DNS_PORT}.
|
||||
*/
|
||||
byte[] forwardToUpstreams(byte[] query, List<String> upstreams, int upstreamPort) throws Exception {
|
||||
static byte[] forwardToUpstreams(byte[] query, List<String> upstreams, int upstreamPort) throws Exception {
|
||||
Exception last = null;
|
||||
for (String upstream : upstreams) {
|
||||
try (java.net.DatagramSocket fwd = new java.net.DatagramSocket()) {
|
||||
@@ -386,13 +404,16 @@ public class EmbeddedDnsServer {
|
||||
return server != null && !server.isBlank() && !server.trim().equals("127.0.0.1");
|
||||
}
|
||||
|
||||
private List<String> readResolvConfNameservers() {
|
||||
static List<String> readResolvConfNameservers() {
|
||||
List<String> servers = new ArrayList<>();
|
||||
try {
|
||||
for (String line : Files.readAllLines(Path.of("/etc/resolv.conf"))) {
|
||||
line = line.trim();
|
||||
if (line.startsWith("nameserver ")) {
|
||||
servers.add(line.substring("nameserver ".length()).trim());
|
||||
Path path = Path.of("/etc/resolv.conf");
|
||||
if (Files.exists(path)) {
|
||||
for (String line : Files.readAllLines(path)) {
|
||||
line = line.trim();
|
||||
if (line.startsWith("nameserver ")) {
|
||||
servers.add(line.substring("nameserver ".length()).trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -360,6 +360,10 @@ public class EksClusterManager implements ClusterNodeInstanceProvider {
|
||||
.withLabels(ContainerStorageHelper.resourceIdentityLabels(
|
||||
"eks", cluster.getName(), labelAccountId, clusterRegion(cluster)));
|
||||
|
||||
if (config.services().eks().embeddedDns()) {
|
||||
specBuilder.withEmbeddedDns();
|
||||
}
|
||||
|
||||
if (config.services().eks().ecrRegistryMirror() && config.services().ecr().enabled()) {
|
||||
specBuilder.withHostDockerInternalOnLinux();
|
||||
}
|
||||
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package io.github.hectorvent.floci.services.route53;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.dns.DnsLookupHelper;
|
||||
import io.github.hectorvent.floci.core.common.dns.DnsRecordSource;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.services.route53.model.AliasTarget;
|
||||
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
|
||||
import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Resolves Route 53 private hosted zone 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.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class Route53DnsRecordSource implements DnsRecordSource {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(Route53DnsRecordSource.class);
|
||||
private static final int MAX_CNAME_DEPTH = 8;
|
||||
private static final int MAX_DNS_ANSWERS = 8;
|
||||
private static final Pattern EC2_PRIVATE_DNS_NAME =
|
||||
Pattern.compile("^ip-(\\d{1,3})-(\\d{1,3})-(\\d{1,3})-(\\d{1,3})\\.ec2\\.internal$", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
private static final List<String> BUILTIN_SUFFIXES = EmbeddedDnsServer.BUILTIN_SUFFIXES;
|
||||
|
||||
private final Route53Service route53Service;
|
||||
private final DnsLookupHelper dnsLookupHelper;
|
||||
private final Set<String> flociSuffixes = new LinkedHashSet<>();
|
||||
|
||||
public Route53DnsRecordSource(Route53Service route53Service) {
|
||||
this(route53Service, null, new DnsLookupHelper());
|
||||
}
|
||||
|
||||
public Route53DnsRecordSource(Route53Service route53Service, EmulatorConfig config) {
|
||||
this(route53Service, config, new DnsLookupHelper(config));
|
||||
}
|
||||
|
||||
@Inject
|
||||
public Route53DnsRecordSource(Route53Service route53Service, EmulatorConfig config, DnsLookupHelper dnsLookupHelper) {
|
||||
this.route53Service = route53Service;
|
||||
this.dnsLookupHelper = dnsLookupHelper != null ? dnsLookupHelper : new DnsLookupHelper(config);
|
||||
this.flociSuffixes.addAll(BUILTIN_SUFFIXES);
|
||||
if (config != null) {
|
||||
config.hostname().ifPresent(this.flociSuffixes::add);
|
||||
if (config.dns() != null) {
|
||||
config.dns().extraSuffixes().ifPresent(this.flociSuffixes::addAll);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<List<String>> resolveIpv4(String name) {
|
||||
if (name == null || name.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!route53Service.isCoveredByPrivateZone(name)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
List<String> addresses = resolveAddresses(name, new HashSet<>(), 0);
|
||||
if (addresses.size() > MAX_DNS_ANSWERS) {
|
||||
addresses = addresses.subList(0, MAX_DNS_ANSWERS);
|
||||
}
|
||||
return Optional.of(addresses);
|
||||
}
|
||||
|
||||
private List<String> resolveAddresses(String qname, Set<String> visited, int depth) {
|
||||
if (depth > MAX_CNAME_DEPTH) {
|
||||
return List.of();
|
||||
}
|
||||
String normalized = Route53Service.normalizeName(qname).toLowerCase();
|
||||
if (!visited.add(normalized)) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
List<ResourceRecordSet> recordSets = route53Service.findPrivateRecordsForName(qname);
|
||||
if (recordSets.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// 1. Direct A records
|
||||
Set<String> addresses = new LinkedHashSet<>();
|
||||
for (ResourceRecordSet rrs : recordSets) {
|
||||
if ("A".equalsIgnoreCase(rrs.getType())) {
|
||||
if (rrs.getRecords() != null) {
|
||||
for (ResourceRecord rr : rrs.getRecords()) {
|
||||
String val = rr.getValue();
|
||||
if (isIpv4(val)) {
|
||||
addresses.add(val.trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
AliasTarget alias = rrs.getAliasTarget();
|
||||
if (alias != null && alias.getDnsName() != null && !alias.getDnsName().isBlank()) {
|
||||
String cleanAlias = alias.getDnsName().trim();
|
||||
if (cleanAlias.endsWith(".")) {
|
||||
cleanAlias = cleanAlias.substring(0, cleanAlias.length() - 1);
|
||||
}
|
||||
if (route53Service.isCoveredByPrivateZone(cleanAlias)) {
|
||||
addresses.addAll(resolveAddresses(cleanAlias, visited, depth + 1));
|
||||
} else if (matchesFlociSuffix(cleanAlias)) {
|
||||
getLocalFlociAddress().ifPresent(addresses::add);
|
||||
} else {
|
||||
Optional<String> ec2Ip = resolveEc2PrivateDnsName(cleanAlias);
|
||||
if (ec2Ip.isPresent()) {
|
||||
addresses.add(ec2Ip.get());
|
||||
} else {
|
||||
addresses.addAll(dnsLookupHelper.resolveIpv4(cleanAlias));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!addresses.isEmpty()) {
|
||||
return List.copyOf(addresses);
|
||||
}
|
||||
|
||||
// 2. CNAME records
|
||||
for (ResourceRecordSet rrs : recordSets) {
|
||||
if ("CNAME".equalsIgnoreCase(rrs.getType())) {
|
||||
if (rrs.getRecords() != null && !rrs.getRecords().isEmpty()) {
|
||||
String target = rrs.getRecords().get(0).getValue();
|
||||
if (target != null && !target.isBlank()) {
|
||||
String cleanTarget = target.trim();
|
||||
if (cleanTarget.endsWith(".")) {
|
||||
cleanTarget = cleanTarget.substring(0, cleanTarget.length() - 1);
|
||||
}
|
||||
if (route53Service.isCoveredByPrivateZone(cleanTarget)) {
|
||||
return resolveAddresses(cleanTarget, visited, depth + 1);
|
||||
}
|
||||
if (matchesFlociSuffix(cleanTarget)) {
|
||||
return getLocalFlociAddress().map(List::of).orElse(List.of());
|
||||
}
|
||||
Optional<String> ec2Ip = resolveEc2PrivateDnsName(cleanTarget);
|
||||
if (ec2Ip.isPresent()) {
|
||||
return List.of(ec2Ip.get());
|
||||
}
|
||||
return dnsLookupHelper.resolveIpv4(cleanTarget);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private boolean matchesFlociSuffix(String name) {
|
||||
if (name == null || name.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String lower = name.toLowerCase();
|
||||
for (String suffix : flociSuffixes) {
|
||||
String s = suffix.toLowerCase();
|
||||
if (lower.equals(s) || lower.endsWith("." + s)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private Optional<String> getLocalFlociAddress() {
|
||||
try {
|
||||
return Optional.of(InetAddress.getLocalHost().getHostAddress());
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Failed to determine local host address: {0}", e.getMessage());
|
||||
return Optional.of("127.0.0.1");
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<String> resolveEc2PrivateDnsName(String name) {
|
||||
if (name == null || name.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Matcher matcher = EC2_PRIVATE_DNS_NAME.matcher(name);
|
||||
if (!matcher.matches()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
StringBuilder address = new StringBuilder();
|
||||
for (int i = 1; i <= 4; i++) {
|
||||
int octet = Integer.parseInt(matcher.group(i));
|
||||
if (octet > 255) {
|
||||
return Optional.empty();
|
||||
}
|
||||
if (i > 1) {
|
||||
address.append('.');
|
||||
}
|
||||
address.append(octet);
|
||||
}
|
||||
return Optional.of(address.toString());
|
||||
}
|
||||
|
||||
private static boolean isIpv4(String s) {
|
||||
if (s == null || s.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String[] parts = s.trim().split("\\.", -1);
|
||||
if (parts.length != 4) {
|
||||
return false;
|
||||
}
|
||||
for (String part : parts) {
|
||||
try {
|
||||
int n = Integer.parseInt(part);
|
||||
if (n < 0 || n > 255) {
|
||||
return false;
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
|
||||
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.Resettable;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
@@ -27,12 +28,13 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@ApplicationScoped
|
||||
public class Route53Service {
|
||||
public class Route53Service implements Resettable {
|
||||
|
||||
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
@@ -55,6 +57,7 @@ public class Route53Service {
|
||||
private final long vpcAssociationControlPlaneDelayMs;
|
||||
private final Map<String, Long> hostedZoneMutationBusyUntilNanos = new ConcurrentHashMap<>();
|
||||
private final Map<String, Long> authorizationMutationBusyUntilNanos = new ConcurrentHashMap<>();
|
||||
private final Map<String, Integer> privateZoneNameCounts = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public Route53Service(StorageFactory factory, EmulatorConfig config, RegionResolver regionResolver,
|
||||
@@ -83,6 +86,11 @@ public class Route53Service {
|
||||
this.regionResolver = regionResolver;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Hosted Zones ──────────────────────────────────────────────────────────
|
||||
@@ -105,6 +113,7 @@ public class Route53Service {
|
||||
zone.setOwnerAccountId(callerAccountId);
|
||||
if (vpcAssociation != null) {
|
||||
vpcAssociation.setOwnerAccountId(callerAccountId);
|
||||
privateZoneNameCounts.merge(normalizedName.toLowerCase(), 1, Integer::sum);
|
||||
}
|
||||
zoneStore.put(id, zone);
|
||||
recordStore.put(id, buildDefaultRecords(normalizedName));
|
||||
@@ -134,6 +143,10 @@ public class Route53Service {
|
||||
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);
|
||||
}
|
||||
return newChange(null);
|
||||
}
|
||||
|
||||
@@ -574,6 +587,108 @@ public class Route53Service {
|
||||
.toList();
|
||||
}
|
||||
|
||||
public boolean isCoveredByPrivateZone(String qname) {
|
||||
if (qname == null || qname.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String normalizedQname = normalizeName(qname).toLowerCase();
|
||||
if (privateZoneNameCounts.isEmpty()
|
||||
|| privateZoneNameCounts.keySet().stream().noneMatch(z -> normalizedQname.equals(z) || normalizedQname.endsWith("." + z))) {
|
||||
return false;
|
||||
}
|
||||
for (OwnedZone owned : allHostedZonesAcrossAccounts()) {
|
||||
HostedZone zone = owned.zone();
|
||||
if (!zone.isPrivateZone()) {
|
||||
continue;
|
||||
}
|
||||
String zoneName = normalizeName(zone.getName()).toLowerCase();
|
||||
if (normalizedQname.equals(zoneName) || normalizedQname.endsWith("." + zoneName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public List<ResourceRecordSet> findPrivateRecordsForName(String qname) {
|
||||
if (qname == null || qname.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
String normalizedQname = normalizeName(qname).toLowerCase();
|
||||
if (privateZoneNameCounts.isEmpty()
|
||||
|| privateZoneNameCounts.keySet().stream().noneMatch(z -> normalizedQname.equals(z) || normalizedQname.endsWith("." + z))) {
|
||||
return List.of();
|
||||
}
|
||||
List<OwnedZone> matchingZones = new ArrayList<>();
|
||||
for (OwnedZone owned : allHostedZonesAcrossAccounts()) {
|
||||
HostedZone zone = owned.zone();
|
||||
if (!zone.isPrivateZone()) {
|
||||
continue;
|
||||
}
|
||||
String zoneName = normalizeName(zone.getName()).toLowerCase();
|
||||
if (normalizedQname.equals(zoneName) || normalizedQname.endsWith("." + zoneName)) {
|
||||
matchingZones.add(owned);
|
||||
}
|
||||
}
|
||||
matchingZones.sort((a, b) -> Integer.compare(
|
||||
normalizeName(b.zone().getName()).length(),
|
||||
normalizeName(a.zone().getName()).length()));
|
||||
|
||||
if (matchingZones.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
// Only search the most-specific matching zone(s) to avoid leaking parent zone records
|
||||
int maxZoneLength = normalizeName(matchingZones.get(0).zone().getName()).length();
|
||||
List<ResourceRecordSet> nameMatches = new ArrayList<>();
|
||||
List<ResourceRecordSet> wildcardMatches = new ArrayList<>();
|
||||
|
||||
for (OwnedZone owned : matchingZones) {
|
||||
if (normalizeName(owned.zone().getName()).length() < maxZoneLength) {
|
||||
break;
|
||||
}
|
||||
List<ResourceRecordSet> records = getRecordsForZoneAcrossAccounts(owned.accountId(), owned.zone().getId());
|
||||
List<ResourceRecordSet> zoneWildcards = new ArrayList<>();
|
||||
for (ResourceRecordSet rrs : records) {
|
||||
String rName = normalizeName(rrs.getName()).toLowerCase();
|
||||
if (rName.equals(normalizedQname)) {
|
||||
nameMatches.add(rrs);
|
||||
} else if (rName.startsWith("*.")) {
|
||||
zoneWildcards.add(rrs);
|
||||
}
|
||||
}
|
||||
if (nameMatches.isEmpty()) {
|
||||
for (ResourceRecordSet rrs : zoneWildcards) {
|
||||
String rName = normalizeName(rrs.getName()).toLowerCase();
|
||||
String wildcardSuffix = rName.substring(2); // e.g. "corp.internal."
|
||||
if (normalizedQname.endsWith("." + wildcardSuffix)) {
|
||||
// Wildcard cannot match beneath an existing closer name in the same zone (RFC 1034 4.3.3)
|
||||
boolean closerNameExists = records.stream()
|
||||
.map(r -> normalizeName(r.getName()).toLowerCase())
|
||||
.filter(n -> !n.startsWith("*."))
|
||||
.anyMatch(n -> n.length() > wildcardSuffix.length()
|
||||
&& (normalizedQname.equals(n) || normalizedQname.endsWith("." + n)));
|
||||
if (!closerNameExists) {
|
||||
wildcardMatches.add(rrs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return !nameMatches.isEmpty() ? nameMatches : wildcardMatches;
|
||||
}
|
||||
|
||||
private List<ResourceRecordSet> getRecordsForZoneAcrossAccounts(String accountId, String zoneId) {
|
||||
if (recordStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
AccountAwareStorageBackend<List<ResourceRecordSet>> accountAware =
|
||||
(AccountAwareStorageBackend<List<ResourceRecordSet>>) rawAccountAware;
|
||||
return accountAware.getForAccount(accountId, zoneId)
|
||||
.or(() -> accountAware.findAnyAccount(zoneId))
|
||||
.orElse(List.of());
|
||||
}
|
||||
return recordStore.get(zoneId).orElse(List.of());
|
||||
}
|
||||
|
||||
private void putZoneForAccount(String accountId, String zoneId, HostedZone zone) {
|
||||
if (zoneStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
|
||||
@SuppressWarnings("unchecked")
|
||||
@@ -702,7 +817,7 @@ public class Route53Service {
|
||||
+ TimeUnit.MILLISECONDS.toNanos(vpcAssociationControlPlaneDelayMs));
|
||||
}
|
||||
|
||||
private static String normalizeName(String name) {
|
||||
public static String normalizeName(String name) {
|
||||
if (name == null || name.isEmpty()) return name;
|
||||
return name.endsWith(".") ? name : name + ".";
|
||||
}
|
||||
@@ -858,4 +973,11 @@ public class Route53Service {
|
||||
List<String> bv = b == null ? List.of() : b.stream().map(ResourceRecord::getValue).sorted().toList();
|
||||
return av.equals(bv);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
hostedZoneMutationBusyUntilNanos.clear();
|
||||
authorizationMutationBusyUntilNanos.clear();
|
||||
privateZoneNameCounts.clear();
|
||||
}
|
||||
}
|
||||
@@ -649,6 +649,7 @@ floci:
|
||||
imds-pod-network: false # route link-local IMDS traffic from ordinary pod network namespaces (requires imds: true)
|
||||
irsa-signing-key: true # sign k3s service account tokens with the cluster OIDC key
|
||||
pod-identity-webhook: true # register a mutating webhook that injects pod identity credentials (needs floci.tls.enabled)
|
||||
embedded-dns: true # point cluster containers at Floci's embedded DNS to resolve Route 53 private zones
|
||||
mwaa:
|
||||
enabled: true
|
||||
mock: false
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package io.github.hectorvent.floci.core.common.dns;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class DnsLookupHelperTest {
|
||||
|
||||
@Test
|
||||
void parseARecordsRejectsMismatchedTxId() {
|
||||
byte[] resp = buildSyntheticDnsResponse((short) 100, "example.com", "93.184.216.34");
|
||||
List<String> result = DnsLookupHelper.parseARecordsFromDnsResponse(
|
||||
resp, resp.length, (short) 200, "example.com");
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseARecordsRejectsMismatchedQuestionName() {
|
||||
byte[] resp = buildSyntheticDnsResponse((short) 100, "other.com", "93.184.216.34");
|
||||
List<String> result = DnsLookupHelper.parseARecordsFromDnsResponse(
|
||||
resp, resp.length, (short) 100, "example.com");
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseARecordsAcceptsValidMatchingResponse() {
|
||||
byte[] resp = buildSyntheticDnsResponse((short) 100, "example.com", "93.184.216.34");
|
||||
List<String> result = DnsLookupHelper.parseARecordsFromDnsResponse(
|
||||
resp, resp.length, (short) 100, "example.com");
|
||||
assertEquals(List.of("93.184.216.34"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseARecordsAcceptsCnameTargetBeforeCnameRecord() {
|
||||
ByteBuffer buf = ByteBuffer.allocate(512);
|
||||
short txId = 100;
|
||||
buf.putShort(txId);
|
||||
buf.putShort((short) 0x8180);
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 2);
|
||||
buf.putShort((short) 0);
|
||||
buf.putShort((short) 0);
|
||||
|
||||
writeDnsName(buf, "alias.com");
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 1);
|
||||
|
||||
writeDnsName(buf, "target.com");
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 1);
|
||||
buf.putInt(300);
|
||||
buf.putShort((short) 4);
|
||||
buf.put((byte) 93);
|
||||
buf.put((byte) 184);
|
||||
buf.put((byte) 216);
|
||||
buf.put((byte) 34);
|
||||
|
||||
writeDnsName(buf, "alias.com");
|
||||
buf.putShort((short) 5);
|
||||
buf.putShort((short) 1);
|
||||
buf.putInt(300);
|
||||
int rdLengthPos = buf.position();
|
||||
buf.putShort((short) 0);
|
||||
int rdataStart = buf.position();
|
||||
writeDnsName(buf, "target.com");
|
||||
int rdataEnd = buf.position();
|
||||
buf.putShort(rdLengthPos, (short) (rdataEnd - rdataStart));
|
||||
|
||||
byte[] resp = new byte[buf.position()];
|
||||
System.arraycopy(buf.array(), 0, resp, 0, resp.length);
|
||||
|
||||
List<String> result = DnsLookupHelper.parseARecordsFromDnsResponse(
|
||||
resp, resp.length, txId, "alias.com");
|
||||
assertEquals(List.of("93.184.216.34"), result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseARecordsHandlesCyclicCompressionPointersWithoutStackOverflow() {
|
||||
ByteBuffer buf = ByteBuffer.allocate(512);
|
||||
short txId = 100;
|
||||
buf.putShort(txId);
|
||||
buf.putShort((short) 0x8180);
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 0);
|
||||
buf.putShort((short) 0);
|
||||
buf.putShort((short) 0);
|
||||
|
||||
int cycleOffset = buf.position();
|
||||
buf.putShort((short) (0xC000 | cycleOffset));
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 1);
|
||||
|
||||
byte[] resp = new byte[buf.position()];
|
||||
System.arraycopy(buf.array(), 0, resp, 0, resp.length);
|
||||
|
||||
List<String> result = DnsLookupHelper.parseARecordsFromDnsResponse(
|
||||
resp, resp.length, txId, "example.com");
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
private void writeDnsName(ByteBuffer buf, String name) {
|
||||
for (String label : name.split("\\.")) {
|
||||
byte[] bytes = label.getBytes(StandardCharsets.US_ASCII);
|
||||
buf.put((byte) bytes.length);
|
||||
buf.put(bytes);
|
||||
}
|
||||
buf.put((byte) 0);
|
||||
}
|
||||
|
||||
private byte[] buildSyntheticDnsResponse(short txId, String questionName, String ip) {
|
||||
ByteBuffer buf = ByteBuffer.allocate(512);
|
||||
buf.putShort(txId);
|
||||
buf.putShort((short) 0x8180);
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 0);
|
||||
buf.putShort((short) 0);
|
||||
|
||||
writeDnsName(buf, questionName);
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 1);
|
||||
|
||||
writeDnsName(buf, questionName);
|
||||
buf.putShort((short) 1);
|
||||
buf.putShort((short) 1);
|
||||
buf.putInt(300);
|
||||
buf.putShort((short) 4);
|
||||
for (String octet : ip.split("\\.")) {
|
||||
buf.put((byte) Integer.parseInt(octet));
|
||||
}
|
||||
|
||||
byte[] result = new byte[buf.position()];
|
||||
System.arraycopy(buf.array(), 0, result, 0, result.length);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -43,6 +43,8 @@ import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mockito;
|
||||
@@ -316,6 +318,38 @@ class EksClusterManagerTest {
|
||||
"io.floci.region", "us-east-1"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {true, false})
|
||||
void startClusterEmbeddedDnsFlag(boolean embeddedDns) {
|
||||
EmulatorConfig config = Mockito.mock(EmulatorConfig.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
when(config.services().eks().defaultImage()).thenReturn("rancher/k3s:v1.30.0-k3s1");
|
||||
when(config.services().eks().embeddedDns()).thenReturn(embeddedDns);
|
||||
|
||||
ContainerLifecycleManager lifecycleManager = Mockito.mock(ContainerLifecycleManager.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
when(lifecycleManager.create(any())).thenReturn("container-id");
|
||||
|
||||
ContainerBuilder containerBuilder = Mockito.mock(ContainerBuilder.class);
|
||||
ContainerBuilder.Builder builder = Mockito.mock(ContainerBuilder.Builder.class, Mockito.RETURNS_SELF);
|
||||
when(containerBuilder.newContainer(anyString())).thenReturn(builder);
|
||||
when(builder.build()).thenReturn(Mockito.mock(ContainerSpec.class));
|
||||
|
||||
EksClusterManager manager = new EksClusterManager(containerBuilder, lifecycleManager,
|
||||
Mockito.mock(ContainerDetector.class), Mockito.mock(PortAllocator.class),
|
||||
Mockito.mock(DockerHostResolver.class), Mockito.mock(EcrRegistryManager.class),
|
||||
config, new RegionResolver("us-east-1", "000000000000"));
|
||||
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("my-cluster");
|
||||
|
||||
manager.startCluster(cluster);
|
||||
|
||||
if (embeddedDns) {
|
||||
verify(builder).withEmbeddedDns();
|
||||
} else {
|
||||
verify(builder, never()).withEmbeddedDns();
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-latching persisted clusters after a Floci/Docker restart (#2609), without a Docker daemon. */
|
||||
@Nested
|
||||
class RestoreCluster {
|
||||
@@ -601,42 +635,6 @@ class EksClusterManagerTest {
|
||||
assertEquals("floci-aws-eks-999999999999.demo", cluster.getDockerName());
|
||||
verify(lifecycleManager).removeIfExists("floci-aws-eks-999999999999.demo");
|
||||
}
|
||||
|
||||
@Test
|
||||
void startClusterRegistersNodeInstanceAndNotifiesListener() {
|
||||
stubFreshStart("cid-new", 6440);
|
||||
List<Instance> registered = new ArrayList<>();
|
||||
manager.addNodeRegistrationListener(registered::add);
|
||||
|
||||
Cluster cluster = cluster();
|
||||
manager.startCluster(cluster);
|
||||
|
||||
Instance inst = manager.getRegisteredClusterNodeInstance(cluster);
|
||||
assertNotNull(inst);
|
||||
assertEquals("cid-new", inst.getDockerContainerId());
|
||||
assertEquals(1, registered.size());
|
||||
assertEquals(inst.getInstanceId(), registered.getFirst().getInstanceId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void restoreClusterRegistersNodeInstanceAndNotifiesListener() {
|
||||
when(lifecycleManager.findByName("floci-eks-demo"))
|
||||
.thenReturn(Optional.of(survivingContainer("cid-1")));
|
||||
when(lifecycleManager.adopt("cid-1", List.of(6443)))
|
||||
.thenReturn(new ContainerInfo("cid-1", Map.of(), Map.of(6443, 6512)));
|
||||
|
||||
List<Instance> registered = new ArrayList<>();
|
||||
manager.addNodeRegistrationListener(registered::add);
|
||||
|
||||
Cluster cluster = cluster();
|
||||
manager.restoreCluster(cluster);
|
||||
|
||||
Instance inst = manager.getRegisteredClusterNodeInstance(cluster);
|
||||
assertNotNull(inst);
|
||||
assertEquals("cid-1", inst.getDockerContainerId());
|
||||
assertEquals(1, registered.size());
|
||||
assertEquals(inst.getInstanceId(), registered.getFirst().getInstanceId());
|
||||
}
|
||||
}
|
||||
|
||||
/** Mirror-injection guard behavior, without a Docker daemon. */
|
||||
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package io.github.hectorvent.floci.services.eks;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
|
||||
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.quarkus.test.junit.QuarkusTestProfile;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(EksRoute53DnsDockerIntegrationTest.Profile.class)
|
||||
class EksRoute53DnsDockerIntegrationTest {
|
||||
|
||||
public static final class Profile implements QuarkusTestProfile {
|
||||
@Override
|
||||
public Map<String, String> getConfigOverrides() {
|
||||
return Map.of(
|
||||
"floci.services.eks.embedded-dns", "true");
|
||||
}
|
||||
}
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EksRoute53DnsDockerIntegrationTest.class);
|
||||
private static final String TEST_IMAGE = "alpine:3.21";
|
||||
|
||||
@Inject
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Inject
|
||||
ContainerBuilder containerBuilder;
|
||||
|
||||
@Inject
|
||||
ContainerLifecycleManager lifecycleManager;
|
||||
|
||||
@Inject
|
||||
EmbeddedDnsServer embeddedDnsServer;
|
||||
|
||||
@Inject
|
||||
Route53Service route53Service;
|
||||
|
||||
private String containerId;
|
||||
private String zoneId;
|
||||
|
||||
@BeforeEach
|
||||
void requireDockerAndEmbeddedDns() {
|
||||
boolean dockerAvailable = isDockerAvailable();
|
||||
if (!dockerAvailable) {
|
||||
LOG.warn("Docker daemon is not available; skipping EksRoute53DnsDockerIntegrationTest");
|
||||
}
|
||||
Assumptions.assumeTrue(dockerAvailable, "Docker daemon must be available for EKS Route 53 DNS integration test");
|
||||
|
||||
boolean dnsAvailable = embeddedDnsServer.getServerIp().isPresent();
|
||||
if (!dnsAvailable) {
|
||||
LOG.warn("Embedded DNS server is not running or has no bound IP; skipping EksRoute53DnsDockerIntegrationTest");
|
||||
}
|
||||
Assumptions.assumeTrue(dnsAvailable, "Embedded DNS server must have a bound IP for Route 53 DNS integration test");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (containerId != null) {
|
||||
try {
|
||||
lifecycleManager.stopAndRemove(containerId, null);
|
||||
} catch (Exception ignored) {
|
||||
// Best-effort cleanup of test container
|
||||
}
|
||||
}
|
||||
if (zoneId != null) {
|
||||
try {
|
||||
List<Map<String, Object>> deletes = route53Service.listResourceRecordSets(zoneId, null, null, 100).stream()
|
||||
.filter(rrs -> !"NS".equals(rrs.getType()) && !"SOA".equals(rrs.getType()))
|
||||
.map(rrs -> Map.<String, Object>of("action", "DELETE", "rrs", rrs))
|
||||
.toList();
|
||||
if (!deletes.isEmpty()) {
|
||||
route53Service.changeResourceRecordSets(zoneId, deletes, null);
|
||||
}
|
||||
route53Service.deleteHostedZone(zoneId);
|
||||
} catch (Exception ignored) {
|
||||
// Best-effort cleanup of test hosted zone
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterContainerResolvesRoute53PrivateHostedZoneRecords() throws Exception {
|
||||
String testDomain = "corp-it-" + UUID.randomUUID().toString().substring(0, 8) + ".internal.";
|
||||
zoneId = route53Service.createHostedZone(
|
||||
testDomain,
|
||||
UUID.randomUUID().toString(),
|
||||
"EKS IT private zone",
|
||||
new VpcAssociation("vpc-12345", "us-east-1")).zone().getId();
|
||||
|
||||
ResourceRecordSet aRrs = new ResourceRecordSet();
|
||||
aRrs.setName("db." + testDomain);
|
||||
aRrs.setType("A");
|
||||
aRrs.setTtl(60L);
|
||||
aRrs.setRecords(List.of(new ResourceRecord("10.0.1.200")));
|
||||
route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", aRrs)), null);
|
||||
|
||||
ContainerSpec spec = containerBuilder.newContainer(TEST_IMAGE)
|
||||
.withName("floci-eks-dns-test-" + UUID.randomUUID().toString().substring(0, 8))
|
||||
.withEmbeddedDns()
|
||||
.withCmd(List.of("sh", "-c", "trap 'exit 0' TERM; sleep 300 & wait"))
|
||||
.build();
|
||||
|
||||
containerId = lifecycleManager.createAndStart(spec).containerId();
|
||||
assertNotNull(containerId, "Container ID must not be null");
|
||||
|
||||
String dnsServerIp = embeddedDnsServer.getServerIp().orElseThrow();
|
||||
|
||||
// Verify that /etc/resolv.conf inside the container has the embedded DNS server IP injected
|
||||
String resolvConf = execInContainer(containerId, new String[]{"cat", "/etc/resolv.conf"});
|
||||
assertTrue(resolvConf.contains(dnsServerIp), "Container /etc/resolv.conf must include embedded DNS server IP: " + resolvConf);
|
||||
|
||||
// Verify that standard resolver queries inside the container resolve the Route 53 private record
|
||||
String lookupCmd = "nslookup db." + testDomain.substring(0, testDomain.length() - 1);
|
||||
String output = execInContainer(containerId, new String[]{"sh", "-c", lookupCmd});
|
||||
assertNotNull(output, "Lookup output must not be null");
|
||||
assertTrue(output.contains("10.0.1.200"), "Lookup output must contain record IP: " + output);
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
return true;
|
||||
} catch (Exception expected) {
|
||||
// Docker daemon is not running or unreachable in this test environment
|
||||
LOG.debugv("Docker ping failed: {0}", expected.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private String execInContainer(String containerId, String[] cmd) throws Exception {
|
||||
ExecCreateCmdResponse exec = dockerClient.execCreateCmd(containerId)
|
||||
.withCmd(cmd).withAttachStdout(true).withAttachStderr(true).exec();
|
||||
|
||||
StringBuilder stdout = new StringBuilder();
|
||||
StringBuilder stderr = new StringBuilder();
|
||||
boolean completed = dockerClient.execStartCmd(exec.getId())
|
||||
.exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
if (frame != null && frame.getPayload() != null) {
|
||||
String text = new String(frame.getPayload(), StandardCharsets.UTF_8);
|
||||
(frame.getStreamType() == StreamType.STDERR ? stderr : stdout).append(text);
|
||||
}
|
||||
}
|
||||
})
|
||||
.awaitCompletion(30, TimeUnit.SECONDS);
|
||||
|
||||
if (!completed) {
|
||||
throw new RuntimeException("exec timed out in container " + containerId);
|
||||
}
|
||||
Long exitCode = dockerClient.inspectExecCmd(exec.getId()).exec().getExitCodeLong();
|
||||
if (exitCode == null || exitCode != 0) {
|
||||
throw new RuntimeException("exec failed with code " + exitCode + ": " + stderr);
|
||||
}
|
||||
return stdout.toString();
|
||||
}
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
package io.github.hectorvent.floci.services.route53;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.dns.DnsLookupHelper;
|
||||
import io.github.hectorvent.floci.services.route53.model.AliasTarget;
|
||||
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
|
||||
import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
|
||||
import io.github.hectorvent.floci.services.route53.model.VpcAssociation;
|
||||
import io.quarkus.test.InjectMock;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class Route53DnsResolutionTest {
|
||||
|
||||
@Inject
|
||||
Route53Service route53Service;
|
||||
|
||||
@InjectMock
|
||||
DnsLookupHelper dnsLookupHelper;
|
||||
|
||||
@Inject
|
||||
Route53DnsRecordSource dnsRecordSource;
|
||||
|
||||
private final List<String> createdZoneIds = new ArrayList<>();
|
||||
|
||||
@AfterEach
|
||||
void cleanupZones() {
|
||||
for (String zoneId : createdZoneIds) {
|
||||
try {
|
||||
List<Map<String, Object>> deletes = route53Service.listResourceRecordSets(zoneId, null, null, 100).stream()
|
||||
.filter(rrs -> !"NS".equals(rrs.getType()) && !"SOA".equals(rrs.getType()))
|
||||
.map(rrs -> Map.<String, Object>of("action", "DELETE", "rrs", rrs))
|
||||
.toList();
|
||||
if (!deletes.isEmpty()) {
|
||||
route53Service.changeResourceRecordSets(zoneId, deletes, null);
|
||||
}
|
||||
route53Service.deleteHostedZone(zoneId);
|
||||
} catch (Exception ignored) {
|
||||
// Best-effort cleanup
|
||||
}
|
||||
}
|
||||
createdZoneIds.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesDirectARecordInPrivateHostedZone() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "api." + zone, "A", "10.0.1.100");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("api." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("10.0.1.100"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesMultipleARecords() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecords(zoneId, "api." + zone, "A", List.of("10.0.1.101", "10.0.1.102"));
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("api." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(2, result.get().size());
|
||||
assertTrue(result.get().contains("10.0.1.101"));
|
||||
assertTrue(result.get().contains("10.0.1.102"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void answersWithAtMostEightRecords() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
List<String> ips = new ArrayList<>();
|
||||
for (int i = 1; i <= 12; i++) {
|
||||
ips.add("10.0.1." + i);
|
||||
}
|
||||
addRecords(zoneId, "fleet." + zone, "A", ips);
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("fleet." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(8, result.get().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolutionIsCaseInsensitiveAndToleratesATrailingDot() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "api." + zone, "A", "10.0.1.200");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("API." + zone.toUpperCase() + ".");
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("10.0.1.200"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotResolvePublicHostedZone() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = route53Service.createHostedZone(
|
||||
zone + ".", UUID.randomUUID().toString(), "public zone", null).zone().getId();
|
||||
createdZoneIds.add(zoneId);
|
||||
addRecord(zoneId, "api." + zone, "A", "1.2.3.4");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("api." + zone);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotResolveNameOutsideAnyPrivateZone() {
|
||||
assertTrue(dnsRecordSource.resolveIpv4("example.com").isEmpty());
|
||||
assertTrue(dnsRecordSource.resolveIpv4("").isEmpty());
|
||||
assertTrue(dnsRecordSource.resolveIpv4(null).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesWildcardRecordInPrivateZone() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "*." + zone, "A", "10.0.2.1");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("app." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("10.0.2.1"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void wildcardDoesNotMatchBeneathCloserExistingName() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "*." + zone, "A", "10.0.2.1");
|
||||
addRecord(zoneId, "b." + zone, "TXT", "\"text-record\"");
|
||||
|
||||
// Wildcard should not match a.b.zone because b.zone exists
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("a.b." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of(), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesPrivateCnameChainToARecord() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "api." + zone, "A", "10.0.3.50");
|
||||
addRecord(zoneId, "service." + zone, "CNAME", "api." + zone + ".");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("service." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("10.0.3.50"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesCnameCycleGracefullyWithoutInfiniteLoop() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "cname1." + zone, "CNAME", "cname2." + zone);
|
||||
addRecord(zoneId, "cname2." + zone, "CNAME", "cname1." + zone);
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("cname1." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of(), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesPrivateCnameToEc2PrivateDnsName() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "ec2host." + zone, "CNAME", "ip-10-0-5-88.ec2.internal.");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("ec2host." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("10.0.5.88"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesPrivateCnameToExternalHostname() {
|
||||
Mockito.when(dnsLookupHelper.resolveIpv4("external.example.com"))
|
||||
.thenReturn(List.of("93.184.216.34"));
|
||||
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "ext." + zone, "CNAME", "external.example.com.");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("ext." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("93.184.216.34"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolvesAliasRecordInPrivateZone() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "target." + zone, "A", "10.0.4.99");
|
||||
addAlias(zoneId, "alias." + zone, "A", "target." + zone + ".");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("alias." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("10.0.4.99"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyListForNonExistentNameInPrivateZone() {
|
||||
String zone = uniqueZone();
|
||||
createPrivateZone(zone);
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("nonexistent." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of(), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyListForExistingNameWithoutARecord() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "txtonly." + zone, "TXT", "\"only text here\"");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("txtonly." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of(), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parentZoneDoesNotAnswerChildNamesIfChildZoneExists() {
|
||||
String parentZone = uniqueZone();
|
||||
String childZone = "sub." + parentZone;
|
||||
String parentId = createPrivateZone(parentZone);
|
||||
String childId = createPrivateZone(childZone);
|
||||
|
||||
addRecord(parentId, "api.sub." + parentZone, "A", "10.0.10.1");
|
||||
addRecord(childId, "api." + childZone, "A", "10.0.20.1");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("api.sub." + parentZone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("10.0.20.1"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cnameTargetToFlociBuiltinSuffixResolvesLocalAddress() throws Exception {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "floci-cname." + zone, "CNAME", "s3.localhost.localstack.cloud");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("floci-cname." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
String expectedIp = InetAddress.getLocalHost().getHostAddress();
|
||||
assertEquals(List.of(expectedIp), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cnameTargetToDefaultFlociSuffixResolvesLocalAddress() throws Exception {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addRecord(zoneId, "floci-cname2." + zone, "CNAME", "sqs.localhost.floci.io");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("floci-cname2." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
String expectedIp = InetAddress.getLocalHost().getHostAddress();
|
||||
assertEquals(List.of(expectedIp), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aliasTargetToFlociBuiltinSuffixResolvesLocalAddress() throws Exception {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addAlias(zoneId, "floci-alias." + zone, "A", "s3.localhost.localstack.cloud");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("floci-alias." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
String expectedIp = InetAddress.getLocalHost().getHostAddress();
|
||||
assertEquals(List.of(expectedIp), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aliasTargetToBareLocalstackCloudDoesNotResolveLocalAddress() throws Exception {
|
||||
Mockito.when(dnsLookupHelper.resolveIpv4("s3.localstack.cloud"))
|
||||
.thenReturn(List.of("192.0.2.1"));
|
||||
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addAlias(zoneId, "bare-alias." + zone, "A", "s3.localstack.cloud");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("bare-alias." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
String localIp = InetAddress.getLocalHost().getHostAddress();
|
||||
assertFalse(result.get().contains(localIp));
|
||||
assertEquals(List.of("192.0.2.1"), result.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aliasTargetToEc2PrivateDnsResolves() {
|
||||
String zone = uniqueZone();
|
||||
String zoneId = createPrivateZone(zone);
|
||||
addAlias(zoneId, "ec2-alias." + zone, "A", "ip-10-0-0-5.ec2.internal");
|
||||
|
||||
Optional<List<String>> result = dnsRecordSource.resolveIpv4("ec2-alias." + zone);
|
||||
assertTrue(result.isPresent());
|
||||
assertEquals(List.of("10.0.0.5"), result.get());
|
||||
}
|
||||
|
||||
private String createPrivateZone(String name) {
|
||||
String zoneName = name.endsWith(".") ? name : name + ".";
|
||||
String id = route53Service.createHostedZone(
|
||||
zoneName,
|
||||
UUID.randomUUID().toString(),
|
||||
"test private zone",
|
||||
new VpcAssociation("vpc-12345", "us-east-1")).zone().getId();
|
||||
createdZoneIds.add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
private void addRecord(String zoneId, String name, String type, String value) {
|
||||
ResourceRecordSet rrs = new ResourceRecordSet();
|
||||
rrs.setName(name);
|
||||
rrs.setType(type);
|
||||
rrs.setTtl(300L);
|
||||
rrs.setRecords(List.of(new ResourceRecord(value)));
|
||||
route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", rrs)), null);
|
||||
}
|
||||
|
||||
private void addRecords(String zoneId, String name, String type, List<String> values) {
|
||||
ResourceRecordSet rrs = new ResourceRecordSet();
|
||||
rrs.setName(name);
|
||||
rrs.setType(type);
|
||||
rrs.setTtl(300L);
|
||||
rrs.setRecords(values.stream().map(ResourceRecord::new).toList());
|
||||
route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", rrs)), null);
|
||||
}
|
||||
|
||||
private void addAlias(String zoneId, String name, String type, String targetDnsName) {
|
||||
ResourceRecordSet rrs = new ResourceRecordSet();
|
||||
rrs.setName(name);
|
||||
rrs.setType(type);
|
||||
AliasTarget alias = new AliasTarget();
|
||||
alias.setDnsName(targetDnsName);
|
||||
alias.setHostedZoneId(zoneId);
|
||||
alias.setEvaluateTargetHealth(false);
|
||||
rrs.setAliasTarget(alias);
|
||||
route53Service.changeResourceRecordSets(zoneId, List.of(Map.of("action", "CREATE", "rrs", rrs)), null);
|
||||
}
|
||||
|
||||
private static String uniqueZone() {
|
||||
return "r53dns" + UUID.randomUUID().toString().substring(0, 8) + ".internal";
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.route53.model.AliasTarget;
|
||||
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 org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
@@ -22,7 +23,9 @@ import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class Route53ServiceTest {
|
||||
|
||||
@@ -263,4 +266,37 @@ class Route53ServiceTest {
|
||||
assertThat(records, hasSize(1));
|
||||
assertEquals("5.6.7.8", records.get(0).getRecords().get(0).getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void clear_resetsPrivateZoneNameCounts() {
|
||||
Route53Service service = newService();
|
||||
String zoneId = service.createHostedZone("corp.internal.", "ref-clear", null,
|
||||
new VpcAssociation("vpc-123", "us-east-1")).zone().getId();
|
||||
|
||||
service.changeResourceRecordSets(zoneId,
|
||||
List.of(change("CREATE", aRecord("app.corp.internal.", 300, "10.0.0.1"))), null);
|
||||
|
||||
List<ResourceRecordSet> beforeClear = service.findPrivateRecordsForName("app.corp.internal.");
|
||||
assertThat(beforeClear, hasSize(1));
|
||||
|
||||
service.clear();
|
||||
|
||||
List<ResourceRecordSet> afterClear = service.findPrivateRecordsForName("app.corp.internal.");
|
||||
assertThat(afterClear, empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isCoveredByPrivateZone_matchesPrivateZoneDomainsOnly() {
|
||||
Route53Service service = newService();
|
||||
service.createHostedZone("corp.internal.", "ref-private", null,
|
||||
new VpcAssociation("vpc-123", "us-east-1"));
|
||||
service.createHostedZone("public.com.", "ref-public", null, null);
|
||||
|
||||
assertTrue(service.isCoveredByPrivateZone("corp.internal"));
|
||||
assertTrue(service.isCoveredByPrivateZone("app.corp.internal."));
|
||||
assertTrue(service.isCoveredByPrivateZone("sub.service.corp.internal"));
|
||||
assertFalse(service.isCoveredByPrivateZone("public.com"));
|
||||
assertFalse(service.isCoveredByPrivateZone("othercorp.internal"));
|
||||
assertFalse(service.isCoveredByPrivateZone("example.org"));
|
||||
}
|
||||
}
|
||||
@@ -334,6 +334,7 @@ floci:
|
||||
ecr-registry-mirror: true
|
||||
imds: false
|
||||
irsa-signing-key: true
|
||||
embedded-dns: true
|
||||
mwaa:
|
||||
enabled: true
|
||||
mock: true
|
||||
|
||||
Reference in new issue
Block a user