Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(dns): resolve public hostnames from spawned containers (#1168)

Hector Ventura2d30641479f6
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaPublicDnsResolutionTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaPublicDnsResolutionTest.java
new file mode 100644
index 0000000000..bb7aea25cf
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaPublicDnsResolutionTest.java
@@ -0,0 +1,106 @@
+package com.floci.test;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.lambda.LambdaClient;
+import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest;
+import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest;
+import software.amazon.awssdk.services.lambda.model.FunctionCode;
+import software.amazon.awssdk.services.lambda.model.InvocationType;
+import software.amazon.awssdk.services.lambda.model.InvokeRequest;
+import software.amazon.awssdk.services.lambda.model.InvokeResponse;
+import software.amazon.awssdk.services.lambda.model.Runtime;
+
+import java.net.InetAddress;
+import java.time.Duration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
+
+/**
+ * Verifies that a Lambda container can resolve a public hostname through Floci's embedded DNS
+ * server, which forwards non-Floci names to its upstream / configured fallback resolvers.
+ *
+ * <p>Regression for <a href="https://github.com/floci-io/floci/issues/1110">#1110</a>: public
+ * lookups failed with {@code ENOTFOUND}/{@code EBUSY} because the forwarder truncated responses
+ * and spawned containers had no fallback resolver.
+ *
+ * <p>Requires Docker dispatch (docker.sock mounted) and outbound internet; self-skips otherwise.
+ */
+@DisplayName("Lambda DNS — public hostname resolution from inside container")
+class LambdaPublicDnsResolutionTest {
+
+ private static final String FUNCTION_NAME = "public-dns-probe-fn";
+ private static final String PUBLIC_HOST = "example.com";
+ private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role";
+
+ private static LambdaClient lambda;
+ private static final ObjectMapper MAPPER = new ObjectMapper();
+
+ @BeforeAll
+ static void setup() {
+ assumeTrue(TestFixtures.isLambdaDispatchAvailable(),
+ "Lambda dispatch unavailable — skipping public DNS resolution test");
+ assumeTrue(hasInternet(),
+ "No outbound internet on the test host — skipping public DNS resolution test");
+
+ lambda = TestFixtures.lambdaClient();
+ lambda.createFunction(CreateFunctionRequest.builder()
+ .functionName(FUNCTION_NAME)
+ .runtime(Runtime.NODEJS20_X)
+ .role(ROLE)
+ .handler("index.handler")
+ .timeout(30)
+ .code(FunctionCode.builder()
+ .zipFile(SdkBytes.fromByteArray(LambdaUtils.publicDnsLookupZip()))
+ .build())
+ .build());
+ }
+
+ @AfterAll
+ static void cleanup() {
+ if (lambda != null) {
+ try { lambda.deleteFunction(DeleteFunctionRequest.builder().functionName(FUNCTION_NAME).build()); } catch (Exception ignored) {}
+ lambda.close();
+ }
+ }
+
+ @Test
+ @DisplayName("Lambda resolves a public hostname via embedded DNS forwarding")
+ void lambdaResolvesPublicHostname() throws Exception {
+ String payload = MAPPER.writeValueAsString(
+ MAPPER.createObjectNode().put("host", PUBLIC_HOST));
+
+ InvokeResponse response = lambda.invoke(InvokeRequest.builder()
+ .functionName(FUNCTION_NAME)
+ .invocationType(InvocationType.REQUEST_RESPONSE)
+ .payload(SdkBytes.fromUtf8String(payload))
+ .overrideConfiguration(c -> c.apiCallTimeout(Duration.ofSeconds(30)))
+ .build());
+
+ assertThat(response.statusCode()).isEqualTo(200);
+ assertThat(response.functionError())
+ .as("public DNS lookup must not fail (ENOTFOUND/EBUSY) inside the Lambda container")
+ .isNullOrEmpty();
+
+ JsonNode result = MAPPER.readTree(response.payload().asUtf8String());
+ assertThat(result.path("resolved").asBoolean()).isTrue();
+ assertThat(result.path("address").asText())
+ .as("resolved public IP address")
+ .isNotBlank();
+ }
+
+ private static boolean hasInternet() {
+ try {
+ InetAddress.getByName(PUBLIC_HOST);
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+}
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaUtils.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaUtils.java
index c35b6d0298..336e297f34 100644
--- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaUtils.java
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/LambdaUtils.java
@@ -189,6 +189,26 @@ public final class LambdaUtils {
return createZip("index.js", code);
}
+ /**
+ * ZIP containing a Node.js handler that resolves a public hostname via {@code dns.lookup}
+ * (the same getaddrinfo path used by {@code fetch}). Receives {@code {host}} in the event.
+ * Used to verify Floci's embedded DNS forwards public lookups from inside Lambda containers
+ * (regression for https://github.com/floci-io/floci/issues/1110).
+ */
+ public static byte[] publicDnsLookupZip() {
+ String code = """
+ const dns = require('dns').promises;
+ exports.handler = async (event) => {
+ const host = (event && event.host) ? event.host : 'example.com';
+ console.log('[public-dns] resolving', host);
+ const res = await dns.lookup(host);
+ console.log('[public-dns] resolved', host, '->', res.address);
+ return { resolved: true, host, address: res.address };
+ };
+ """;
+ return createZip("index.js", code);
+ }
+
private static byte[] createZip(String filename, String content) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index 420009db29..de024b33a8 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -223,12 +223,29 @@ on its container IP. All Lambda containers launched by Floci are configured to
use it as their DNS resolver. The embedded DNS server:
- Resolves `*.localhost.floci.io` → Floci's Docker network IP
-- Forwards all other queries to the upstream resolver from `/etc/resolv.conf`
+- Forwards all other queries to the upstream resolver(s) from `/etc/resolv.conf`,
+ falling back to public resolvers so **public hostnames** (e.g.
+ `business-api.tiktok.com`) resolve from inside Lambda containers
No extra configuration or `cap_add` is needed — Docker containers have
`CAP_NET_BIND_SERVICE` in their default capability set, so Floci (running as a
non-root user) can bind UDP/53 without any changes to your Compose file.
+!!! note "Resolving public hostnames from Lambda"
+ A Lambda whose handler reaches a public host (`fetch()`/HTTPS to e.g.
+ `business-api.tiktok.com`) resolves it through Floci's embedded DNS. As a
+ safety net, Floci also appends configurable public resolvers (default
+ `8.8.8.8`, `8.8.4.4`) after its own IP on each spawned container's DNS list,
+ so name resolution still works if the embedded forwarder cannot answer.
+
+ Tune or disable this for offline / locked-down networks where those resolvers
+ are blocked:
+
+ ```bash
+ FLOCI_DNS_CONTAINER_FALLBACK_SERVERS=1.1.1.1,1.0.0.1 # use different resolvers
+ FLOCI_DNS_CONTAINER_FALLBACK_ENABLED=false # inject only Floci's DNS
+ ```
+
!!! tip "Docker Compose service names"
If Floci runs as a Docker Compose service, set `FLOCI_HOSTNAME` to the
service name, for example `FLOCI_HOSTNAME=floci`. When no explicit Lambda
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index c720e97614..fe6f02fcb0 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -91,6 +91,32 @@ public interface EmulatorConfig {
* </pre>
*/
Optional<List<String>> extraSuffixes();
+
+ /**
+ * When {@code true} (default), the configured {@link #containerFallbackServers()} are
+ * appended after Floci's embedded DNS to every spawned container's {@code HostConfig.Dns}.
+ * This gives Lambda/CodeBuild/etc. a real secondary resolver so public hostnames still
+ * resolve if Floci's embedded forwarder cannot answer — mirroring the
+ * {@code docker run --dns <FlociIP> --dns 8.8.8.8} workaround.
+ *
+ * <p>Disable (via {@code FLOCI_DNS_CONTAINER_FALLBACK_ENABLED=false}) in offline or
+ * locked-down networks where the public resolvers are unreachable/blocked.
+ */
+ @WithDefault("true")
+ boolean containerFallbackEnabled();
+
+ /**
+ * Ordered list of public DNS resolvers used both as the fallback upstream for Floci's
+ * embedded DNS forwarder and (when {@link #containerFallbackEnabled()}) as the secondary
+ * resolvers injected into spawned containers.
+ *
+ * <p>Via environment variable (comma-separated):
+ * <pre>
+ * FLOCI_DNS_CONTAINER_FALLBACK_SERVERS=1.1.1.1,1.0.0.1
+ * </pre>
+ */
+ @WithDefault("8.8.8.8,8.8.4.4")
+ List<String> containerFallbackServers();
}
interface SecurityConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
index 04479b45e6..f2c72db66d 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java
@@ -11,6 +11,7 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.nio.ByteBuffer;
@@ -31,8 +32,10 @@ import java.util.SequencedSet;
* Docker network IP so virtual-hosted S3 URLs (my-bucket.floci:4566) work from
* inside Lambda containers without requiring wildcard Docker aliases.
*
- * All other queries are forwarded transparently to the upstream resolver read from
- * /etc/resolv.conf (Docker's embedded DNS at 127.0.0.11).
+ * 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
+ * resolv.conf resolver does not answer.
*
* Only starts when Floci detects it is running inside Docker. No-op on the host.
*/
@@ -44,6 +47,13 @@ public class EmbeddedDnsServer {
private static final int DNS_PORT = 53;
private static final int TTL = 60;
private static final String FALLBACK_UPSTREAM = "127.0.0.11";
+ // EDNS0-capable resolvers (Node/c-ares, glibc) advertise UDP payloads well above the
+ // legacy 512-byte limit; CDN-backed public names return larger responses. Receiving into
+ // a 512-byte buffer silently truncates the datagram and corrupts the forwarded answer.
+ private static final int MAX_DNS_UDP_RESPONSE = 4096;
+ // Per-upstream timeout. Bounded so trying every upstream stays under a typical 5s client
+ // resolver timeout even in the worst case.
+ private static final int FORWARD_TIMEOUT_MS = 1500;
public static final String DEFAULT_SUFFIX = "localhost.floci.io";
public static final String LOCALSTACK_SUFFIX = "localhost.localstack.cloud";
@@ -56,7 +66,7 @@ public class EmbeddedDnsServer {
private volatile String serverIp;
private final SequencedSet<String> suffixes = new LinkedHashSet<>();
- private String upstreamDns;
+ private volatile List<String> upstreamDnsServers = List.of();
EmbeddedDnsServer(List<String> suffixes) {
this.suffixes.addAll(BUILTIN_SUFFIXES);
@@ -70,7 +80,8 @@ public class EmbeddedDnsServer {
}
try {
String myIp = InetAddress.getLocalHost().getHostAddress();
- upstreamDns = readUpstreamDns();
+ upstreamDnsServers = composeUpstreams(readResolvConfNameservers(),
+ config.dns().containerFallbackServers());
suffixes.addAll(BUILTIN_SUFFIXES);
config.hostname().ifPresent(suffixes::add);
@@ -208,41 +219,85 @@ public class EmbeddedDnsServer {
private void forwardAsync(Vertx vertx, DatagramSocket socket, byte[] query,
String senderHost, int senderPort) {
- String upstream = upstreamDns;
- if (upstream == null) {
+ List<String> upstreams = upstreamDnsServers;
+ if (upstreams.isEmpty()) {
return;
}
- vertx.executeBlocking(() -> {
+ vertx.executeBlocking(() -> forwardToUpstreams(query, upstreams, DNS_PORT))
+ .onSuccess(response ->
+ socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {}))
+ .onFailure(e ->
+ LOG.warnv("DNS forwarding failed on all upstreams {0}: {1}",
+ upstreams, e.getMessage()));
+ }
+
+ /**
+ * 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}.
+ */
+ byte[] forwardToUpstreams(byte[] query, List<String> upstreams, int upstreamPort) throws Exception {
+ Exception last = null;
+ for (String upstream : upstreams) {
try (java.net.DatagramSocket fwd = new java.net.DatagramSocket()) {
- fwd.setSoTimeout(2000);
+ fwd.setSoTimeout(FORWARD_TIMEOUT_MS);
InetAddress addr = InetAddress.getByName(upstream);
- fwd.send(new DatagramPacket(query, query.length, addr, DNS_PORT));
- byte[] buf = new byte[512];
+ fwd.send(new DatagramPacket(query, query.length, addr, upstreamPort));
+ 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());
}
- }).onSuccess(response ->
- socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {})
- ).onFailure(e ->
- LOG.debugv("DNS forwarding to {0} failed: {1}", upstream, e.getMessage())
- );
+ }
+ throw last != null ? last : new IOException("no upstream resolvers configured");
+ }
+
+ /**
+ * Builds the ordered, de-duplicated upstream list the forwarder tries in turn: the
+ * resolver(s) from {@code /etc/resolv.conf} first (or Docker's embedded resolver as a
+ * baseline when none are usable), then the configured public fallbacks. The fallbacks let
+ * public names resolve even when the resolv.conf resolver does not answer, mirroring the
+ * {@code --dns <FlociIP> --dns 8.8.8.8} workaround.
+ */
+ static List<String> composeUpstreams(List<String> resolvConf, List<String> fallbacks) {
+ SequencedSet<String> ordered = new LinkedHashSet<>();
+ for (String server : resolvConf) {
+ if (isUsableUpstream(server)) {
+ ordered.add(server.trim());
+ }
+ }
+ if (ordered.isEmpty()) {
+ ordered.add(FALLBACK_UPSTREAM);
+ }
+ if (fallbacks != null) {
+ for (String server : fallbacks) {
+ if (isUsableUpstream(server)) {
+ ordered.add(server.trim());
+ }
+ }
+ }
+ return List.copyOf(ordered);
+ }
+
+ private static boolean isUsableUpstream(String server) {
+ return server != null && !server.isBlank() && !server.trim().equals("127.0.0.1");
}
- private String readUpstreamDns() {
+ private List<String> readResolvConfNameservers() {
+ List<String> servers = new ArrayList<>();
try {
for (String line : Files.readAllLines(Path.of("/etc/resolv.conf"))) {
line = line.trim();
if (line.startsWith("nameserver ")) {
- String server = line.substring("nameserver ".length()).trim();
- if (!server.equals("127.0.0.1")) {
- return server;
- }
+ servers.add(line.substring("nameserver ".length()).trim());
}
}
} catch (Exception e) {
LOG.debugv("Could not read /etc/resolv.conf: {0}", e.getMessage());
}
- return FALLBACK_UPSTREAM;
+ return servers;
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
index bb6cab62f9..f8b96eb81f 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
@@ -319,9 +319,22 @@ public class ContainerBuilder {
* Injects Floci's embedded DNS server into the container so virtual-hosted
* S3 hostnames (my-bucket.localhost.floci.io) resolve to Floci's Docker
* network IP. No-op when the embedded DNS server is not running.
+ *
+ * <p>When {@code floci.dns.container-fallback-enabled} is set, the configured public
+ * fallback resolvers are appended after Floci's IP so the container's own resolver can
+ * fall through for public hostnames if Floci's embedded forwarder cannot answer.
*/
public Builder withEmbeddedDns() {
- embeddedDnsServer.getServerIp().ifPresent(dnsServers::add);
+ embeddedDnsServer.getServerIp().ifPresent(flociIp -> {
+ dnsServers.add(flociIp);
+ if (config.dns().containerFallbackEnabled()) {
+ for (String fallback : config.dns().containerFallbackServers()) {
+ if (fallback != null && !fallback.isBlank() && !dnsServers.contains(fallback.trim())) {
+ dnsServers.add(fallback.trim());
+ }
+ }
+ }
+ });
return this;
}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index bb62b3dffd..d1f8506256 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -93,6 +93,15 @@ floci:
# extra-suffixes:
# - localhost.localstack.cloud
+ # Public resolvers appended after Floci's embedded DNS on spawned containers' HostConfig.Dns,
+ # and used as the fallback upstream for Floci's own DNS forwarder. Lets Lambda/CodeBuild
+ # resolve public hostnames even if the embedded forwarder cannot answer.
+ # Disable in offline/locked-down networks where these resolvers are blocked.
+ container-fallback-enabled: true # FLOCI_DNS_CONTAINER_FALLBACK_ENABLED
+ container-fallback-servers: # FLOCI_DNS_CONTAINER_FALLBACK_SERVERS=1.1.1.1,1.0.0.1
+ - 8.8.8.8
+ - 8.8.4.4
+
auth:
validate-signatures: false
presign-secret: local-emulator-secret
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java
index 4c9563eeda..fdbd346946 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java
@@ -3,6 +3,9 @@ package io.github.hectorvent.floci.core.common.dns;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import java.net.DatagramPacket;
+import java.net.DatagramSocket;
+import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.List;
@@ -194,6 +197,83 @@ class EmbeddedDnsServerTest {
assertEquals((byte) 42, resp.get());
}
+ // ── composeUpstreams — forwarder upstream ordering ────────────────────────
+
+ @Test
+ void composeUpstreams_resolvConfFirstThenFallbacks() {
+ List<String> upstreams = EmbeddedDnsServer.composeUpstreams(
+ List.of("192.168.65.7"), List.of("8.8.8.8", "8.8.4.4"));
+ assertEquals(List.of("192.168.65.7", "8.8.8.8", "8.8.4.4"), upstreams);
+ }
+
+ @Test
+ void composeUpstreams_usesDockerResolverBaselineWhenResolvConfEmpty() {
+ List<String> upstreams = EmbeddedDnsServer.composeUpstreams(
+ List.of(), List.of("8.8.8.8"));
+ // Docker's embedded resolver is the baseline, then the configured fallback.
+ assertEquals(List.of("127.0.0.11", "8.8.8.8"), upstreams);
+ }
+
+ @Test
+ void composeUpstreams_skipsLoopbackAndBlankEntries() {
+ List<String> upstreams = EmbeddedDnsServer.composeUpstreams(
+ List.of("127.0.0.1", " ", "10.0.0.2"), List.of("", "8.8.8.8"));
+ assertEquals(List.of("10.0.0.2", "8.8.8.8"), upstreams);
+ }
+
+ @Test
+ void composeUpstreams_dedupesAcrossResolvConfAndFallbacks() {
+ List<String> upstreams = EmbeddedDnsServer.composeUpstreams(
+ List.of("8.8.8.8"), List.of("8.8.8.8", "8.8.4.4"));
+ assertEquals(List.of("8.8.8.8", "8.8.4.4"), upstreams);
+ }
+
+ @Test
+ void composeUpstreams_toleratesNullFallbacks() {
+ List<String> upstreams = EmbeddedDnsServer.composeUpstreams(List.of("10.0.0.2"), null);
+ assertEquals(List.of("10.0.0.2"), upstreams);
+ }
+
+ // ── forwarding — response buffer size (issue #1110 regression) ────────────
+
+ @Test
+ void forwardToUpstreams_returnsResponseLargerThan512BytesIntact() throws Exception {
+ // Regression guard: a 512-byte receive buffer silently truncated EDNS0 responses from
+ // CDN-backed public hosts, corrupting the answer forwarded back to the Lambda container.
+ byte[] bigResponse = new byte[1500];
+ for (int i = 0; i < bigResponse.length; i++) {
+ bigResponse[i] = (byte) (i & 0xFF);
+ }
+
+ try (DatagramSocket responder = new DatagramSocket(0, InetAddress.getByName("127.0.0.1"))) {
+ startResponder(responder, bigResponse);
+ byte[] query = buildQuery("business-api.tiktok.com", (short) 0x1234);
+
+ byte[] response = dns.forwardToUpstreams(
+ query, List.of("127.0.0.1"), responder.getLocalPort());
+
+ assertEquals(bigResponse.length, response.length,
+ "response larger than 512 bytes must be forwarded without truncation");
+ assertArrayEquals(bigResponse, response);
+ }
+ }
+
+ /** 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(() -> {
+ try {
+ DatagramPacket req = new DatagramPacket(new byte[4096], 4096);
+ responder.receive(req);
+ responder.send(new DatagramPacket(
+ responsePayload, responsePayload.length, req.getAddress(), req.getPort()));
+ } catch (Exception ignored) {
+ // socket closed when the test completes
+ }
+ });
+ t.setDaemon(true);
+ t.start();
+ }
+
// ── helpers ───────────────────────────────────────────────────────────────
private byte[] encodeName(String name) {
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java
index e9fa9a4b35..d3fa41feff 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilderTest.java
@@ -4,6 +4,7 @@ import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
import org.junit.jupiter.api.Test;
+import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -49,10 +50,48 @@ class ContainerBuilderTest {
assertEquals("avoxx-network", spec.networkMode());
}
+ @Test
+ void withEmbeddedDns_appendsFallbackResolversAfterFlociIp() {
+ TestFixture fixture = new TestFixture();
+ when(fixture.embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.18.0.4"));
+
+ ContainerSpec spec = fixture.builder.newContainer("alpine")
+ .withEmbeddedDns()
+ .build();
+
+ assertEquals(List.of("172.18.0.4", "8.8.8.8", "8.8.4.4"), spec.dnsServers());
+ }
+
+ @Test
+ void withEmbeddedDns_omitsFallbackResolversWhenDisabled() {
+ TestFixture fixture = new TestFixture();
+ when(fixture.embeddedDnsServer.getServerIp()).thenReturn(Optional.of("172.18.0.4"));
+ when(fixture.dns.containerFallbackEnabled()).thenReturn(false);
+
+ ContainerSpec spec = fixture.builder.newContainer("alpine")
+ .withEmbeddedDns()
+ .build();
+
+ assertEquals(List.of("172.18.0.4"), spec.dnsServers());
+ }
+
+ @Test
+ void withEmbeddedDns_noOpWhenEmbeddedDnsNotRunning() {
+ TestFixture fixture = new TestFixture();
+ // getServerIp() empty (default) — no Floci IP, so no fallbacks are injected either.
+
+ ContainerSpec spec = fixture.builder.newContainer("alpine")
+ .withEmbeddedDns()
+ .build();
+
+ assertEquals(List.of(), spec.dnsServers());
+ }
+
private static class TestFixture {
final EmulatorConfig config = mock(EmulatorConfig.class);
final EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
final EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
+ final EmulatorConfig.DnsConfig dns = mock(EmulatorConfig.DnsConfig.class);
final DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
final EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class);
final CurrentContainerNetworkResolver currentContainerNetworkResolver =
@@ -66,6 +105,9 @@ class ContainerBuilderTest {
when(config.docker()).thenReturn(docker);
when(docker.logMaxSize()).thenReturn("10m");
when(docker.logMaxFile()).thenReturn("3");
+ when(config.dns()).thenReturn(dns);
+ when(dns.containerFallbackEnabled()).thenReturn(true);
+ when(dns.containerFallbackServers()).thenReturn(List.of("8.8.8.8", "8.8.4.4"));
when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty());
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
index 469508e056..e47f38ded7 100644
--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeSchedulerIntegrationTest.java
@@ -299,7 +299,16 @@ class EventBridgeSchedulerIntegrationTest {
@Override
public StorageConfig storage() { return null; }
@Override
- public DnsConfig dns() { return Optional::empty; }
+ public DnsConfig dns() {
+ return new DnsConfig() {
+ @Override
+ public Optional<List<String>> extraSuffixes() { return Optional.empty(); }
+ @Override
+ public boolean containerFallbackEnabled() { return true; }
+ @Override
+ public List<String> containerFallbackServers() { return List.of("8.8.8.8", "8.8.4.4"); }
+ };
+ }
@Override
public AuthConfig auth() { return null; }
@Override