mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(dns): answer Cloud Map and Route 53 names when Floci runs natively (#8522)
The embedded DNS server only started when Floci ran in Docker, so a natively running Floci left <service>.<namespace>, Route 53 private zone records and its own names unresolvable, both for the containers it launches and for the host. Natively it now starts up to two listeners. On a host with a docker0 bridge it listens on that bridge's address, port 53, the address host-gateway points at, and hands it to the containers it launches as their resolver, as it does from Docker. Port 53 needs root or CAP_NET_BIND_SERVICE; without it Floci logs how to grant it and the containers keep resolving through Docker. floci.dns.bridge-listener-enabled turns it off. With floci.dns.host-port set it also listens on 127.0.0.1 at that port for the host's own resolver; that listener is never handed to containers, and it refuses names Floci does not hold rather than forwarding them, so a host resolver that routes a domain to Floci cannot get a lookup back. Each listener answers Floci's own names with its own address. Startup now waits, up to five seconds, for the listener containers are given to bind or fail, in Docker as well as natively, so a container launched right after startup is not created without Floci's resolver. Closes #2556
This commit is contained in:
1 parent
9d65db843b
commit
b0625347d8
12 files changed
+461
-61
No files matched your search
@@ -103,6 +103,17 @@ floci:
|
||||
# Via env var: FLOCI_DNS_SPOOF_AWS_ENDPOINTS=true
|
||||
spoof-aws-endpoints: false
|
||||
|
||||
# When Floci runs natively: a resolver on 127.0.0.1:<port> for the host's own resolver,
|
||||
# answering the same names (Cloud Map <service>.<namespace>, Route 53 private zones) and
|
||||
# refusing the rest.
|
||||
# Via env var: FLOCI_DNS_HOST_PORT=5354
|
||||
# host-port: 5354
|
||||
|
||||
# When Floci runs natively on a host with a docker0 bridge: listen on that bridge's
|
||||
# address, port 53, for the containers Floci launches (needs root or CAP_NET_BIND_SERVICE).
|
||||
# Via env var: FLOCI_DNS_BRIDGE_LISTENER_ENABLED=false
|
||||
bridge-listener-enabled: true
|
||||
|
||||
auth:
|
||||
validate-signatures: false # Set to true to verify SigV4 signatures for every service (S3: header, presigned URL, presigned POST; others: header)
|
||||
presign-secret: local-emulator-secret # HMAC secret for S3 pre-signed URL verification
|
||||
|
||||
@@ -151,6 +151,8 @@ Floci's embedded DNS server always resolves the following wildcard suffixes to F
|
||||
|---|---|---|
|
||||
| `FLOCI_DNS_EXTRA_SUFFIXES` | _(none)_ | Comma-separated list of additional hostname suffixes to resolve to Floci's container IP. Use this for custom domains beyond the built-in ones above (e.g. a private internal suffix). |
|
||||
| `FLOCI_DNS_SPOOF_AWS_ENDPOINTS` | `false` | Resolve every AWS partition's DNS and dual-stack suffix (`amazonaws.com`, `api.aws`, `amazonaws.eu`, and more) and every subdomain to Floci's container IP inside spawned containers (transparent endpoint injection). See below. |
|
||||
| `FLOCI_DNS_HOST_PORT` | _(none)_ | When Floci runs natively, the UDP port of a resolver on `127.0.0.1` that answers the same names, for the host's own resolver. See [Floci running natively](#floci-running-natively). |
|
||||
| `FLOCI_DNS_BRIDGE_LISTENER_ENABLED` | `true` | When Floci runs natively on a host with a `docker0` bridge, listen on that bridge's address, port 53, and give it to the containers Floci launches as their resolver. See [Floci running natively](#floci-running-natively). |
|
||||
|
||||
### Transparent endpoints
|
||||
|
||||
@@ -173,6 +175,30 @@ Combine it with `FLOCI_TLS_ENABLED=true` so hardcoded `https://` endpoints work
|
||||
|
||||
With TLS, set `FLOCI_DNS_SPOOF_AWS_ENDPOINTS` as an environment variable (or `-Dfloci.dns.spoof-aws-endpoints=true`), because the certificate generator does not read `application.yml`; Floci logs a warning at startup if the flag is only set there.
|
||||
|
||||
### Floci running natively
|
||||
|
||||
The embedded DNS server answers the names above, Cloud Map `<service>.<namespace>` names and Route 53 private zone records. When Floci runs in Docker it listens on its own container address, and publishing the container's port 53/udp (for example `-p 127.0.0.1:53:53/udp`) lets the host reach it as well.
|
||||
|
||||
When Floci runs natively, it starts up to two listeners:
|
||||
|
||||
- **For the containers it launches**, on the address of the host's `docker0` bridge, port 53, the address Docker's `host-gateway` points at. Those containers get it as their resolver, as they do when Floci runs in Docker. Binding port 53 needs root or `CAP_NET_BIND_SERVICE` (or `net.ipv4.ip_unprivileged_port_start=53`); without either, Floci logs how to grant it and the containers resolve through Docker as before. There is no such bridge on Docker Desktop or with rootless Docker, so there the containers keep resolving through Docker. `FLOCI_DNS_BRIDGE_LISTENER_ENABLED=false` turns this listener off.
|
||||
- **For the host**, on `127.0.0.1` at `FLOCI_DNS_HOST_PORT`, when it is set. Floci's own names resolve to `127.0.0.1` there. It answers only the names Floci holds and refuses every other one rather than forwarding it, so it cannot send a lookup back to the host's resolver.
|
||||
|
||||
Point the host's resolver at the host listener for the domains you use and nothing else. For a Cloud Map namespace `demo.local` on port 5354:
|
||||
|
||||
- macOS: a file `/etc/resolver/demo.local` with `nameserver 127.0.0.1` and `port 5354`.
|
||||
- dnsmasq: `server=/demo.local/127.0.0.1#5354`.
|
||||
- systemd-resolved: give the domain a link of its own that is not a default route, so no other name is sent there. A global `DNS=` in `resolved.conf` will not do: global servers also receive every name no routing domain matches, and Floci refuses those.
|
||||
|
||||
```bash
|
||||
sudo ip link add floci-dns type dummy && sudo ip link set floci-dns up
|
||||
sudo resolvectl dns floci-dns 127.0.0.1:5354
|
||||
sudo resolvectl domain floci-dns '~demo.local'
|
||||
sudo resolvectl default-route floci-dns false
|
||||
```
|
||||
|
||||
The settings go away with the link, which `ip link add` does not keep across a restart. `dig @127.0.0.1 -p 5354 api.demo.local` checks the listener directly. An instance registered with a container's Docker network address is reachable from a Linux host, not from Docker Desktop's.
|
||||
|
||||
---
|
||||
|
||||
## Initialization Hooks
|
||||
|
||||
@@ -78,10 +78,16 @@ capped at 4096 bytes. Oversized answers are truncated at whole-record boundaries
|
||||
and carry the DNS truncation flag. The embedded server remains UDP-only; TCP
|
||||
retry is not implemented.
|
||||
|
||||
Two limits are worth knowing. `HTTP` namespaces do not resolve, matching AWS,
|
||||
where they are reachable only through `DiscoverInstances`. The embedded DNS server only runs
|
||||
when Floci itself runs inside Docker, so name resolution is available to
|
||||
containers, not to processes on the host.
|
||||
`HTTP` namespaces do not resolve, matching AWS, where they are reachable only
|
||||
through `DiscoverInstances`.
|
||||
|
||||
When Floci itself runs in Docker, the containers it launches resolve these names
|
||||
through it, and publishing the Floci container's port 53/udp lets the host's
|
||||
resolver use it too. When Floci runs natively, the containers it launches resolve
|
||||
them through a listener on the Docker bridge, which needs a Linux host and
|
||||
permission to bind port 53, and the host's own resolver can be pointed at a
|
||||
listener on `127.0.0.1` set with `FLOCI_DNS_HOST_PORT`. See
|
||||
[DNS](../configuration/environment-variables.md#dns) for both.
|
||||
|
||||
## Supported Operations
|
||||
|
||||
|
||||
@@ -244,6 +244,26 @@ public interface EmulatorConfig {
|
||||
*/
|
||||
@WithDefault("false")
|
||||
boolean spoofAwsEndpoints();
|
||||
|
||||
/**
|
||||
* When Floci runs natively, the UDP port of a resolver on {@code 127.0.0.1} that answers the names the
|
||||
* embedded DNS server answers for containers, Cloud Map {@code <service>.<namespace>} and Route 53 private
|
||||
* zones among them, so the host's own resolver can be pointed at Floci for them. It refuses every other
|
||||
* name rather than forwarding it. Unset by default, which starts no listener. When Floci runs in Docker,
|
||||
* publish the container's port 53/udp instead.
|
||||
* Env: {@code FLOCI_DNS_HOST_PORT}
|
||||
*/
|
||||
OptionalInt hostPort();
|
||||
|
||||
/**
|
||||
* When Floci runs natively on a host with a {@code docker0} bridge, the embedded DNS server also listens on
|
||||
* that bridge's address, port 53, and the containers Floci launches resolve through it, as they do when
|
||||
* Floci runs in Docker. Port 53 needs root or {@code CAP_NET_BIND_SERVICE}; without either, Floci logs how
|
||||
* to grant it and the containers keep resolving through Docker.
|
||||
* Env: {@code FLOCI_DNS_BRIDGE_LISTENER_ENABLED}
|
||||
*/
|
||||
@WithDefault("true")
|
||||
boolean bridgeListenerEnabled();
|
||||
}
|
||||
|
||||
interface SecurityConfig {
|
||||
|
||||
@@ -7,6 +7,7 @@ import io.floci.aws.core.common.DomainNames;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
|
||||
import io.floci.aws.core.common.docker.DockerBridgeAddress;
|
||||
import io.quarkus.runtime.Startup;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Vertx;
|
||||
@@ -34,15 +35,19 @@ import java.util.Collections;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.SequencedSet;
|
||||
import java.util.concurrent.Callable;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Embedded UDP/53 DNS server that runs inside the Floci container and is injected
|
||||
* into every spawned container (Lambda, RDS, ElastiCache) as their DNS resolver.
|
||||
* Embedded UDP/53 DNS server that is injected into every spawned container (Lambda, RDS,
|
||||
* ElastiCache) as their DNS resolver.
|
||||
*
|
||||
* Resolves *.{floci.hostname} (and any configured extra-suffixes) to Floci's own
|
||||
* Docker network IP so virtual-hosted S3 URLs (my-bucket.floci:4566) work from
|
||||
@@ -64,7 +69,13 @@ import java.util.regex.Pattern;
|
||||
* (floci.dns.container-fallback-servers) so public hostnames still resolve when the
|
||||
* resolv.conf resolver does not answer.
|
||||
*
|
||||
* Only starts when Floci detects it is running inside Docker. No-op on the host.
|
||||
* Inside Docker it listens on Floci's own container address. When Floci runs natively it listens on
|
||||
* the {@code docker0} bridge address, port 53, for the containers it launches (when the process may
|
||||
* bind that port), and on {@code 127.0.0.1} at {@code floci.dns.host-port} for the host's own
|
||||
* resolver. Each listener answers Floci's own names with its own address; only the one for
|
||||
* containers is handed to them. The host listener answers only the names Floci holds and refuses
|
||||
* the rest instead of forwarding them: the host's resolver handles those itself, and a forwarded
|
||||
* name it routes to Floci would come straight back.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
@Startup
|
||||
@@ -72,6 +83,9 @@ public class EmbeddedDnsServer {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(EmbeddedDnsServer.class);
|
||||
static final int DNS_PORT = 53;
|
||||
static final String LOOPBACK = "127.0.0.1";
|
||||
/** How long startup waits for the listener containers are given, before any of them can be launched. */
|
||||
static final long CONTAINER_LISTENER_WAIT_SECONDS = 5;
|
||||
private static final String FALLBACK_UPSTREAM = "127.0.0.11";
|
||||
// EDNS0-capable resolvers (Node/c-ares, glibc) advertise UDP payloads well above the
|
||||
// legacy 512-byte limit; CDN-backed public names return larger responses. Receiving into
|
||||
@@ -157,50 +171,121 @@ public class EmbeddedDnsServer {
|
||||
Instance<DnsRecordSource> recordSources,
|
||||
Instance<DnsForwardingRuleSource> forwardingRuleSources,
|
||||
Instance<DnsClientVpcSource> clientVpcSources,
|
||||
CurrentContainerNetworkResolver currentContainer) {
|
||||
CurrentContainerNetworkResolver currentContainer,
|
||||
DockerBridgeAddress dockerBridge) {
|
||||
this.recordSources = recordSources;
|
||||
this.forwardingRuleSources = forwardingRuleSources;
|
||||
this.clientVpcSources = clientVpcSources;
|
||||
if (!containerDetector.isRunningInContainer()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
String myIp = ownAddress(currentContainer);
|
||||
upstreamDnsServers = composeUpstreams(readResolvConfNameservers(),
|
||||
config.dns().containerFallbackServers());
|
||||
|
||||
suffixes.addAll(BUILTIN_SUFFIXES);
|
||||
config.hostname().ifPresent(suffixes::add);
|
||||
LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()).ifPresent(suffixes::addAll);
|
||||
if (config.dns().spoofAwsEndpoints()) {
|
||||
suffixes.addAll(TlsConfigSource.awsEndpointSuffixes());
|
||||
if (shouldWarnSpoofInvisibleToTls(true, TlsConfigSource.tlsEnabledVisibleToTls(),
|
||||
TlsConfigSource.spoofAwsEndpointsVisibleToTls())) {
|
||||
LOG.warnv("floci.dns.spoof-aws-endpoints is set in application config but the TLS certificate only reads it from FLOCI_DNS_SPOOF_AWS_ENDPOINTS or -Dfloci.dns.spoof-aws-endpoints; https:// calls to {0} will fail the handshake until it is set there.", TlsConfigSource.awsEndpointSuffixes());
|
||||
if (containerDetector.isRunningInContainer()) {
|
||||
prepare(config);
|
||||
if (config.dns().hostPort().isPresent()) {
|
||||
LOG.info("floci.dns.host-port only applies when Floci runs natively; "
|
||||
+ "publish port 53/udp of the Floci container instead");
|
||||
}
|
||||
listenForContainers(vertx, ownAddress(currentContainer), false);
|
||||
return;
|
||||
}
|
||||
|
||||
listen(vertx, myIp, DNS_PORT)
|
||||
.onSuccess(socket -> LOG.infov(
|
||||
"Embedded DNS server started on {0}:53, resolving {1} → {0}", myIp, suffixes))
|
||||
.onFailure(error -> LOG.warnv(
|
||||
"Embedded DNS server failed to bind on {0}:53: {1}", myIp, error.getMessage()));
|
||||
OptionalInt hostPort = config.dns().hostPort();
|
||||
Optional<String> bridge = config.dns().bridgeListenerEnabled() ? dockerBridge.resolve() : Optional.empty();
|
||||
if (hostPort.isEmpty() && bridge.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
prepare(config);
|
||||
if (hostPort.isPresent()) {
|
||||
listenForHost(vertx, hostPort.getAsInt());
|
||||
}
|
||||
bridge.ifPresent(address -> listenForContainers(vertx, address, true));
|
||||
} catch (Exception e) {
|
||||
LOG.warnv("Failed to initialize embedded DNS server: {0}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void prepare(EmulatorConfig config) {
|
||||
upstreamDnsServers = composeUpstreams(readResolvConfNameservers(), config.dns().containerFallbackServers());
|
||||
|
||||
suffixes.addAll(BUILTIN_SUFFIXES);
|
||||
config.hostname().ifPresent(suffixes::add);
|
||||
LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()).ifPresent(suffixes::addAll);
|
||||
if (config.dns().spoofAwsEndpoints()) {
|
||||
suffixes.addAll(TlsConfigSource.awsEndpointSuffixes());
|
||||
if (shouldWarnSpoofInvisibleToTls(true, TlsConfigSource.tlsEnabledVisibleToTls(),
|
||||
TlsConfigSource.spoofAwsEndpointsVisibleToTls())) {
|
||||
LOG.warnv("floci.dns.spoof-aws-endpoints is set in application config but the TLS certificate only reads it from FLOCI_DNS_SPOOF_AWS_ENDPOINTS or -Dfloci.dns.spoof-aws-endpoints; https:// calls to {0} will fail the handshake until it is set there.", TlsConfigSource.awsEndpointSuffixes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void listenForContainers(Vertx vertx, String address, boolean onDockerBridge) {
|
||||
Future<DatagramSocket> bound = listen(vertx, address, DNS_PORT)
|
||||
.onSuccess(socket -> LOG.infov(
|
||||
"Embedded DNS server started on {0}:53, resolving {1} → {0}", address, suffixes))
|
||||
.onFailure(error -> {
|
||||
if (onDockerBridge) {
|
||||
LOG.infov("Embedded DNS server could not listen on the Docker bridge at {0}:53 ({1}), so "
|
||||
+ "the containers Floci launches keep resolving through Docker. Port 53 needs root "
|
||||
+ "or CAP_NET_BIND_SERVICE, or net.ipv4.ip_unprivileged_port_start=53; "
|
||||
+ "floci.dns.bridge-listener-enabled=false turns this listener off.",
|
||||
address, error.getMessage());
|
||||
} else {
|
||||
LOG.warnv("Embedded DNS server failed to bind on {0}:53: {1}", address, error.getMessage());
|
||||
}
|
||||
});
|
||||
awaitBind(bound, address);
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds startup until the bind succeeds or fails: until then {@link #getServerIp()} is empty, and a container
|
||||
* launched in that window would be created without Floci's resolver and never be given it.
|
||||
*/
|
||||
private static void awaitBind(Future<DatagramSocket> bound, String address) {
|
||||
try {
|
||||
bound.toCompletionStage().toCompletableFuture().get(CONTAINER_LISTENER_WAIT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (ExecutionException ignored) {
|
||||
// The failure handler has already logged why the bind failed; containers keep resolving without it.
|
||||
} catch (TimeoutException e) {
|
||||
LOG.warnv("Embedded DNS server on {0}:53 did not finish binding within {1} seconds; containers "
|
||||
+ "launched before it does are not given Floci's resolver",
|
||||
address, String.valueOf(CONTAINER_LISTENER_WAIT_SECONDS));
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
private void listenForHost(Vertx vertx, int port) {
|
||||
if (port < 1 || port > 65535) {
|
||||
LOG.warnv("Ignoring floci.dns.host-port {0}: not a port between 1 and 65535", String.valueOf(port));
|
||||
return;
|
||||
}
|
||||
bind(vertx, LOOPBACK, port, false)
|
||||
.onSuccess(socket -> LOG.infov("Embedded DNS server listening for the host on {0}:{1}",
|
||||
LOOPBACK, String.valueOf(port)))
|
||||
.onFailure(error -> LOG.warnv("Embedded DNS server failed to bind on {0}:{1}: {2}",
|
||||
LOOPBACK, String.valueOf(port), error.getMessage()));
|
||||
}
|
||||
|
||||
public Optional<String> getServerIp() {
|
||||
return Optional.ofNullable(serverIp);
|
||||
}
|
||||
|
||||
/** Starts the listener the containers Floci launches are given as their resolver. */
|
||||
Future<DatagramSocket> listen(Vertx vertx, String address, int port) {
|
||||
return bind(vertx, address, port, true).map(bound -> {
|
||||
serverIp = address;
|
||||
return bound;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a listener that answers Floci's own names with {@code address}, without handing it to containers. One
|
||||
* that does not forward refuses every name Floci does not hold.
|
||||
*/
|
||||
Future<DatagramSocket> bind(Vertx vertx, String address, int port, boolean forwardsUnknownNames) {
|
||||
DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false));
|
||||
// A wildcard bind can reply from a different interface, which DNS clients reject.
|
||||
return socket.listen(port, address).map(bound -> {
|
||||
bound.handler(packet -> handleQuery(vertx, bound, packet.data().getBytes(),
|
||||
packet.sender().host(), packet.sender().port(), address));
|
||||
serverIp = address;
|
||||
packet.sender().host(), packet.sender().port(), address, forwardsUnknownNames));
|
||||
return bound;
|
||||
});
|
||||
}
|
||||
@@ -209,6 +294,11 @@ public class EmbeddedDnsServer {
|
||||
|
||||
void handleQuery(Vertx vertx, DatagramSocket socket, byte[] data,
|
||||
String senderHost, int senderPort, String myIp) {
|
||||
handleQuery(vertx, socket, data, senderHost, senderPort, myIp, true);
|
||||
}
|
||||
|
||||
void handleQuery(Vertx vertx, DatagramSocket socket, byte[] data,
|
||||
String senderHost, int senderPort, String myIp, boolean forwardsUnknownNames) {
|
||||
try {
|
||||
ByteBuffer buf = ByteBuffer.wrap(data);
|
||||
short txId = buf.getShort();
|
||||
@@ -231,11 +321,15 @@ public class EmbeddedDnsServer {
|
||||
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 {
|
||||
if (!plan.ruleTargets().isEmpty()) {
|
||||
forwardToRuleTargets(vertx, socket, data, senderHost, senderPort,
|
||||
plan.ruleTargets(), qname, txId, questionOffset, questionEnd);
|
||||
} else if (forwardsUnknownNames) {
|
||||
forwardAsync(vertx, socket, data, senderHost, senderPort);
|
||||
} else {
|
||||
byte[] refused = buildPublicResponse(data, txId, questionOffset, questionEnd,
|
||||
DnsAnswer.refused());
|
||||
socket.send(Buffer.buffer(refused), senderPort, senderHost, v -> {});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The host's IPv4 address on Docker's default bridge, {@code docker0}: where {@code host-gateway} points unless the
|
||||
* daemon sets {@code host-gateway-ip}, so it is the address a container reaches a natively running Floci at. Empty
|
||||
* where the host has no such interface, as with Docker Desktop or rootless Docker, whose bridge lives inside a VM or
|
||||
* a namespace.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class DockerBridgeAddress {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DockerBridgeAddress.class);
|
||||
static final String INTERFACE_NAME = "docker0";
|
||||
|
||||
public Optional<String> resolve() {
|
||||
try {
|
||||
NetworkInterface bridge = NetworkInterface.getByName(INTERFACE_NAME);
|
||||
return bridge == null ? Optional.empty() : firstIpv4(bridge.inetAddresses());
|
||||
} catch (SocketException e) {
|
||||
LOG.debugv("Could not read the {0} interface: {1}", INTERFACE_NAME, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
static Optional<String> firstIpv4(Stream<InetAddress> addresses) {
|
||||
return addresses
|
||||
.filter(Inet4Address.class::isInstance)
|
||||
.map(InetAddress::getHostAddress)
|
||||
.findFirst();
|
||||
}
|
||||
}
|
||||
@@ -337,6 +337,17 @@ floci:
|
||||
# with a certificate covering those suffixes and their regional wildcards.
|
||||
spoof-aws-endpoints: false # FLOCI_DNS_SPOOF_AWS_ENDPOINTS
|
||||
|
||||
# When Floci runs natively: a resolver on 127.0.0.1:<port> answering the same names as the
|
||||
# embedded DNS server (Cloud Map <service>.<namespace>, Route 53 private zones), for the host's
|
||||
# own resolver to point at; other names are refused. Unset starts no listener. In Docker,
|
||||
# publish port 53/udp instead.
|
||||
# host-port: 5354 # FLOCI_DNS_HOST_PORT
|
||||
|
||||
# When Floci runs natively on a host with a docker0 bridge: also listen on that bridge's
|
||||
# address, port 53, and give it to the containers Floci launches as their resolver. Port 53
|
||||
# needs root or CAP_NET_BIND_SERVICE; without it Floci logs how to grant it.
|
||||
bridge-listener-enabled: true # FLOCI_DNS_BRIDGE_LISTENER_ENABLED
|
||||
|
||||
auth:
|
||||
validate-signatures: false
|
||||
presign-secret: local-emulator-secret
|
||||
|
||||
@@ -2,11 +2,13 @@ package io.floci.aws.core.common.dns;
|
||||
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.datagram.DatagramSocket;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledOnOs;
|
||||
import org.junit.jupiter.api.condition.OS;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.InetAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
@@ -22,9 +24,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@EnabledOnOs(OS.LINUX)
|
||||
class EmbeddedDnsReplySourceTest {
|
||||
|
||||
// The host listener (forContainers false) answers Floci's own names with its own address too, and
|
||||
// is never the address handed to the containers Floci launches.
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void replyComesFromTheQueriedAddress(boolean connectedClient) throws Exception {
|
||||
@CsvSource({"false,true", "true,true", "false,false", "true,false"})
|
||||
void replyComesFromTheQueriedAddress(boolean connectedClient, boolean forContainers) throws Exception {
|
||||
Vertx vertx = Vertx.vertx();
|
||||
EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of());
|
||||
InetAddress serverAddress = InetAddress.getByName("127.0.0.2");
|
||||
@@ -32,19 +36,16 @@ class EmbeddedDnsReplySourceTest {
|
||||
// Vert.x owns the server socket; the JDK socket models a resolver that filters its peer.
|
||||
try (java.net.DatagramSocket client =
|
||||
new java.net.DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {
|
||||
server = dns.listen(vertx, serverAddress.getHostAddress(), 0)
|
||||
String address = serverAddress.getHostAddress();
|
||||
server = (forContainers ? dns.listen(vertx, address, 0) : dns.bind(vertx, address, 0, false))
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
int serverPort = server.localAddress().port();
|
||||
assertEquals(Optional.of(serverAddress.getHostAddress()), dns.getServerIp());
|
||||
client.setSoTimeout(5000);
|
||||
assertEquals(forContainers ? Optional.of(address) : Optional.empty(), dns.getServerIp());
|
||||
if (connectedClient) {
|
||||
client.connect(serverAddress, serverPort);
|
||||
}
|
||||
byte[] request = DnsTestQuery.query(EmbeddedDnsServer.DEFAULT_SUFFIX, 1, 0x1234);
|
||||
client.send(new DatagramPacket(request, request.length, serverAddress, serverPort));
|
||||
|
||||
DatagramPacket reply = new DatagramPacket(new byte[512], 512);
|
||||
client.receive(reply);
|
||||
DatagramPacket reply = exchange(client, serverAddress, serverPort, request);
|
||||
|
||||
assertEquals(serverAddress, reply.getAddress());
|
||||
assertEquals(serverPort, reply.getPort());
|
||||
@@ -55,13 +56,49 @@ class EmbeddedDnsReplySourceTest {
|
||||
assertArrayEquals(serverAddress.getAddress(),
|
||||
Arrays.copyOfRange(reply.getData(), request.length + 12, request.length + 16));
|
||||
} finally {
|
||||
try {
|
||||
if (server != null) {
|
||||
server.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
} finally {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
close(server, vertx);
|
||||
}
|
||||
}
|
||||
|
||||
// Catches: the host listener forwarding a name Floci does not hold to the host's resolver, which a
|
||||
// resolver routing that domain to Floci sends straight back, so the lookup loops until it times out.
|
||||
@Test
|
||||
void theHostListenerRefusesNamesFlociDoesNotHold() throws Exception {
|
||||
Vertx vertx = Vertx.vertx();
|
||||
EmbeddedDnsServer dns = new EmbeddedDnsServer(List.of());
|
||||
InetAddress loopback = InetAddress.getByName(EmbeddedDnsServer.LOOPBACK);
|
||||
DatagramSocket server = null;
|
||||
try (java.net.DatagramSocket client = new java.net.DatagramSocket(0, loopback)) {
|
||||
server = dns.bind(vertx, EmbeddedDnsServer.LOOPBACK, 0, false)
|
||||
.toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
byte[] request = DnsTestQuery.query("not-held.example.invalid", 1, 0x4321);
|
||||
|
||||
DatagramPacket reply = exchange(client, loopback, server.localAddress().port(), request);
|
||||
|
||||
ByteBuffer response = ByteBuffer.wrap(reply.getData(), 0, reply.getLength());
|
||||
assertEquals((short) 0x4321, response.getShort(0));
|
||||
assertEquals(5, response.getShort(2) & 0x000F, "REFUSED");
|
||||
} finally {
|
||||
close(server, vertx);
|
||||
}
|
||||
}
|
||||
|
||||
private static DatagramPacket exchange(java.net.DatagramSocket client, InetAddress serverAddress, int serverPort,
|
||||
byte[] request) throws IOException {
|
||||
client.setSoTimeout(5000);
|
||||
client.send(new DatagramPacket(request, request.length, serverAddress, serverPort));
|
||||
DatagramPacket reply = new DatagramPacket(new byte[512], 512);
|
||||
client.receive(reply);
|
||||
return reply;
|
||||
}
|
||||
|
||||
private static void close(DatagramSocket server, Vertx vertx) throws Exception {
|
||||
try {
|
||||
if (server != null) {
|
||||
server.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
} finally {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(5, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,20 +3,33 @@ package io.floci.aws.core.common.dns;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.CurrentContainerNetworkResolver;
|
||||
import io.floci.aws.core.common.docker.DockerBridgeAddress;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.datagram.DatagramSocket;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.SocketException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -40,27 +53,125 @@ class EmbeddedDnsServerAddressTest {
|
||||
assertEquals(InetAddress.getLocalHost().getHostAddress(), EmbeddedDnsServer.ownAddress(currentContainer));
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void inAContainerTheServerAnswersAtThatAddress() {
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(true);
|
||||
CurrentContainerNetworkResolver currentContainer = mock(CurrentContainerNetworkResolver.class);
|
||||
when(currentContainer.resolveContainerIp()).thenReturn(Optional.of("172.19.0.2"));
|
||||
private final Vertx vertx = mock(Vertx.class);
|
||||
private final DatagramSocket socket = mock(DatagramSocket.class);
|
||||
private final DockerBridgeAddress dockerBridge = mock(DockerBridgeAddress.class);
|
||||
|
||||
private static EmulatorConfig config(OptionalInt hostPort, boolean bridgeListenerEnabled) {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.hostname()).thenReturn(Optional.empty());
|
||||
when(config.dns().extraSuffixes()).thenReturn(Optional.empty());
|
||||
when(config.dns().containerFallbackServers()).thenReturn(List.of());
|
||||
when(config.dns().spoofAwsEndpoints()).thenReturn(false);
|
||||
Vertx vertx = mock(Vertx.class);
|
||||
DatagramSocket socket = mock(DatagramSocket.class);
|
||||
when(config.dns().hostPort()).thenReturn(hostPort);
|
||||
when(config.dns().bridgeListenerEnabled()).thenReturn(bridgeListenerEnabled);
|
||||
return config;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private EmbeddedDnsServer server(EmulatorConfig config, boolean inContainer) {
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
when(containerDetector.isRunningInContainer()).thenReturn(inContainer);
|
||||
CurrentContainerNetworkResolver currentContainer = mock(CurrentContainerNetworkResolver.class);
|
||||
when(currentContainer.resolveContainerIp()).thenReturn(Optional.of("172.19.0.2"));
|
||||
when(vertx.createDatagramSocket(any())).thenReturn(socket);
|
||||
return new EmbeddedDnsServer(config, containerDetector, vertx, mock(Instance.class),
|
||||
mock(Instance.class), mock(Instance.class), currentContainer, dockerBridge);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inAContainerTheServerAnswersAtThatAddress() {
|
||||
when(socket.listen(53, "172.19.0.2")).thenReturn(Future.succeededFuture(socket));
|
||||
|
||||
EmbeddedDnsServer server = new EmbeddedDnsServer(config, containerDetector, vertx, mock(Instance.class),
|
||||
mock(Instance.class), mock(Instance.class), currentContainer);
|
||||
// The host port belongs to a native Floci; in Docker the container's port 53 is published instead.
|
||||
EmbeddedDnsServer server = server(config(OptionalInt.of(5354), true), true);
|
||||
|
||||
assertEquals(Optional.of("172.19.0.2"), server.getServerIp());
|
||||
verify(socket).listen(53, "172.19.0.2");
|
||||
verify(socket, never()).listen(5354, "127.0.0.1");
|
||||
verify(dockerBridge, never()).resolve();
|
||||
}
|
||||
|
||||
// Catches: a native Floci leaving the containers it launches without its resolver, so Cloud Map
|
||||
// and Route 53 private names fail in them.
|
||||
@Test
|
||||
void nativelyTheContainersResolveThroughTheDockerBridge() {
|
||||
when(dockerBridge.resolve()).thenReturn(Optional.of("172.17.0.1"));
|
||||
when(socket.listen(53, "172.17.0.1")).thenReturn(Future.succeededFuture(socket));
|
||||
|
||||
EmbeddedDnsServer server = server(config(OptionalInt.empty(), true), false);
|
||||
|
||||
assertEquals(Optional.of("172.17.0.1"), server.getServerIp());
|
||||
}
|
||||
|
||||
// Catches: the host listener handed to containers, which cannot reach the host's loopback.
|
||||
@Test
|
||||
void nativelyTheHostListenerAnswersOnLoopbackAndIsNotGivenToContainers() {
|
||||
when(socket.listen(5354, "127.0.0.1")).thenReturn(Future.succeededFuture(socket));
|
||||
|
||||
EmbeddedDnsServer server = server(config(OptionalInt.of(5354), false), false);
|
||||
|
||||
verify(socket).listen(5354, "127.0.0.1");
|
||||
assertEquals(Optional.empty(), server.getServerIp());
|
||||
}
|
||||
|
||||
// Catches: containers pointed at a bridge listener that never started, so every name they look up fails.
|
||||
@Test
|
||||
void nativelyABridgeTheProcessMayNotBindLeavesContainersResolvingThroughDocker() {
|
||||
when(dockerBridge.resolve()).thenReturn(Optional.of("172.17.0.1"));
|
||||
when(socket.listen(53, "172.17.0.1"))
|
||||
.thenReturn(Future.failedFuture(new SocketException("Permission denied")));
|
||||
|
||||
EmbeddedDnsServer server = server(config(OptionalInt.empty(), true), false);
|
||||
|
||||
assertEquals(Optional.empty(), server.getServerIp());
|
||||
}
|
||||
|
||||
// Catches: startup going on while the containers' listener is still binding, so a container launched in
|
||||
// that window is created without Floci's resolver and is never given it.
|
||||
@Test
|
||||
void startupWaitsForTheContainersListenerToBind() throws Exception {
|
||||
when(dockerBridge.resolve()).thenReturn(Optional.of("172.17.0.1"));
|
||||
Promise<DatagramSocket> bind = Promise.promise();
|
||||
CountDownLatch bindRequested = new CountDownLatch(1);
|
||||
when(socket.listen(53, "172.17.0.1")).thenAnswer(invocation -> {
|
||||
bindRequested.countDown();
|
||||
return bind.future();
|
||||
});
|
||||
|
||||
CompletableFuture<EmbeddedDnsServer> started =
|
||||
CompletableFuture.supplyAsync(() -> server(config(OptionalInt.empty(), true), false));
|
||||
assertTrue(bindRequested.await(5, TimeUnit.SECONDS));
|
||||
assertThrows(TimeoutException.class, () -> started.get(200, TimeUnit.MILLISECONDS),
|
||||
"startup must still be waiting on the bind");
|
||||
bind.complete(socket);
|
||||
|
||||
assertEquals(Optional.of("172.17.0.1"), started.get(5, TimeUnit.SECONDS).getServerIp());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nativelyWithNoBridgeAndNoHostPortNothingListens() {
|
||||
when(dockerBridge.resolve()).thenReturn(Optional.empty());
|
||||
|
||||
EmbeddedDnsServer server = server(config(OptionalInt.empty(), true), false);
|
||||
|
||||
verify(vertx, never()).createDatagramSocket(any());
|
||||
assertEquals(Optional.empty(), server.getServerIp());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBridgeListenerCanBeTurnedOff() {
|
||||
when(dockerBridge.resolve()).thenReturn(Optional.of("172.17.0.1"));
|
||||
|
||||
server(config(OptionalInt.empty(), false), false);
|
||||
|
||||
verify(socket, never()).listen(anyInt(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aHostPortOutsideThePortRangeStartsNoListener() {
|
||||
server(config(OptionalInt.of(70000), false), false);
|
||||
|
||||
verify(socket, never()).listen(anyInt(), anyString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/** The address a container reaches a natively running Floci at, read from the {@code docker0} interface. */
|
||||
class DockerBridgeAddressTest {
|
||||
|
||||
// Catches: the bridge's IPv6 link-local address handed to containers as their resolver, which
|
||||
// Docker's --dns cannot use.
|
||||
@Test
|
||||
void theBridgesIpv4AddressIsTheOne() throws UnknownHostException {
|
||||
Stream<InetAddress> addresses = Stream.of(InetAddress.getByName("fe80::1"), InetAddress.getByName("172.17.0.1"));
|
||||
|
||||
assertEquals(Optional.of("172.17.0.1"), DockerBridgeAddress.firstIpv4(addresses));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBridgeWithoutAnIpv4AddressHasNoAddress() throws UnknownHostException {
|
||||
assertEquals(Optional.empty(), DockerBridgeAddress.firstIpv4(Stream.of(InetAddress.getByName("fe80::1"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBridgeWithNoAddressHasNoAddress() {
|
||||
assertEquals(Optional.empty(), DockerBridgeAddress.firstIpv4(Stream.empty()));
|
||||
}
|
||||
}
|
||||
+5
@@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test;
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.mock;
|
||||
@@ -342,6 +343,10 @@ class EventBridgeSchedulerIntegrationTest {
|
||||
public List<String> containerFallbackServers() { return List.of("8.8.8.8", "8.8.4.4"); }
|
||||
@Override
|
||||
public boolean spoofAwsEndpoints() { return false; }
|
||||
@Override
|
||||
public OptionalInt hostPort() { return OptionalInt.empty(); }
|
||||
@Override
|
||||
public boolean bridgeListenerEnabled() { return true; }
|
||||
};
|
||||
}
|
||||
@Override
|
||||
|
||||
@@ -126,6 +126,11 @@ floci:
|
||||
strict-claiming: false
|
||||
reject-unknown-service-scope: true
|
||||
|
||||
dns:
|
||||
# Tests run natively; with the bridge listener on, a runner allowed to bind port 53 would change
|
||||
# how every container a test launches resolves names.
|
||||
bridge-listener-enabled: false
|
||||
|
||||
docker:
|
||||
log-max-size: "10m"
|
||||
log-max-file: "3"
|
||||
|
||||
Reference in new issue
Block a user