mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user