mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
bc15516cc0
commit
a8eedb1fd9
13 files changed
+1285
-35
No files matched your search
@@ -7,6 +7,8 @@ import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -191,6 +193,185 @@ class EmbeddedDnsServerTest {
|
||||
return DnsAnswer.records(List.of(addresses), DnsAnswer.DEFAULT_TTL_SECONDS);
|
||||
}
|
||||
|
||||
// ── planQuery: Route 53 Resolver rules ────────────────────────────────────
|
||||
|
||||
private static final String CLIENT = "172.31.0.9";
|
||||
private static final String MY_IP = "172.31.0.2";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
|
||||
@Test
|
||||
void forwardingRuleMatchesOnlyItsDomainAndTheSubdomainsBeneathIt() {
|
||||
DnsForwardingRule rule = forward("acme.example.com", "10.1.0.53");
|
||||
|
||||
assertTrue(rule.matches("acme.example.com"));
|
||||
assertTrue(rule.matches("zenith.acme.example.com."));
|
||||
assertFalse(rule.matches("example.com"));
|
||||
assertFalse(rule.matches("nadir.example.com"));
|
||||
assertFalse(rule.matches("notacme.example.com"));
|
||||
assertEquals(3, rule.specificity());
|
||||
assertTrue(forward(".", "10.1.0.53").matches("anything.example.com"));
|
||||
assertEquals(0, forward(".", "10.1.0.53").specificity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_forwardsToTheTargetsOfARuleAssociatedWithTheQueryingVpc() {
|
||||
EmbeddedDnsServer dns = withRules(List.of(),
|
||||
rules("vpc-a", forward("corp.internal", "10.1.0.53")), clientVpc("vpc-a"));
|
||||
|
||||
EmbeddedDnsServer.QueryPlan plan = dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1);
|
||||
|
||||
assertTrue(plan.answer().isEmpty());
|
||||
assertEquals(List.of(new DnsForwardingRule.Target("10.1.0.53", 53)), plan.ruleTargets());
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_ignoresARuleThatIsNotAssociatedWithTheQueryingVpc() {
|
||||
EmbeddedDnsServer dns = withRules(List.of(),
|
||||
rules("vpc-other", forward("corp.internal", "10.1.0.53")), clientVpc("vpc-a"));
|
||||
|
||||
assertEquals(EmbeddedDnsServer.QueryPlan.UPSTREAM,
|
||||
dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_appliesNoRuleWhenNoSourceClaimsTheQueryAddress() {
|
||||
EmbeddedDnsServer dns = withRules(List.of(),
|
||||
rules("vpc-a", forward("corp.internal", "10.1.0.53")),
|
||||
clientAddress -> Optional.empty());
|
||||
|
||||
assertEquals(EmbeddedDnsServer.QueryPlan.UPSTREAM,
|
||||
dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_appliesNoRuleWhenTheQueryOriginIsIncomplete() {
|
||||
DnsForwardingRuleSource anyOrigin = (accountId, region, vpcId) ->
|
||||
List.of(forward("corp.internal", "10.1.0.53"));
|
||||
|
||||
for (DnsClientVpcSource.ClientVpc partial : List.of(
|
||||
new DnsClientVpcSource.ClientVpc(ACCOUNT, REGION, ""),
|
||||
new DnsClientVpcSource.ClientVpc(ACCOUNT, "", "vpc-a"),
|
||||
new DnsClientVpcSource.ClientVpc("", REGION, "vpc-a"))) {
|
||||
EmbeddedDnsServer dns = withRules(List.of(), anyOrigin,
|
||||
clientAddress -> Optional.of(partial));
|
||||
|
||||
assertEquals(EmbeddedDnsServer.QueryPlan.UPSTREAM,
|
||||
dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1), partial.toString());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_appliesTheMoreSpecificOfTwoMatchingRules() {
|
||||
EmbeddedDnsServer dns = withRules(List.of(),
|
||||
rules("vpc-a", forward("corp.internal", "10.1.0.53"),
|
||||
forward("db.corp.internal", "10.2.0.53")),
|
||||
clientVpc("vpc-a"));
|
||||
|
||||
assertEquals(List.of(new DnsForwardingRule.Target("10.2.0.53", 53)),
|
||||
dns.planQuery("replica.db.corp.internal", CLIENT, MY_IP, 1).ruleTargets());
|
||||
assertEquals(List.of(new DnsForwardingRule.Target("10.1.0.53", 53)),
|
||||
dns.planQuery("web.corp.internal", CLIENT, MY_IP, 1).ruleTargets());
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_aSystemRuleCarvesASubdomainOutOfABroaderForwardRule() {
|
||||
EmbeddedDnsServer dns = withRules(
|
||||
List.of(source("acme.corp.internal", List.of("10.9.9.9"))),
|
||||
rules("vpc-a", forward("corp.internal", "10.1.0.53"),
|
||||
DnsForwardingRule.system("acme.corp.internal")),
|
||||
clientVpc("vpc-a"));
|
||||
|
||||
assertEquals(List.of("10.9.9.9"),
|
||||
dns.planQuery("acme.corp.internal", CLIENT, MY_IP, 1).answer().orElseThrow().addresses());
|
||||
assertEquals(List.of(new DnsForwardingRule.Target("10.1.0.53", 53)),
|
||||
dns.planQuery("other.corp.internal", CLIENT, MY_IP, 1).ruleTargets());
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_aMatchingRuleTakesPrecedenceOverAPrivateHostedZoneRecord() {
|
||||
EmbeddedDnsServer dns = withRules(
|
||||
List.of(source("db.corp.internal", List.of("10.0.0.7"))),
|
||||
rules("vpc-a", forward("corp.internal", "10.1.0.53")), clientVpc("vpc-a"));
|
||||
|
||||
EmbeddedDnsServer.QueryPlan plan = dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1);
|
||||
|
||||
assertTrue(plan.answer().isEmpty(), "the rule decides the name, not the zone record");
|
||||
assertEquals(List.of(new DnsForwardingRule.Target("10.1.0.53", 53)), plan.ruleTargets());
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_aPrivateHostedZoneRecordAnswersWhenNoRuleIsAssociated() {
|
||||
EmbeddedDnsServer dns = withRules(
|
||||
List.of(source("db.corp.internal", List.of("10.0.0.7"))),
|
||||
rules("vpc-other", forward("corp.internal", "10.1.0.53")), clientVpc("vpc-a"));
|
||||
|
||||
assertEquals(List.of("10.0.0.7"),
|
||||
dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1).answer().orElseThrow().addresses());
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_aNameMatchingNoRuleStillGoesToTheUpstreamResolvers() {
|
||||
EmbeddedDnsServer dns = withRules(
|
||||
List.of(source("db.corp.internal", List.of("10.0.0.7"))),
|
||||
rules("vpc-a", forward("corp.internal", "10.1.0.53")), clientVpc("vpc-a"));
|
||||
|
||||
assertEquals(EmbeddedDnsServer.QueryPlan.UPSTREAM, dns.planQuery("example.com", CLIENT, MY_IP, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_neverForwardsTheEmulatorsOwnNames() {
|
||||
EmbeddedDnsServer dns = withRules(List.of(), rules("vpc-a", forward(".", "10.1.0.53")),
|
||||
clientVpc("vpc-a"));
|
||||
|
||||
assertEquals(List.of(MY_IP),
|
||||
dns.planQuery("bucket.localhost.floci.io", CLIENT, MY_IP, 1).answer().orElseThrow().addresses());
|
||||
assertEquals(List.of("172.16.128.9"),
|
||||
dns.planQuery("ip-172-16-128-9.ec2.internal", CLIENT, MY_IP, 1).answer().orElseThrow().addresses());
|
||||
assertEquals(List.of(new DnsForwardingRule.Target("10.1.0.53", 53)),
|
||||
dns.planQuery("example.com", CLIENT, MY_IP, 1).ruleTargets());
|
||||
}
|
||||
|
||||
@Test
|
||||
void planQuery_keepsResolvingWhenARuleSourceThrows() {
|
||||
DnsForwardingRuleSource failing = (accountId, region, vpcId) -> {
|
||||
throw new IllegalStateException("storage is down");
|
||||
};
|
||||
EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of("localhost.floci.io"),
|
||||
List.of(source("db.corp.internal", List.of("10.0.0.7"))),
|
||||
List.of(failing), List.of(clientVpc("vpc-a")));
|
||||
|
||||
assertEquals(List.of("10.0.0.7"),
|
||||
dns.planQuery("db.corp.internal", CLIENT, MY_IP, 1).answer().orElseThrow().addresses());
|
||||
}
|
||||
|
||||
private static EmbeddedDnsServer withRules(List<DnsRecordSource> recordSources,
|
||||
DnsForwardingRuleSource ruleSource,
|
||||
DnsClientVpcSource clientVpcSource) {
|
||||
return new EmbeddedDnsServer(List.of("localhost.floci.io"), recordSources,
|
||||
List.of(ruleSource), List.of(clientVpcSource));
|
||||
}
|
||||
|
||||
/** Returns the rules most specific first, as {@link DnsForwardingRuleSource} asks sources to. */
|
||||
private static DnsForwardingRuleSource rules(String associatedVpcId, DnsForwardingRule... rules) {
|
||||
List<DnsForwardingRule> ordered = Arrays.stream(rules)
|
||||
.sorted(Comparator.comparingInt(DnsForwardingRule::specificity).reversed())
|
||||
.toList();
|
||||
return (accountId, region, vpcId) -> ACCOUNT.equals(accountId) && REGION.equals(region)
|
||||
&& associatedVpcId.equals(vpcId) ? ordered : List.of();
|
||||
}
|
||||
|
||||
private static DnsClientVpcSource clientVpc(String vpcId) {
|
||||
return clientAddress -> CLIENT.equals(clientAddress)
|
||||
? Optional.of(new DnsClientVpcSource.ClientVpc(ACCOUNT, REGION, vpcId))
|
||||
: Optional.empty();
|
||||
}
|
||||
|
||||
private static DnsForwardingRule forward(String domainName, String... targets) {
|
||||
return DnsForwardingRule.forwardTo(domainName,
|
||||
Arrays.stream(targets).map(DnsForwardingRule.Target::new).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildAResponse_usesTheDefaultTtlForFlociNames() {
|
||||
DnsAnswer answer = dns.resolveARecordWithOwnership(
|
||||
@@ -418,6 +599,15 @@ class EmbeddedDnsServerTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardToTargets_throwsWhenEveryTargetIsUnreachable() {
|
||||
// Nothing listens on port 1 of the loopback, so every target fails and the caller decides
|
||||
// what a failed rule means rather than silently getting an upstream answer.
|
||||
assertThrows(Exception.class, () -> EmbeddedDnsServer.forwardToTargets(
|
||||
buildQuery("db.corp.internal", (short) 8),
|
||||
List.of(new DnsForwardingRule.Target("127.0.0.1", 1))));
|
||||
}
|
||||
|
||||
/** Replies to the first datagram received with a fixed payload, on a daemon thread. */
|
||||
private void startResponder(DatagramSocket responder, byte[] responsePayload) {
|
||||
Thread t = new Thread(() -> {
|
||||
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package io.github.hectorvent.floci.core.common.dns;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
// Vert.x's DatagramSocket is the one used most here; the JDK's is qualified inline where the
|
||||
// test needs a plain blocking socket to stand in for the rule's target resolver.
|
||||
import io.vertx.core.datagram.DatagramSocket;
|
||||
import io.vertx.core.datagram.DatagramSocketOptions;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* Drives the whole packet path with a forwarding rule in place: the query really leaves the DNS
|
||||
* server over UDP, and what comes back is what the rule's target answered.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class ResolverRuleDnsPacketTest {
|
||||
|
||||
private static final String CLIENT = "127.0.0.1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String VPC_ID = "vpc-0dns0000";
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@Test
|
||||
void aForwardedQueryIsAnsweredByTheRulesTarget() throws Exception {
|
||||
byte[] request = buildQuery("db.corp.internal");
|
||||
byte[] targetAnswer = answerFor(request, "10.4.0.11");
|
||||
|
||||
try (java.net.DatagramSocket target = new java.net.DatagramSocket(0, InetAddress.getByName(CLIENT))) {
|
||||
respondOnce(target, targetAnswer);
|
||||
EmbeddedDnsServer dns = serverForwarding("corp.internal", target.getLocalPort());
|
||||
|
||||
byte[] response = query(dns, request);
|
||||
|
||||
assertArrayEquals(targetAnswer, response,
|
||||
"the answer the rule's target gave must reach the client unchanged");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreachableRuleTargetsFailOnlyTheQueryTheRuleMatched() throws Exception {
|
||||
// Port 1 on the loopback has no resolver on it, so every target of the rule fails.
|
||||
EmbeddedDnsServer dns = serverForwarding("corp.internal", 1);
|
||||
|
||||
byte[] failed = query(dns, buildQuery("db.corp.internal"));
|
||||
assertEquals(2, ByteBuffer.wrap(failed).getShort(2) & 0x000F, "SERVFAIL for the rule's name");
|
||||
assertEquals(0, ByteBuffer.wrap(failed).getShort(2) & 0x0400,
|
||||
"Floci is not the authority for a name a rule sends elsewhere");
|
||||
|
||||
byte[] request = buildQuery("api.sapphire.internal");
|
||||
byte[] resolved = query(dns, request);
|
||||
assertEquals(0, ByteBuffer.wrap(resolved).getShort(2) & 0x000F);
|
||||
assertEquals(1, ByteBuffer.wrap(resolved).getShort(6));
|
||||
assertArrayEquals(new byte[]{(byte) 172, 31, 0, 6},
|
||||
Arrays.copyOfRange(resolved, request.length + 12, request.length + 16));
|
||||
}
|
||||
|
||||
private EmbeddedDnsServer serverForwarding(String domainName, int targetPort) {
|
||||
DnsForwardingRule rule = DnsForwardingRule.forwardTo(domainName,
|
||||
List.of(new DnsForwardingRule.Target(CLIENT, targetPort)));
|
||||
DnsRecordSource records = name -> "api.sapphire.internal".equals(name)
|
||||
? Optional.of(DnsAnswer.records(List.of("172.31.0.6"), 60)) : Optional.empty();
|
||||
return new EmbeddedDnsServer(List.of(), List.of(records),
|
||||
List.of((accountId, region, vpcId) -> ACCOUNT.equals(accountId)
|
||||
&& REGION.equals(region) && VPC_ID.equals(vpcId) ? List.of(rule) : List.of()),
|
||||
List.of(clientAddress ->
|
||||
Optional.of(new DnsClientVpcSource.ClientVpc(ACCOUNT, REGION, VPC_ID))));
|
||||
}
|
||||
|
||||
/** Answers the first datagram with {@code payload}, on a daemon thread. */
|
||||
private void respondOnce(java.net.DatagramSocket socket, byte[] payload) {
|
||||
Thread responder = new Thread(() -> {
|
||||
try {
|
||||
DatagramPacket received = new DatagramPacket(new byte[4096], 4096);
|
||||
socket.receive(received);
|
||||
socket.send(new DatagramPacket(payload, payload.length,
|
||||
received.getAddress(), received.getPort()));
|
||||
} catch (Exception ignored) {
|
||||
// the socket is closed when the test completes
|
||||
}
|
||||
});
|
||||
responder.setDaemon(true);
|
||||
responder.start();
|
||||
}
|
||||
|
||||
private byte[] query(EmbeddedDnsServer dns, byte[] request) throws Exception {
|
||||
DatagramSocket server = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false));
|
||||
DatagramSocket client = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false));
|
||||
try {
|
||||
server.listen(0, CLIENT).toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
server.handler(packet -> dns.handleQuery(vertx, server, packet.data().getBytes(),
|
||||
packet.sender().host(), packet.sender().port(), CLIENT));
|
||||
client.listen(0, CLIENT).toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
CompletableFuture<byte[]> received = new CompletableFuture<>();
|
||||
client.handler(packet -> received.complete(packet.data().getBytes()));
|
||||
|
||||
client.send(Buffer.buffer(request), server.localAddress().port(), CLIENT)
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
return received.get(10, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
server.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
client.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] buildQuery(String name) {
|
||||
String[] labels = name.split("\\.");
|
||||
int nameLength = 1;
|
||||
for (String label : labels) {
|
||||
nameLength += label.length() + 1;
|
||||
}
|
||||
ByteBuffer query = ByteBuffer.allocate(12 + nameLength + 4);
|
||||
query.putShort((short) 0x2468);
|
||||
query.putShort((short) 0x0100);
|
||||
query.putShort((short) 1);
|
||||
query.putShort((short) 0);
|
||||
query.putShort((short) 0);
|
||||
query.putShort((short) 0);
|
||||
for (String label : labels) {
|
||||
byte[] bytes = label.getBytes(StandardCharsets.US_ASCII);
|
||||
query.put((byte) bytes.length);
|
||||
query.put(bytes);
|
||||
}
|
||||
query.put((byte) 0);
|
||||
query.putShort((short) 1);
|
||||
query.putShort((short) 1);
|
||||
return query.array();
|
||||
}
|
||||
|
||||
/** The query echoed back as a one-answer response, which is what a real resolver would send. */
|
||||
private static byte[] answerFor(byte[] request, String address) {
|
||||
ByteBuffer response = ByteBuffer.allocate(request.length + 16);
|
||||
response.put(request);
|
||||
response.putShort(2, (short) 0x8180);
|
||||
response.putShort(6, (short) 1);
|
||||
response.position(request.length);
|
||||
response.putShort((short) 0xC00C);
|
||||
response.putShort((short) 1);
|
||||
response.putShort((short) 1);
|
||||
response.putInt(30);
|
||||
response.putShort((short) 4);
|
||||
for (String octet : address.split("\\.")) {
|
||||
response.put((byte) Integer.parseInt(octet));
|
||||
}
|
||||
return response.array();
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ 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.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;
|
||||
@@ -63,6 +64,9 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Handler;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.LogRecord;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -999,6 +1003,89 @@ class EksClusterManagerTest {
|
||||
assertTrue(instance.getTags().stream().anyMatch(t -> "eks:cluster-name".equals(t.getKey()) && "no-imds-cluster".equals(t.getValue())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterNodeAddressesResolveToTheClustersVpcForResolverRules() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("dns-cluster");
|
||||
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
|
||||
vpcConfig.setVpcId("vpc-12345678");
|
||||
cluster.setResourcesVpcConfig(vpcConfig);
|
||||
|
||||
manager.registerClusterNodeInstance(cluster, "container-dns");
|
||||
|
||||
assertEquals(Optional.of(new ClientVpc("000000000000", "us-east-1", "vpc-12345678")),
|
||||
manager.vpcForClient("172.17.0.2"));
|
||||
assertTrue(manager.vpcForClient("172.17.0.99").isEmpty());
|
||||
assertTrue(manager.vpcForClient(null).isEmpty());
|
||||
|
||||
manager.unregisterMetadataEndpoint(cluster);
|
||||
assertTrue(manager.vpcForClient("172.17.0.2").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWithoutAVpcClaimsNoAddress() {
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("no-vpc-cluster");
|
||||
|
||||
manager.registerClusterNodeInstance(cluster, "container-no-vpc");
|
||||
|
||||
assertTrue(manager.vpcForClient("172.17.0.2").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aClusterWhoseAddressesCannotBeDeterminedClaimsNoneAndSaysWhy() {
|
||||
// Inspection failing leaves resolver rules quietly not applying rather than failing
|
||||
// anything, so the warning is the only way a reader finds out. See #4538 review.
|
||||
when(dockerClient.inspectContainerCmd(anyString()))
|
||||
.thenThrow(new RuntimeException("docker is unreachable"));
|
||||
Cluster cluster = new Cluster();
|
||||
cluster.setName("unreachable-cluster");
|
||||
ResourcesVpcConfig vpcConfig = new ResourcesVpcConfig();
|
||||
vpcConfig.setVpcId("vpc-12345678");
|
||||
cluster.setResourcesVpcConfig(vpcConfig);
|
||||
|
||||
List<LogRecord> logs = captureClusterManagerLogs(
|
||||
() -> manager.registerClusterNodeInstance(cluster, "container-unreachable"));
|
||||
|
||||
assertTrue(manager.vpcForClient("172.17.0.2").isEmpty());
|
||||
// Compared by severity, not identity: JBoss LogManager has its own Level constants, so
|
||||
// its WARN is not the same object as java.util.logging's WARNING.
|
||||
assertTrue(logs.stream().anyMatch(
|
||||
record -> record.getLevel().intValue() >= Level.WARNING.intValue()
|
||||
&& String.valueOf(record.getMessage()).contains("Resolver rules will not apply")),
|
||||
"the cluster must say why its rules stopped applying, got: "
|
||||
+ logs.stream().map(LogRecord::getMessage).toList());
|
||||
}
|
||||
|
||||
private static List<LogRecord> captureClusterManagerLogs(Runnable action) {
|
||||
java.util.logging.Logger julLogger =
|
||||
java.util.logging.Logger.getLogger(EksClusterManager.class.getName());
|
||||
julLogger.setLevel(Level.ALL);
|
||||
List<LogRecord> records = new ArrayList<>();
|
||||
Handler handler = new Handler() {
|
||||
@Override
|
||||
public void publish(LogRecord record) {
|
||||
records.add(record);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void flush() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
};
|
||||
handler.setLevel(Level.ALL);
|
||||
julLogger.addHandler(handler);
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
julLogger.removeHandler(handler);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterNodeInstanceProviderFindsAndListsRegisteredInstances() {
|
||||
Cluster cluster = new Cluster();
|
||||
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package io.github.hectorvent.floci.services.route53resolver;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.core.common.dns.DnsForwardingRule;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
class Route53ResolverDnsForwardingRulesTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
@Inject
|
||||
Route53ResolverService resolverService;
|
||||
|
||||
@Inject
|
||||
Route53ResolverDnsForwardingRules forwardingRules;
|
||||
|
||||
@Inject
|
||||
ObjectMapper objectMapper;
|
||||
|
||||
private final List<String> createdRuleIds = new ArrayList<>();
|
||||
|
||||
@AfterEach
|
||||
void deleteCreatedRules() {
|
||||
for (String ruleId : createdRuleIds) {
|
||||
try {
|
||||
resolverService.deleteResolverRule(ruleId);
|
||||
} catch (Exception ignored) {
|
||||
// best-effort cleanup; the rule may already be gone
|
||||
}
|
||||
}
|
||||
createdRuleIds.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAssociatedForwardRuleCarriesItsTargetsAndTheirPorts() {
|
||||
String vpcId = uniqueVpcId();
|
||||
associate(forwardRule("corp.internal", target("10.1.0.53", null), target("10.1.0.54", 5353)), vpcId);
|
||||
|
||||
List<DnsForwardingRule> rules = forwardingRules.rulesFor(ACCOUNT, REGION, vpcId);
|
||||
|
||||
assertEquals(1, rules.size());
|
||||
assertEquals("corp.internal", rules.getFirst().domainName());
|
||||
assertEquals(List.of(new DnsForwardingRule.Target("10.1.0.53", 53),
|
||||
new DnsForwardingRule.Target("10.1.0.54", 5353)), rules.getFirst().targets());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleAppliesToNoVpcUntilItIsAssociatedWithOne() {
|
||||
createRule(forwardRule("unassociated.internal", target("10.1.0.53", null)));
|
||||
associate(forwardRule("elsewhere.internal", target("10.1.0.53", null)), uniqueVpcId());
|
||||
|
||||
assertTrue(forwardingRules.rulesFor(ACCOUNT, REGION, uniqueVpcId()).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherAccountSeesNoneOfThisAccountsAssociations() {
|
||||
// AssociateResolverRule stores whatever VPC id the caller names, so a VPC id is not proof of
|
||||
// ownership. Only the account whose partition holds the association may be steered by it,
|
||||
// otherwise any account could redirect another account's cluster DNS by naming its VPC.
|
||||
String vpcId = uniqueVpcId();
|
||||
associate(forwardRule("corp.internal", target("10.1.0.53", null)), vpcId);
|
||||
assertEquals(1, forwardingRules.rulesFor(ACCOUNT, REGION, vpcId).size());
|
||||
|
||||
assertTrue(forwardingRules.rulesFor("999999999999", REGION, vpcId).isEmpty());
|
||||
assertTrue(resolverService.resolverRuleIdsAssociatedWith("999999999999", vpcId).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noAccountRegionOrVpcMeansNoRules() {
|
||||
String vpcId = uniqueVpcId();
|
||||
associate(forwardRule("corp.internal", target("10.1.0.53", null)), vpcId);
|
||||
|
||||
assertTrue(forwardingRules.rulesFor(null, REGION, vpcId).isEmpty());
|
||||
assertTrue(forwardingRules.rulesFor(ACCOUNT, " ", vpcId).isEmpty());
|
||||
assertTrue(forwardingRules.rulesFor(ACCOUNT, REGION, " ").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleFromAnotherRegionDoesNotSteerThisRegionsQueries() {
|
||||
// Route 53 Resolver is regional: "objects that you create in one AWS Region are available
|
||||
// only in that Region". The stores carry no region in their keys, so the rule's region comes
|
||||
// from the ARN this service minted for it.
|
||||
String vpcId = uniqueVpcId();
|
||||
String ruleId = createRuleIn(forwardRule("corp.internal", target("10.1.0.53", null)), "eu-west-1");
|
||||
ObjectNode association = objectMapper.createObjectNode();
|
||||
association.put("ResolverRuleId", ruleId);
|
||||
association.put("VPCId", vpcId);
|
||||
resolverService.associateResolverRule(association);
|
||||
|
||||
assertEquals(List.of(ruleId), resolverService.resolverRuleIdsAssociatedWith(ACCOUNT, vpcId));
|
||||
assertTrue(forwardingRules.rulesFor(ACCOUNT, REGION, vpcId).isEmpty());
|
||||
assertEquals(1, forwardingRules.rulesFor(ACCOUNT, "eu-west-1", vpcId).size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSystemRuleCarriesNoTargetsAndSortsAheadOfTheBroaderForwardRule() {
|
||||
String vpcId = uniqueVpcId();
|
||||
associate(forwardRule("corp.internal", target("10.1.0.53", null)), vpcId);
|
||||
associate(systemRule("acme.corp.internal"), vpcId);
|
||||
|
||||
List<DnsForwardingRule> rules = forwardingRules.rulesFor(ACCOUNT, REGION, vpcId);
|
||||
|
||||
assertEquals(List.of("acme.corp.internal", "corp.internal"),
|
||||
rules.stream().map(DnsForwardingRule::domainName).toList());
|
||||
assertTrue(rules.getFirst().targets().isEmpty());
|
||||
assertTrue(rules.getLast().forwards());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRecursiveRuleResolvesLocallyAndADelegateRuleIsNotApplied() {
|
||||
String vpcId = uniqueVpcId();
|
||||
associate(ruleRequest("RECURSIVE", "recursive.internal"), vpcId);
|
||||
associate(ruleRequest("DELEGATE", "delegate.internal"), vpcId);
|
||||
|
||||
List<DnsForwardingRule> rules = forwardingRules.rulesFor(ACCOUNT, REGION, vpcId);
|
||||
|
||||
assertEquals(List.of("recursive.internal"),
|
||||
rules.stream().map(DnsForwardingRule::domainName).toList());
|
||||
assertTrue(rules.getFirst().targets().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aForwardRuleWithOnlyIpv6TargetsIsNotApplied() {
|
||||
String vpcId = uniqueVpcId();
|
||||
ObjectNode request = ruleRequest("FORWARD", "corp.internal");
|
||||
ObjectNode ipv6Target = objectMapper.createObjectNode();
|
||||
ipv6Target.put("Ipv6", "2001:db8::53");
|
||||
request.putArray("TargetIps").add(ipv6Target);
|
||||
associate(request, vpcId);
|
||||
|
||||
assertTrue(forwardingRules.rulesFor(ACCOUNT, REGION, vpcId).isEmpty());
|
||||
}
|
||||
|
||||
private void associate(ObjectNode ruleRequest, String vpcId) {
|
||||
ObjectNode association = objectMapper.createObjectNode();
|
||||
association.put("ResolverRuleId", createRule(ruleRequest));
|
||||
association.put("VPCId", vpcId);
|
||||
resolverService.associateResolverRule(association);
|
||||
}
|
||||
|
||||
private String createRule(ObjectNode ruleRequest) {
|
||||
return createRuleIn(ruleRequest, REGION);
|
||||
}
|
||||
|
||||
private String createRuleIn(ObjectNode ruleRequest, String region) {
|
||||
String ruleId = resolverService.createResolverRule(ruleRequest, region, ACCOUNT).get("Id").asText();
|
||||
createdRuleIds.add(ruleId);
|
||||
return ruleId;
|
||||
}
|
||||
|
||||
private ObjectNode forwardRule(String domainName, ObjectNode... targets) {
|
||||
ObjectNode request = ruleRequest("FORWARD", domainName);
|
||||
for (ObjectNode target : targets) {
|
||||
request.withArray("TargetIps").add(target);
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private ObjectNode systemRule(String domainName) {
|
||||
return ruleRequest("SYSTEM", domainName);
|
||||
}
|
||||
|
||||
private ObjectNode ruleRequest(String ruleType, String domainName) {
|
||||
ObjectNode request = objectMapper.createObjectNode();
|
||||
request.put("Name", ruleType.toLowerCase() + "-rule");
|
||||
request.put("RuleType", ruleType);
|
||||
request.put("DomainName", domainName);
|
||||
return request;
|
||||
}
|
||||
|
||||
private ObjectNode target(String ip, Integer port) {
|
||||
ObjectNode target = objectMapper.createObjectNode();
|
||||
target.put("Ip", ip);
|
||||
if (port != null) {
|
||||
target.put("Port", port);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/** A VPC id per test, so rules from other tests in the same store cannot leak into the result. */
|
||||
private static String uniqueVpcId() {
|
||||
return "vpc-" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user