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

Lambda/CodeBuild containers get Floci's IP as their only DNS, so all
public-name resolution flows through Floci's embedded UDP/53 forwarder.
The forwarder read responses into a hardcoded 512-byte buffer, silently
truncating larger EDNS0 responses (e.g. CDN-backed hosts), so public
lookups failed inside Lambda with ENOTFOUND/EBUSY.

- Enlarge the forwarder receive buffer to 4096 bytes (EDNS0).
- Forward across an ordered upstream list (resolv.conf + configurable
  public fallbacks), returning the first valid response; warn when all
  upstreams fail instead of dropping the response silently.
- Append configurable fallback resolvers (default 8.8.8.8, 8.8.4.4)
  after Floci's IP on spawned containers' HostConfig.Dns, controllable
  via floci.dns.container-fallback-* / FLOCI_DNS_CONTAINER_FALLBACK_*.

Closes #1110
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-06-04 00:42:38 -05:00
1 parent 7128758a63
commit 2d30641479
10 files changed
+401 -24

No files matched your search

@@ -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 {
@@ -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");
}
private String readUpstreamDns() {
/**
* 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 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;
}
}
@@ -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;
}