feat(route53resolver): apply resolver rules to DNS resolution (#4538)

* feat(route53resolver): apply resolver rules to DNS resolution

Resolver rules were stored and ignored. The embedded DNS server now consults them
before resolving a name itself, via two CDI SPIs so core.common.dns imports neither
Route 53 Resolver nor EKS: DnsForwardingRuleSource supplies the rules associated with
one VPC, DnsClientVpcSource maps a query's source address to the VPC it came from.

FORWARD rules forward the raw query to their TargetIps, each on its own port, in a
random order with the next target tried when one does not answer. SYSTEM and RECURSIVE
rules carry no targets and hand the query back to Floci, so a SYSTEM rule carves a
subdomain out of a broader FORWARD. Matching is exact-or-subdomain on label boundaries
and the most specific matching rule wins. A rule takes precedence over a private hosted
zone matching the same name, as AWS documents. Floci's own suffixes and ec2.internal
names resolve locally whatever the rules say, as AWS autodefines system rules for its
internal domains. A rule whose targets are all unreachable answers SERVFAIL for that
query only.

Route53ResolverDnsForwardingRules reads the rule and association stores through
Route53ResolverService across account partitions, since the packet path has no caller.
EksClusterManager claims its cluster node container addresses for the cluster's
resourcesVpcConfig.vpcId.

* fix(route53resolver): scope rule DNS lookups to the querying account

AssociateResolverRule stores whatever VPCId the caller names without proving
ownership of it, so joining associations across account partitions by VPC id let
one account redirect another account's cluster DNS by naming its VPC. The DNS
client VPC now carries the account alongside the VPC id, and the rule source
reads only that account's associations.

Rules are fetched by id instead of scanned for, so a query reads only the rules
an association named rather than the whole rule store, and registration warns
when a running cluster's container addresses cannot be determined instead of
leaving its rules silently inert.

Also stop setting the authoritative bit on the SERVFAIL answer for a forwarded
query: Floci is not the authority for a name a rule sends elsewhere.

* style(route53resolver): import Optional instead of qualifying it inline

* fix(route53resolver): scope rule DNS lookups to the querying region

Route 53 Resolver is regional, so a rule created in one region governs nothing in
another, but the DNS path matched on account and VPC alone. A rule created in
eu-west-1 therefore steered a query from a VPC in us-east-1. The DNS client origin
now carries the region, and a rule is only applied when its own region matches.

The stores carry no region in their keys, so a rule's region is read back from the
ARN the service minted for it rather than reshaping the stores. A stored rule with
no parseable ARN has no region to claim and is treated as belonging to the region
asking, which no create path can produce.

Associations are now read as rule ids rather than as nodes, so a query no longer
deep-copies a record per association when all it needs is which rules to look at.

* test(eks): pin the warning when a cluster's addresses cannot be determined

Inspecting the node container can fail, and when it does the cluster gets no VPC
mapping and its queries quietly ignore every associated resolver rule. Nothing
fails, so the warning is the only way a reader finds out, which makes it worth a
test rather than leaving it to inspection.

Levels are compared by severity rather than identity because JBoss LogManager
has its own Level constants, so its WARN is not java.util.logging's WARNING.
This commit is contained in:
Simone Primarosa authored and GitHub committed 2026-09-28 09:44:28 -04:00
1 parent bc15516cc0
commit a8eedb1fd9
13 files changed
+1285 -35

No files matched your search

@@ -0,0 +1,30 @@
package io.github.hectorvent.floci.core.common.dns;
import java.util.Optional;
/**
* Tells {@link EmbeddedDnsServer} which VPC a query came from, so rules associated with that VPC
* can be applied and rules that are not can be ignored.
*
* <p>The DNS wire protocol carries no VPC identifier, but the query's source address identifies the
* container that sent it, and a service that launches containers for an AWS resource knows the VPC
* that resource sits in. Implemented by those services and discovered through CDI.
*/
public interface DnsClientVpcSource {
/**
* Where a query came from. The account is part of it because a VPC id alone is not an identity:
* any account can associate a resolver rule with any VPC id it cares to name, so a rule may only
* steer queries from a resource its own account owns. The region is part of it because Route 53
* Resolver is regional, so a rule only governs queries from the region it was created in.
*/
record ClientVpc(String accountId, String region, String vpcId) {
}
/**
* The account, region and VPC of the resource reachable at {@code clientAddress}, or empty when
* this source launched nothing there. Empty is not an error: a query no one claims has no VPC, so
* no rules apply to it.
*/
Optional<ClientVpc> vpcForClient(String clientAddress);
}
@@ -0,0 +1,78 @@
package io.github.hectorvent.floci.core.common.dns;
import java.util.List;
import java.util.Locale;
/**
* One rule that steers a DNS query away from the resolution {@link EmbeddedDnsServer} would perform
* on its own. A rule with targets sends a matching query to those resolvers, as a Route 53 Resolver
* {@code FORWARD} rule does; a rule with no targets sends it back to Floci's own resolution, as a
* {@code SYSTEM} rule does when it carves a subdomain out of a broader forwarding rule.
*
* <p>Matching follows Route 53 Resolver: a rule matches a query name that equals its domain name or
* is a subdomain of it, and where several rules match, the one with the most labels in its domain
* name wins. The root domain, which AWS spells {@code "."}, matches every name and is the least
* specific rule there is.
*/
public record DnsForwardingRule(String domainName, List<Target> targets) {
/** A resolver a matching query is forwarded to. Route 53 Resolver defaults the port to 53. */
public record Target(String address, int port) {
public static final int DEFAULT_DNS_PORT = 53;
public Target(String address) {
this(address, DEFAULT_DNS_PORT);
}
}
public DnsForwardingRule {
domainName = normalize(domainName);
targets = List.copyOf(targets);
}
/** A rule that forwards matching queries to {@code targets}. */
public static DnsForwardingRule forwardTo(String domainName, List<Target> targets) {
return new DnsForwardingRule(domainName, targets);
}
/** A rule that hands matching queries back to Floci's own resolution. */
public static DnsForwardingRule system(String domainName) {
return new DnsForwardingRule(domainName, List.of());
}
public boolean forwards() {
return !targets.isEmpty();
}
/** Whether {@code queryName} is this rule's domain name or a subdomain of it. */
public boolean matches(String queryName) {
if (queryName == null || queryName.isBlank()) {
return false;
}
if (domainName.isEmpty()) {
return true;
}
String query = normalize(queryName);
return query.equals(domainName) || query.endsWith("." + domainName);
}
/**
* How specific this rule's domain name is, as its label count. The root domain scores zero,
* so any named rule outranks a rule for {@code "."}.
*/
public int specificity() {
return domainName.isEmpty() ? 0 : domainName.split("\\.").length;
}
private static String normalize(String name) {
if (name == null) {
return "";
}
String normalized = name.trim().toLowerCase(Locale.ROOT);
while (normalized.endsWith(".")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
return normalized;
}
}
@@ -0,0 +1,23 @@
package io.github.hectorvent.floci.core.common.dns;
import java.util.List;
/**
* A source of {@link DnsForwardingRule}s that {@link EmbeddedDnsServer} consults before resolving a
* query itself, discovered through CDI so the DNS server never imports the service that stores them.
*
* <p>The source is asked for the rules of one VPC, in one account and one region, so association
* and scoping are its decision; picking between several matching rules is the DNS server's, which
* compares them on domain specificity. Returning the rules most specific first makes that choice
* deterministic when two rules tie.
*
* <p>It runs outside any request context, on a worker thread.
*/
public interface DnsForwardingRuleSource {
/**
* The rules {@code accountId} has associated with {@code vpcId} in {@code region}, none of which
* is blank. An empty list leaves resolution exactly as it is without this source.
*/
List<DnsForwardingRule> rulesFor(String accountId, String region, String vpcId);
}
@@ -21,10 +21,12 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.SequencedSet;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -39,6 +41,10 @@ import java.util.regex.Pattern;
* Also answers for any name a {@link DnsRecordSource} owns, which is how a service that holds
* a private DNS zone (Cloud Map) gets real records rather than only API responses.
*
* A {@link DnsForwardingRuleSource} can steer a query away from all of that before it is
* resolved, which is how a Route 53 Resolver forwarding rule associated with the querying
* container's VPC sends matching names to the resolvers the rule names instead.
*
* All other queries are forwarded to the upstream resolvers read from /etc/resolv.conf
* (Docker's embedded DNS at 127.0.0.11), falling back to the configured public resolvers
* (floci.dns.container-fallback-servers) so public hostnames still resolve when the
@@ -78,21 +84,35 @@ public class EmbeddedDnsServer {
// Held as the Iterable a CDI Instance already is, so iterating resolves the beans lazily on
// the packet path rather than at startup, where a source's storage must not be touched yet.
private final Iterable<DnsRecordSource> recordSources;
private final Iterable<DnsForwardingRuleSource> forwardingRuleSources;
private final Iterable<DnsClientVpcSource> clientVpcSources;
EmbeddedDnsServer(List<String> suffixes) {
this(suffixes, List.of());
}
EmbeddedDnsServer(List<String> suffixes, Iterable<DnsRecordSource> recordSources) {
this(suffixes, recordSources, List.of(), List.of());
}
EmbeddedDnsServer(List<String> suffixes, Iterable<DnsRecordSource> recordSources,
Iterable<DnsForwardingRuleSource> forwardingRuleSources,
Iterable<DnsClientVpcSource> clientVpcSources) {
this.suffixes.addAll(BUILTIN_SUFFIXES);
this.suffixes.addAll(suffixes);
this.recordSources = recordSources;
this.forwardingRuleSources = forwardingRuleSources;
this.clientVpcSources = clientVpcSources;
}
@Inject
public EmbeddedDnsServer(EmulatorConfig config, ContainerDetector containerDetector, Vertx vertx,
Instance<DnsRecordSource> recordSources) {
Instance<DnsRecordSource> recordSources,
Instance<DnsForwardingRuleSource> forwardingRuleSources,
Instance<DnsClientVpcSource> clientVpcSources) {
this.recordSources = recordSources;
this.forwardingRuleSources = forwardingRuleSources;
this.clientVpcSources = clientVpcSources;
if (!containerDetector.isRunningInContainer()) {
return;
}
@@ -149,13 +169,18 @@ public class EmbeddedDnsServer {
buf.getShort(); // qclass
int questionEnd = buf.position();
vertx.<Optional<DnsAnswer>>executeBlocking(() -> resolveRecordWithOwnership(qname, myIp, qtype), false)
.onSuccess(answer -> {
if (answer.isEmpty()) {
forwardAsync(vertx, socket, data, senderHost, senderPort);
vertx.<QueryPlan>executeBlocking(() -> planQuery(qname, senderHost, myIp, qtype), false)
.onSuccess(plan -> {
if (plan.answer().isEmpty()) {
if (plan.ruleTargets().isEmpty()) {
forwardAsync(vertx, socket, data, senderHost, senderPort);
} else {
forwardToRuleTargets(vertx, socket, data, senderHost, senderPort,
plan.ruleTargets(), qname, txId, questionOffset, questionEnd);
}
return;
}
DnsAnswer records = answer.orElseThrow();
DnsAnswer records = plan.answer().orElseThrow();
byte[] response = !records.isEmpty()
? buildAResponse(data, txId, questionOffset, questionEnd, records)
: buildEmptyResponse(data, txId, questionOffset, questionEnd,
@@ -194,15 +219,122 @@ public class EmbeddedDnsServer {
}
private Optional<DnsAnswer> resolveRecordWithOwnership(String name, String myIp, int type) {
Optional<DnsAnswer> emulatorName = resolveEmulatorName(name, myIp, type);
return emulatorName.isPresent() ? emulatorName : resolveFromRecordSources(name, type);
}
/**
* What happens to one query, decided on a worker thread because every step behind it reads
* storage: an answer Floci owns, a set of resolvers a rule forwards the query to, or neither,
* which leaves it to the upstream resolvers.
*/
record QueryPlan(Optional<DnsAnswer> answer, List<DnsForwardingRule.Target> ruleTargets) {
static final QueryPlan UPSTREAM = new QueryPlan(Optional.empty(), List.of());
static QueryPlan answering(DnsAnswer answer) {
return new QueryPlan(Optional.of(answer), List.of());
}
static QueryPlan forwardingTo(List<DnsForwardingRule.Target> targets) {
return new QueryPlan(Optional.empty(), targets);
}
}
/**
* Names the emulator itself owns come first, whatever the rules say. Route 53 Resolver does
* the same for the AWS-internal domains it autodefines system rules for, so that a rule for a
* broad domain (or for "." itself) cannot send the platform's own names off to a resolver that
* knows nothing about them.
*
* <p>A forwarding rule associated with the querying VPC is then applied before Floci resolves
* the name from a record source, because a Resolver rule takes precedence over a private
* hosted zone that matches the same name.
*/
QueryPlan planQuery(String name, String clientAddress, String myIp, int type) {
Optional<DnsAnswer> emulatorName = resolveEmulatorName(name, myIp, type);
if (emulatorName.isPresent()) {
return QueryPlan.answering(emulatorName.orElseThrow());
}
// A rule steers the name whatever the query asks about it, so this is deliberately not
// gated on the record type: the raw query is relayed to the rule's resolvers as it stands.
Optional<DnsForwardingRule> rule = matchingRule(name, clientAddress);
if (rule.isPresent() && rule.orElseThrow().forwards()) {
return QueryPlan.forwardingTo(rule.orElseThrow().targets());
}
return resolveFromRecordSources(name, type).map(QueryPlan::answering).orElse(QueryPlan.UPSTREAM);
}
private Optional<DnsAnswer> resolveEmulatorName(String name, String myIp, int type) {
if (matchesSuffix(name)) {
return Optional.of(type == 1 ? DnsAnswer.records(List.of(myIp), DnsAnswer.DEFAULT_TTL_SECONDS)
: DnsAnswer.noData());
}
Optional<String> ec2PrivateDnsName = resolveEc2PrivateDnsName(name);
return ec2PrivateDnsName
return resolveEc2PrivateDnsName(name)
.map(address -> type == 1 ? DnsAnswer.records(List.of(address), DnsAnswer.DEFAULT_TTL_SECONDS)
: DnsAnswer.noData())
.map(Optional::of).orElseGet(() -> resolveFromRecordSources(name, type));
: DnsAnswer.noData());
}
/**
* The rule that governs this query: the most specific one whose domain matches the name among
* those associated with the VPC the query came from. A source that throws is skipped rather
* than allowed to fail the query, which is how {@link #resolveFromRecordSources} treats one too.
*/
Optional<DnsForwardingRule> matchingRule(String name, String clientAddress) {
if (forwardingRuleSources == null || name == null || name.isBlank()) {
return Optional.empty();
}
Optional<DnsClientVpcSource.ClientVpc> clientVpc = vpcForClient(clientAddress);
if (clientVpc.isEmpty()) {
return Optional.empty();
}
DnsClientVpcSource.ClientVpc origin = clientVpc.orElseThrow();
DnsForwardingRule best = null;
for (DnsForwardingRuleSource source : forwardingRuleSources) {
try {
for (DnsForwardingRule rule :
source.rulesFor(origin.accountId(), origin.region(), origin.vpcId())) {
if (rule == null || !rule.matches(name)) {
continue;
}
if (best == null || rule.specificity() > best.specificity()) {
best = rule;
}
}
} catch (Exception e) {
LOG.debugv("DNS forwarding rule source {0} failed for {1}: {2}",
source.getClass().getSimpleName(), name, e.getMessage());
}
}
return Optional.ofNullable(best);
}
private Optional<DnsClientVpcSource.ClientVpc> vpcForClient(String clientAddress) {
if (clientVpcSources == null || clientAddress == null || clientAddress.isBlank()) {
return Optional.empty();
}
for (DnsClientVpcSource source : clientVpcSources) {
try {
Optional<DnsClientVpcSource.ClientVpc> clientVpc =
source.vpcForClient(clientAddress.trim());
if (clientVpc != null && clientVpc.isPresent() && isUsableOrigin(clientVpc.orElseThrow())) {
return clientVpc;
}
} catch (Exception e) {
LOG.debugv("DNS client VPC source {0} failed for {1}: {2}",
source.getClass().getSimpleName(), clientAddress, e.getMessage());
}
}
return Optional.empty();
}
private static boolean isUsableOrigin(DnsClientVpcSource.ClientVpc clientVpc) {
return isPresent(clientVpc.accountId()) && isPresent(clientVpc.region())
&& isPresent(clientVpc.vpcId());
}
private static boolean isPresent(String value) {
return value != null && !value.isBlank();
}
/**
@@ -229,10 +361,25 @@ public class EmbeddedDnsServer {
}
byte[] buildEmptyResponse(byte[] query, short txId, int questionOffset, int questionEnd, int responseCode) {
return buildAnswerlessResponse(query, txId, questionOffset, questionEnd,
(short) (0x8580 | responseCode));
}
/**
* The failure answer for a query a forwarding rule claimed and no target answered. Not
* authoritative, unlike {@link #buildEmptyResponse}: Floci is not the authority for a name a
* rule sends elsewhere, it only failed to reach the resolver that is.
*/
byte[] buildServerFailureResponse(byte[] query, short txId, int questionOffset, int questionEnd) {
return buildAnswerlessResponse(query, txId, questionOffset, questionEnd, (short) 0x8182);
}
private static byte[] buildAnswerlessResponse(byte[] query, short txId, int questionOffset,
int questionEnd, short flags) {
UdpPayload payload = udpPayload(query, questionEnd);
ByteBuffer response = ByteBuffer.allocate(12 + questionEnd - questionOffset + (payload.edns() ? 11 : 0));
response.putShort(txId);
response.putShort((short) (0x8580 | responseCode));
response.putShort(flags);
response.putShort((short) 1);
response.putShort((short) 0);
response.putShort((short) 0);
@@ -404,28 +551,71 @@ public class EmbeddedDnsServer {
upstreams, e.getMessage()));
}
/**
* Sends the query to the resolvers a forwarding rule names instead of to the upstreams. The
* order is shuffled because Route 53 Resolver picks a rule's target at random and retries
* another one when it does not answer.
*
* <p>A rule whose targets are all unreachable fails this query with SERVFAIL rather than
* falling back to the upstream resolvers. The rule said where the name lives, so an upstream
* answer for it would be the wrong answer, and resolution of every other name is untouched.
*/
private void forwardToRuleTargets(Vertx vertx, DatagramSocket socket, byte[] query,
String senderHost, int senderPort,
List<DnsForwardingRule.Target> targets, String qname,
short txId, int questionOffset, int questionEnd) {
vertx.executeBlocking(() -> forwardToTargets(query, shuffled(targets)))
.onSuccess(response ->
socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {}))
.onFailure(e -> {
LOG.warnv("Resolver rule forwarding for {0} failed on every target {1}: {2}",
qname, targets, e.getMessage());
socket.send(Buffer.buffer(
buildServerFailureResponse(query, txId, questionOffset, questionEnd)),
senderPort, senderHost, v -> {});
});
}
private static List<DnsForwardingRule.Target> shuffled(List<DnsForwardingRule.Target> targets) {
if (targets.size() < 2) {
return targets;
}
List<DnsForwardingRule.Target> order = new ArrayList<>(targets);
Collections.shuffle(order, ThreadLocalRandom.current());
return order;
}
/**
* Forwards the query to each upstream in order and returns the first valid UDP response.
* 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}.
*/
static byte[] forwardToUpstreams(byte[] query, List<String> upstreams, int upstreamPort) throws Exception {
return forwardToTargets(query, upstreams.stream()
.map(upstream -> new DnsForwardingRule.Target(upstream, upstreamPort)).toList());
}
/**
* Forwards the query to each target in order and returns the first valid UDP response. Targets
* carry their own port because a resolver rule may name a resolver that does not listen on 53.
*/
static byte[] forwardToTargets(byte[] query, List<DnsForwardingRule.Target> targets) throws Exception {
Exception last = null;
for (String upstream : upstreams) {
for (DnsForwardingRule.Target target : targets) {
try (java.net.DatagramSocket fwd = new java.net.DatagramSocket()) {
fwd.setSoTimeout(FORWARD_TIMEOUT_MS);
InetAddress addr = InetAddress.getByName(upstream);
fwd.send(new DatagramPacket(query, query.length, addr, upstreamPort));
InetAddress addr = InetAddress.getByName(target.address());
fwd.send(new DatagramPacket(query, query.length, addr, target.port()));
byte[] buf = new byte[MAX_DNS_UDP_RESPONSE];
DatagramPacket resp = new DatagramPacket(buf, buf.length);
fwd.receive(resp);
return Arrays.copyOf(resp.getData(), resp.getLength());
} catch (Exception e) {
last = e;
LOG.debugv("DNS forward to {0} failed: {1}", upstream, e.getMessage());
LOG.debugv("DNS forward to {0} failed: {1}", target.address(), e.getMessage());
}
}
throw last != null ? last : new IOException("no upstream resolvers configured");
throw last != null ? last : new IOException("no resolvers to forward to");
}
/**
@@ -10,6 +10,8 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.FlociCertificateAuthority;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.dns.DnsClientVpcSource;
import io.github.hectorvent.floci.core.common.dns.DnsClientVpcSource.ClientVpc;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
@@ -80,7 +82,8 @@ import java.util.stream.Collectors;
* Not used when {@code floci.services.eks.mock=true}.
*/
@ApplicationScoped
public class EksClusterManager implements ClusterNodeInstanceProvider, VpcRouteTableListener {
public class EksClusterManager
implements ClusterNodeInstanceProvider, VpcRouteTableListener, DnsClientVpcSource {
private static final Logger LOG = Logger.getLogger(EksClusterManager.class);
private static final int K3S_API_SERVER_PORT = 6443;
@@ -174,6 +177,61 @@ public class EksClusterManager implements ClusterNodeInstanceProvider, VpcRouteT
record ClusterNodeRecord(String accountId, String region, Instance instance) {}
/** Which cluster owns a Docker address its node container answers on, and where that cluster sits. */
record ClusterNodeVpc(String clusterResourceName, ClientVpc clientVpc) {}
private final Map<String, ClusterNodeVpc> clusterNodeVpcs = new ConcurrentHashMap<>();
/**
* A DNS query from a cluster container originates in the account, region and VPC the cluster was
* created with, which is what a Route 53 Resolver rule has to belong to for the query to follow
* it. A cluster with no resolvable VPC id claims no address: its queries resolve as they do
* without any rule rather than picking up another cluster's.
*/
@Override
public Optional<ClientVpc> vpcForClient(String clientAddress) {
if (clientAddress == null || clientAddress.isBlank()) {
return Optional.empty();
}
return Optional.ofNullable(clusterNodeVpcs.get(clientAddress.trim()))
.map(ClusterNodeVpc::clientVpc);
}
private void registerClusterNodeVpc(Cluster cluster, String accountId, String region,
Set<String> addresses) {
String clusterKey = clusterResourceName(cluster);
forgetClusterNodeVpcs(clusterKey);
String vpcId = cluster.getResourcesVpcConfig() != null
? cluster.getResourcesVpcConfig().getVpcId() : null;
if (vpcId == null || vpcId.isBlank()) {
return;
}
Set<String> usable = new LinkedHashSet<>();
for (String address : addresses) {
if (address != null && !address.isBlank()) {
usable.add(address);
}
}
if (usable.isEmpty()) {
// Without the container's own addresses there is nothing to recognise its queries by, so
// resolver rules cannot apply to this cluster. Said out loud rather than left as silence:
// the cluster runs fine and only rule-steered names behave as though no rule existed.
LOG.warnv("Resolver rules will not apply to EKS cluster {0} in {1}: its container"
+ " addresses could not be determined, so its DNS queries cannot be attributed"
+ " to the VPC. Restart the cluster to retry.", cluster.getName(), vpcId);
return;
}
ClientVpc clientVpc = new ClientVpc(accountId, region, vpcId);
for (String address : usable) {
clusterNodeVpcs.put(address, new ClusterNodeVpc(clusterKey, clientVpc));
}
}
private void forgetClusterNodeVpcs(String clusterResourceName) {
clusterNodeVpcs.entrySet().removeIf(
entry -> clusterResourceName.equals(entry.getValue().clusterResourceName()));
}
public EksClusterManager(ContainerBuilder containerBuilder,
ContainerLifecycleManager lifecycleManager,
ContainerDetector containerDetector,
@@ -1692,6 +1750,7 @@ public class EksClusterManager implements ClusterNodeInstanceProvider, VpcRouteT
Instance nodeInstance = synthesizeClusterNodeInstance(cluster, containerIps.primaryIp(), region, accountId);
nodeInstance.setDockerContainerId(containerId);
clusterNodeInstances.put(clusterResourceName(cluster), new ClusterNodeRecord(accountId, region, nodeInstance));
registerClusterNodeVpc(cluster, accountId, region, containerIps.allIps());
for (Consumer<Instance> listener : nodeRegistrationListeners) {
try {
listener.accept(nodeInstance);
@@ -1936,6 +1995,7 @@ public class EksClusterManager implements ClusterNodeInstanceProvider, VpcRouteT
activeClusters.remove(clusterKey);
programmedClusterRoutes.remove(clusterKey);
}
forgetClusterNodeVpcs(clusterKey);
ClusterNodeRecord record = clusterNodeInstances.remove(clusterKey);
Instance nodeInstance = record != null ? record.instance() : null;
if (metadataServer != null && nodeInstance != null) {
@@ -0,0 +1,94 @@
package io.github.hectorvent.floci.services.route53resolver;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.dns.DnsForwardingRule;
import io.github.hectorvent.floci.core.common.dns.DnsForwardingRuleSource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
/**
* Turns the resolver rules {@link Route53ResolverService} stores into the forwarding rules the
* embedded DNS server applies. Discovered via CDI as a {@link DnsForwardingRuleSource}, so the DNS
* server never imports this service, and the rules are read from its stores rather than copied.
*
* <p>Only rules the querying account has associated with the querying VPC, in the querying region,
* are returned. An unassociated rule is inert in AWS, an association naming a VPC of some other
* account is not that account's business, and Route 53 Resolver is regional, so a rule governs
* nothing outside the region it was created in. {@code FORWARD} rules carry their target resolvers;
* {@code SYSTEM} and {@code RECURSIVE} rules carry none and so hand the query back to Floci's own
* resolution, which is what both mean in AWS. {@code DELEGATE} is stored but not applied.
*/
@ApplicationScoped
public class Route53ResolverDnsForwardingRules implements DnsForwardingRuleSource {
private final Route53ResolverService resolverService;
private final EmulatorConfig config;
@Inject
public Route53ResolverDnsForwardingRules(Route53ResolverService resolverService, EmulatorConfig config) {
this.resolverService = resolverService;
this.config = config;
}
@Override
public List<DnsForwardingRule> rulesFor(String accountId, String region, String vpcId) {
if (!config.services().route53resolver().enabled()) {
return List.of();
}
List<DnsForwardingRule> rules = new ArrayList<>();
for (String ruleId : resolverService.resolverRuleIdsAssociatedWith(accountId, vpcId)) {
resolverService.resolverRuleIn(accountId, region, ruleId)
.flatMap(Route53ResolverDnsForwardingRules::forwardingRuleFor)
.ifPresent(rules::add);
}
// Most specific first, so the DNS server's choice between two equally specific rules is the
// same on every query rather than following whatever order the store scanned in.
rules.sort(Comparator.comparingInt(DnsForwardingRule::specificity).reversed()
.thenComparing(DnsForwardingRule::domainName));
return List.copyOf(rules);
}
private static Optional<DnsForwardingRule> forwardingRuleFor(ObjectNode rule) {
String domainName = text(rule, "DomainName");
if (domainName == null || domainName.isBlank()) {
return Optional.empty();
}
String ruleType = text(rule, "RuleType");
return switch (ruleType == null ? "" : ruleType) {
case "FORWARD" -> targetsOf(rule).map(targets -> DnsForwardingRule.forwardTo(domainName, targets));
case "SYSTEM", "RECURSIVE" -> Optional.of(DnsForwardingRule.system(domainName));
default -> Optional.empty();
};
}
/**
* The rule's IPv4 targets. {@code Ipv6} targets are skipped because the embedded DNS server
* binds and forwards over IPv4 only, and a rule left with no usable target is dropped rather
* than applied, so its queries resolve as they would without it.
*/
private static Optional<List<DnsForwardingRule.Target>> targetsOf(ObjectNode rule) {
List<DnsForwardingRule.Target> targets = new ArrayList<>();
for (JsonNode target : rule.path("TargetIps")) {
String address = text(target, "Ip");
if (address == null || address.isBlank()) {
continue;
}
int port = target.path("Port").asInt(DnsForwardingRule.Target.DEFAULT_DNS_PORT);
targets.add(new DnsForwardingRule.Target(address.trim(),
port > 0 && port <= 65535 ? port : DnsForwardingRule.Target.DEFAULT_DNS_PORT));
}
return targets.isEmpty() ? Optional.empty() : Optional.of(targets);
}
private static String text(JsonNode node, String field) {
JsonNode value = node == null ? null : node.get(field);
return value == null || value.isNull() ? null : value.asText();
}
}
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import jakarta.enterprise.context.ApplicationScoped;
@@ -17,8 +18,13 @@ import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
/**
@@ -88,16 +94,16 @@ public class Route53ResolverService {
@Inject
public Route53ResolverService(StorageFactory storageFactory, ObjectMapper objectMapper) {
this.domainListStore = storageFactory.create("route53resolver", "route53resolver-domain-lists.json",
new TypeReference<java.util.Map<String, ObjectNode>>() {});
new TypeReference<Map<String, ObjectNode>>() {});
this.endpointStore = storageFactory.create("route53resolver", "route53resolver-endpoints.json",
new TypeReference<java.util.Map<String, ObjectNode>>() {});
new TypeReference<Map<String, ObjectNode>>() {});
this.ruleStore = storageFactory.create("route53resolver", "route53resolver-rules.json",
new TypeReference<java.util.Map<String, ObjectNode>>() {});
new TypeReference<Map<String, ObjectNode>>() {});
this.ruleAssociationStore = storageFactory.create("route53resolver",
"route53resolver-rule-associations.json", new TypeReference<java.util.Map<String, ObjectNode>>() {});
"route53resolver-rule-associations.json", new TypeReference<Map<String, ObjectNode>>() {});
this.endpointIpRequestStore = storageFactory.create("route53resolver",
"route53resolver-endpoint-ip-requests.json",
new TypeReference<java.util.Map<String, ObjectNode>>() {});
new TypeReference<Map<String, ObjectNode>>() {});
this.objectMapper = objectMapper;
}
@@ -137,7 +143,7 @@ public class Route53ResolverService {
public synchronized ObjectNode createFirewallDomainList(JsonNode request, String region, String accountId) {
String name = requireText(request, "Name", VALIDATION);
java.util.Optional<ObjectNode> replay = replayOf(domainListStore, request, region);
Optional<ObjectNode> replay = replayOf(domainListStore, request, region);
if (replay.isPresent()) {
return replay.get();
}
@@ -168,7 +174,7 @@ public class Route53ResolverService {
return domainListStore.scan(key -> true).stream().map(ObjectNode::deepCopy).toList();
}
public java.util.Optional<ObjectNode> getCustomFirewallDomainList(String id) {
public Optional<ObjectNode> getCustomFirewallDomainList(String id) {
return domainListStore.get(id).map(ObjectNode::deepCopy);
}
@@ -182,7 +188,7 @@ public class Route53ResolverService {
if (!ipAddresses.isArray() || ipAddresses.isEmpty()) {
throw new AwsException(INVALID_PARAMETER, "IpAddresses is required", 400);
}
java.util.Optional<ObjectNode> replay = replayOf(endpointStore, request, region);
Optional<ObjectNode> replay = replayOf(endpointStore, request, region);
if (replay.isPresent()) {
ObjectNode existing = replay.get();
requireReplayMatches(existing, request, "Name", "Direction", "SecurityGroupIds");
@@ -250,7 +256,7 @@ public class Route53ResolverService {
"TargetIps must contain at least one target address.", 400);
}
String domainName = text(request, "DomainName");
java.util.Optional<ObjectNode> replay = replayOf(ruleStore, request, region);
Optional<ObjectNode> replay = replayOf(ruleStore, request, region);
if (replay.isPresent()) {
requireReplayMatches(replay.get(), request,
"Name", "RuleType", "DomainName", "TargetIps", "ResolverEndpointId");
@@ -338,6 +344,75 @@ public class Route53ResolverService {
return ruleAssociationStore.scan(key -> true).stream().map(ObjectNode::deepCopy).toList();
}
/**
* The ids of the rules {@code accountId} has associated with {@code vpcId}. The DNS server reads
* these off the packet path, where there is no caller, so the account comes from the resource the
* query originated on rather than from a request context.
*
* <p>Scoped to that one account deliberately. A {@code VPCId} is not proof of ownership:
* {@code AssociateResolverRule} stores whatever VPC id the caller names, so an association made
* by another account naming this account's VPC must not steer its queries. Restricting the
* lookup to the querying account's partition is the boundary, and it costs nothing because
* {@code AssociateResolverRule} can only reference a rule that exists in the caller's own
* partition, so an association and its rule always share an account.
*
* <p>Returns ids rather than the association nodes so the DNS path does not copy a record per
* association on every query when all it needs is which rules to look at.
*/
public List<String> resolverRuleIdsAssociatedWith(String accountId, String vpcId) {
if (accountId == null || accountId.isBlank() || vpcId == null || vpcId.isBlank()) {
return List.of();
}
List<String> ruleIds = new ArrayList<>();
for (ObjectNode association : associationsForAccount(accountId)) {
String ruleId = text(association, "ResolverRuleId");
if (ruleId != null && !ruleIds.contains(ruleId) && vpcId.equals(text(association, "VPCId"))) {
ruleIds.add(ruleId);
}
}
return List.copyOf(ruleIds);
}
private List<ObjectNode> associationsForAccount(String accountId) {
if (ruleAssociationStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<ObjectNode> accountAware =
(AccountAwareStorageBackend<ObjectNode>) rawAccountAware;
return accountAware.scanForAccount(accountId, key -> true);
}
return ruleAssociationStore.scan(key -> true);
}
/**
* One of an account's resolver rules by id, but only if it belongs to {@code region}. Fetched
* rather than scanned for, so the DNS path reads only the rules an association actually named.
*
* <p>Route 53 Resolver is regional: a rule created in one region governs nothing in another. The
* stores carry no region in their keys, so the rule's own region comes from the ARN this service
* minted for it, the same place {@link #replayOf} reads it from. A stored rule with no parseable
* ARN has no region to claim and is treated as belonging to the region asking, which no create
* path can produce and which cannot leak another region's rule.
*/
public Optional<ObjectNode> resolverRuleIn(String accountId, String region, String ruleId) {
if (accountId == null || accountId.isBlank() || region == null || region.isBlank()
|| ruleId == null || ruleId.isBlank()) {
return Optional.empty();
}
return storedRule(accountId, ruleId)
.filter(rule -> region.equals(AwsArnUtils.regionOrDefault(text(rule, "Arn"), region)))
.map(ObjectNode::deepCopy);
}
private Optional<ObjectNode> storedRule(String accountId, String ruleId) {
if (ruleStore instanceof AccountAwareStorageBackend<?> rawAccountAware) {
@SuppressWarnings("unchecked")
AccountAwareStorageBackend<ObjectNode> accountAware =
(AccountAwareStorageBackend<ObjectNode>) rawAccountAware;
return accountAware.getForAccount(accountId, ruleId);
}
return ruleStore.get(ruleId);
}
/**
* AWS gives a resolver endpoint a direction-specific id prefix: {@code rslvr-in-} for
* inbound endpoints, {@code rslvr-out-} for outbound. {@code INBOUND_DELEGATION} is an
@@ -373,11 +448,11 @@ public class Route53ResolverService {
* shapes have no field for. Same intent as {@code FisService.idempotencyKey} and
* {@code BedrockAgentCoreControlService.tokenKey}, which fold the region into the key.</p>
*/
private java.util.Optional<ObjectNode> replayOf(StorageBackend<String, ObjectNode> store, JsonNode request,
private Optional<ObjectNode> replayOf(StorageBackend<String, ObjectNode> store, JsonNode request,
String region) {
String creatorRequestId = text(request, "CreatorRequestId");
if (creatorRequestId == null || creatorRequestId.isBlank()) {
return java.util.Optional.empty();
return Optional.empty();
}
String regionPrefix = "arn:" + AwsRegions.partitionFor(region) + ":route53resolver:" + region + ":";
return store.scan(key -> true).stream()
@@ -478,9 +553,9 @@ public class Route53ResolverService {
* key must not depend on it.</p>
*/
private ArrayNode normalizedIpRequests(JsonNode ipAddresses) {
List<JsonNode> entries = new java.util.ArrayList<>();
List<JsonNode> entries = new ArrayList<>();
ipAddresses.forEach(entries::add);
entries.sort(java.util.Comparator.comparing(Route53ResolverService::canonicalKey));
entries.sort(Comparator.comparing(Route53ResolverService::canonicalKey));
ArrayNode normalized = objectMapper.createArrayNode();
entries.forEach(normalized::add);
return normalized;
@@ -489,9 +564,9 @@ public class Route53ResolverService {
/** A node's contents as a string that does not depend on the order its members were written in. */
private static String canonicalKey(JsonNode node) {
if (node.isObject()) {
List<String> names = new java.util.ArrayList<>();
List<String> names = new ArrayList<>();
node.fieldNames().forEachRemaining(names::add);
java.util.Collections.sort(names);
Collections.sort(names);
StringBuilder key = new StringBuilder("{");
for (String name : names) {
key.append(name).append('=').append(canonicalKey(node.get(name))).append(';');