diff --git a/docker-compose.yml b/docker-compose.yml index d7365cc86b..1766738032 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -22,7 +22,7 @@ services: networks: floci_default: aliases: - - localhost.floci.cloud + - localhost.floci.io networks: floci_default: diff --git a/docs/configuration/application-yml.md b/docs/configuration/application-yml.md index 99bc585883..7d6b625ece 100644 --- a/docs/configuration/application-yml.md +++ b/docs/configuration/application-yml.md @@ -64,6 +64,15 @@ floci: opensearch: flush-interval-ms: 5000 + dns: + # Extra hostname suffixes resolved to Floci's container IP by the embedded DNS server. + # The primary suffix (floci.hostname or derived from base-url) is always included. + # Useful when migrating from LocalStack — Lambda functions that hardcode + # localhost.localstack.cloud as their endpoint work without code changes. + # Via env var (comma-separated): FLOCI_DNS_EXTRA_SUFFIXES=localhost.localstack.cloud,other.internal + # extra-suffixes: + # - localhost.localstack.cloud + auth: validate-signatures: false # Set to true to enforce AWS SigV4 validation presign-secret: local-emulator-secret # HMAC secret for S3 pre-signed URL verification @@ -226,6 +235,7 @@ All keys in this table are declared on `EmulatorConfig` and accept environment v | `FLOCI_DEFAULT_AVAILABILITY_ZONE` | `us-east-1a` | Default AZ reported by EC2, RDS, and other AZ-aware services | | `FLOCI_DEFAULT_ACCOUNT_ID` | `000000000000` | Default AWS account ID used in ARNs | | `FLOCI_ECR_BASE_URI` | `public.ecr.aws` | Base URI used when pulling container images (e.g. Lambda) | +| `FLOCI_DNS_EXTRA_SUFFIXES` | *(unset)* | Comma-separated extra hostname suffixes the embedded DNS server resolves to Floci's container IP. E.g. `localhost.localstack.cloud,localhost.example.internal` | | `FLOCI_SERVICES_SSM_MAX_PARAMETER_HISTORY` | `5` | Max parameter versions kept | | `FLOCI_SERVICES_SQS_DEFAULT_VISIBILITY_TIMEOUT` | `30` | Default visibility timeout (seconds) | | `FLOCI_SERVICES_SQS_MAX_MESSAGE_SIZE` | `262144` | Max message size (bytes) | diff --git a/docs/services/lambda.md b/docs/services/lambda.md index c56ad66b60..22d2ece871 100644 --- a/docs/services/lambda.md +++ b/docs/services/lambda.md @@ -143,6 +143,58 @@ services: - /var/run/docker.sock:/var/run/docker.sock ``` +### S3 virtual-hosted-style addressing inside Lambda containers + +AWS SDKs use **virtual-hosted-style** S3 addressing by default, forming URLs like +`https://my-bucket.s3.amazonaws.com/key`. Against Floci the same pattern becomes +`http://my-bucket.localhost.floci.io:4566/key`. + +When Floci runs **inside Docker**, Lambda containers are on the same Docker +network. Docker's embedded DNS resolves the exact alias `localhost.floci.io` +correctly, but has no wildcard support — `my-bucket.localhost.floci.io` +falls through to public DNS and resolves to the wrong IP, causing the Lambda +invocation to time out. + +**Floci solves this automatically** by running an embedded DNS server (UDP/53) +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` + +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 "Path-style as a workaround" + If you cannot use virtual-hosted-style (e.g. Floci is running natively on + the host, not in Docker), configure the SDK client with + `forcePathStyle: true` / `s3ForcePathStyle: true`. Requests will go to + `http://localhost:4566/my-bucket/key` instead and work without DNS. + +#### Migrating from LocalStack + +If your Lambda functions have `AWS_ENDPOINT_URL=http://localhost.localstack.cloud:4566` +hardcoded, add the LocalStack suffix to Floci's DNS resolver so it resolves to +Floci's IP without any function-side changes: + +```yaml +floci: + dns: + extra-suffixes: + - localhost.localstack.cloud +``` + +Via environment variable — use a comma-separated list for multiple suffixes: + +```bash +# Single suffix +FLOCI_DNS_EXTRA_SUFFIXES=localhost.localstack.cloud + +# Multiple suffixes +FLOCI_DNS_EXTRA_SUFFIXES=localhost.localstack.cloud,localhost.example.internal +``` + ### Private registry authentication Container image functions (`"PackageType": "Image"`) that pull from private registries need Docker credentials. See [Docker Configuration → Private Registry Authentication](../configuration/docker.md#private-registry-authentication) for the full guide. 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 4f4de875a7..132159af06 100644 --- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java +++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java @@ -53,6 +53,8 @@ public interface EmulatorConfig { StorageConfig storage(); + DnsConfig dns(); + AuthConfig auth(); ServicesConfig services(); @@ -61,6 +63,27 @@ public interface EmulatorConfig { InitHooksConfig initHooks(); + interface DnsConfig { + /** + * Additional hostname suffixes the embedded DNS server will resolve to Floci's + * container IP, alongside the primary {@code floci.hostname}. + * + * Useful for migrating from LocalStack without changing Lambda endpoint configuration: + *
+         * floci:
+         *   dns:
+         *     extra-suffixes:
+         *       - localhost.localstack.cloud
+         * 
+ * + * Via environment variable (comma-separated for multiple values): + *
+         * FLOCI_DNS_EXTRA_SUFFIXES=localhost.localstack.cloud,localhost.example.internal
+         * 
+ */ + Optional> extraSuffixes(); + } + interface StorageConfig { @WithDefault("hybrid") String mode(); 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 new file mode 100644 index 0000000000..bffac4e330 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServer.java @@ -0,0 +1,233 @@ +package io.github.hectorvent.floci.core.common.dns; + +import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.docker.ContainerDetector; +import io.vertx.core.Vertx; +import io.vertx.core.buffer.Buffer; +import io.vertx.core.datagram.DatagramSocket; +import io.vertx.core.datagram.DatagramSocketOptions; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +/** + * 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. + * + * 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 + * 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). + * + * Only starts when Floci detects it is running inside Docker. No-op on the host. + */ +@ApplicationScoped +public class EmbeddedDnsServer { + + private static final Logger LOG = Logger.getLogger(EmbeddedDnsServer.class); + private static final int DNS_PORT = 53; + private static final int TTL = 60; + private static final String FALLBACK_UPSTREAM = "127.0.0.11"; + + private volatile String serverIp; + private final List suffixes = new ArrayList<>(); + private String upstreamDns; + + EmbeddedDnsServer(List suffixes) { + this.suffixes.addAll(suffixes); + } + + @Inject + public EmbeddedDnsServer(EmulatorConfig config, ContainerDetector containerDetector, Vertx vertx) { + if (!containerDetector.isRunningInContainer()) { + return; + } + try { + String myIp = InetAddress.getLocalHost().getHostAddress(); + upstreamDns = readUpstreamDns(); + + config.hostname().ifPresent(suffixes::add); + config.dns().extraSuffixes().ifPresent(suffixes::addAll); + + DatagramSocket socket = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false)); + socket.listen(DNS_PORT, "0.0.0.0", ar -> { + if (ar.succeeded()) { + serverIp = myIp; + LOG.infov("Embedded DNS server started on {0}:53, resolving {1} → {0}", myIp, suffixes); + socket.handler(packet -> handleQuery( + vertx, socket, packet.data().getBytes(), + packet.sender().host(), packet.sender().port(), myIp)); + } else { + LOG.warnv("Embedded DNS server failed to bind on port 53: {0}", ar.cause().getMessage()); + } + }); + } catch (Exception e) { + LOG.warnv("Failed to initialize embedded DNS server: {0}", e.getMessage()); + } + } + + public Optional getServerIp() { + return Optional.ofNullable(serverIp); + } + + // ── packet handling ─────────────────────────────────────────────────────── + + private void handleQuery(Vertx vertx, DatagramSocket socket, byte[] data, + String senderHost, int senderPort, String myIp) { + try { + ByteBuffer buf = ByteBuffer.wrap(data); + short txId = buf.getShort(); + short flags = buf.getShort(); + short qdCount = buf.getShort(); + buf.getShort(); // ancount + buf.getShort(); // nscount + buf.getShort(); // arcount + + if ((flags & 0x8000) != 0 || qdCount < 1) { + return; // not a standard query + } + + int questionOffset = buf.position(); // always 12 for a standard query + String qname = readName(buf, data); + short qtype = buf.getShort(); + buf.getShort(); // qclass + int questionEnd = buf.position(); + + if (qtype == 1 && matchesSuffix(qname)) { + byte[] response = buildAResponse(data, txId, questionOffset, questionEnd, myIp); + socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {}); + } else { + forwardAsync(vertx, socket, data, senderHost, senderPort); + } + } catch (Exception e) { + LOG.debugv("DNS packet error: {0}", e.getMessage()); + } + } + + // ── helpers ─────────────────────────────────────────────────────────────── + + boolean matchesSuffix(String name) { + if (name == null || name.isEmpty()) { + return false; + } + String lower = name.toLowerCase(); + for (String suffix : suffixes) { + String s = suffix.toLowerCase(); + if (lower.equals(s) || lower.endsWith("." + s)) { + return true; + } + } + return false; + } + + String readName(ByteBuffer buf, byte[] data) { + StringBuilder sb = new StringBuilder(); + int safety = 0; + while (buf.hasRemaining() && safety++ < 128) { + int len = buf.get() & 0xFF; + if (len == 0) { + break; + } + if ((len & 0xC0) == 0xC0) { + // compression pointer + int offset = ((len & 0x3F) << 8) | (buf.get() & 0xFF); + ByteBuffer ptr = ByteBuffer.wrap(data); + ptr.position(offset); + if (sb.length() > 0) { + sb.append('.'); + } + sb.append(readName(ptr, data)); + return sb.toString(); + } + if (sb.length() > 0) { + sb.append('.'); + } + byte[] label = new byte[len]; + buf.get(label); + sb.append(new String(label)); + } + return sb.toString(); + } + + byte[] buildAResponse(byte[] query, short txId, int questionOffset, int questionEnd, String ip) { + int questionLength = questionEnd - questionOffset; + // header(12) + question + answer(name-ptr(2) + type(2) + class(2) + ttl(4) + rdlen(2) + rdata(4)) + ByteBuffer resp = ByteBuffer.allocate(12 + questionLength + 16); + + // header + resp.putShort(txId); + resp.putShort((short) 0x8180); // QR=1, AA=1, RD=1, RCODE=0 + resp.putShort((short) 1); // qdcount + resp.putShort((short) 1); // ancount + resp.putShort((short) 0); // nscount + resp.putShort((short) 0); // arcount + + // question (copied verbatim from query) + resp.put(query, questionOffset, questionLength); + + // answer + resp.putShort((short) 0xC00C); // name pointer to offset 12 (start of question name) + resp.putShort((short) 1); // type A + resp.putShort((short) 1); // class IN + resp.putInt(TTL); + resp.putShort((short) 4); // rdlength + + for (String octet : ip.split("\\.")) { + resp.put((byte) Integer.parseInt(octet)); + } + + return resp.array(); + } + + private void forwardAsync(Vertx vertx, DatagramSocket socket, byte[] query, + String senderHost, int senderPort) { + String upstream = upstreamDns; + if (upstream == null) { + return; + } + vertx.executeBlocking(() -> { + try (java.net.DatagramSocket fwd = new java.net.DatagramSocket()) { + fwd.setSoTimeout(2000); + InetAddress addr = InetAddress.getByName(upstream); + fwd.send(new DatagramPacket(query, query.length, addr, DNS_PORT)); + byte[] buf = new byte[512]; + DatagramPacket resp = new DatagramPacket(buf, buf.length); + fwd.receive(resp); + return Arrays.copyOf(resp.getData(), resp.getLength()); + } + }).onSuccess(response -> + socket.send(Buffer.buffer(response), senderPort, senderHost, v -> {}) + ).onFailure(e -> + LOG.debugv("DNS forwarding to {0} failed: {1}", upstream, e.getMessage()) + ); + } + + private String readUpstreamDns() { + 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; + } + } + } + } catch (Exception e) { + LOG.debugv("Could not read /etc/resolv.conf: {0}", e.getMessage()); + } + return FALLBACK_UPSTREAM; + } +} 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 f036c9afb4..198c8e11c3 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 @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.core.common.docker; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import com.github.dockerjava.api.model.Bind; import com.github.dockerjava.api.model.LogConfig; import com.github.dockerjava.api.model.Mount; @@ -35,11 +36,14 @@ public class ContainerBuilder { private final EmulatorConfig config; private final DockerHostResolver dockerHostResolver; + private final EmbeddedDnsServer embeddedDnsServer; @Inject - public ContainerBuilder(EmulatorConfig config, DockerHostResolver dockerHostResolver) { + public ContainerBuilder(EmulatorConfig config, DockerHostResolver dockerHostResolver, + EmbeddedDnsServer embeddedDnsServer) { this.config = config; this.dockerHostResolver = dockerHostResolver; + this.embeddedDnsServer = embeddedDnsServer; } /** @@ -49,7 +53,7 @@ public class ContainerBuilder { * @return a new Builder instance */ public Builder newContainer(String image) { - return new Builder(image, config, dockerHostResolver); + return new Builder(image, config, dockerHostResolver, embeddedDnsServer); } /** @@ -59,6 +63,7 @@ public class ContainerBuilder { private final String image; private final EmulatorConfig config; private final DockerHostResolver dockerHostResolver; + private final EmbeddedDnsServer embeddedDnsServer; private String name; private final List env = new ArrayList<>(); @@ -73,11 +78,14 @@ public class ContainerBuilder { private final List extraHosts = new ArrayList<>(); private LogConfig logConfig; private boolean privileged; + private final List dnsServers = new ArrayList<>(); - Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver) { + Builder(String image, EmulatorConfig config, DockerHostResolver dockerHostResolver, + EmbeddedDnsServer embeddedDnsServer) { this.image = image; this.config = config; this.dockerHostResolver = dockerHostResolver; + this.embeddedDnsServer = embeddedDnsServer; } /** @@ -278,6 +286,16 @@ public class ContainerBuilder { return this; } + /** + * 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. + */ + public Builder withEmbeddedDns() { + embeddedDnsServer.getServerIp().ifPresent(dnsServers::add); + return this; + } + /** * Builds the immutable ContainerSpec. */ @@ -296,7 +314,8 @@ public class ContainerBuilder { List.copyOf(binds), List.copyOf(extraHosts), logConfig, - privileged + privileged, + List.copyOf(dnsServers) ); } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java index 1bc852827f..1585b566bf 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java @@ -329,6 +329,12 @@ public class ContainerLifecycleManager { hostConfig.withLogConfig(spec.logConfig()); } + // DNS servers — used to inject Floci's embedded DNS so spawned containers + // can resolve *.localhost.floci.io to Floci's Docker network IP. + if (spec.dnsServers() != null && !spec.dnsServers().isEmpty()) { + hostConfig.withDns(spec.dnsServers().toArray(new String[0])); + } + return hostConfig; } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java index b879e3f2ba..3bb3b0f74f 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java @@ -25,6 +25,7 @@ import java.util.Map; * @param extraHosts Extra /etc/hosts entries as "hostname:ip" strings * @param logConfig Docker log driver configuration (null = daemon default) * @param privileged Whether to run the container in privileged mode (required for k3s) + * @param dnsServers DNS server IPs to inject into the container (e.g. Floci's embedded DNS) */ public record ContainerSpec( String image, @@ -40,14 +41,15 @@ public record ContainerSpec( List binds, List extraHosts, LogConfig logConfig, - boolean privileged + boolean privileged, + List dnsServers ) { /** * Creates a minimal spec with just the image name. * All other fields will be null or empty lists. */ public ContainerSpec(String image) { - this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), null, false); + this(image, null, List.of(), null, null, null, Map.of(), List.of(), null, List.of(), List.of(), List.of(), null, false, List.of()); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java index 587634c675..164e11fea1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java +++ b/src/main/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncher.java @@ -157,6 +157,8 @@ public class ContainerLauncher { .withHostDockerInternalOnLinux() .withLogRotation(); + specBuilder.withEmbeddedDns(); + // For Image package type without an explicit handler, omit CMD so the image's own CMD is used if (fn.getHandler() != null && !fn.getHandler().isBlank()) { specBuilder.withCmd(fn.getHandler()); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 11f9532d04..6b72b23e36 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -65,6 +65,14 @@ floci: opensearch: flush-interval-ms: 5000 + dns: + # Extra hostname suffixes resolved to Floci's container IP by the embedded DNS server. + # Useful when migrating from LocalStack — add localhost.localstack.cloud to avoid + # changing Lambda endpoint environment variables. + # Via env var (comma-separated): FLOCI_DNS_EXTRA_SUFFIXES=localhost.localstack.cloud,other.internal + # extra-suffixes: + # - localhost.localstack.cloud + 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 new file mode 100644 index 0000000000..16a086a6c4 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/core/common/dns/EmbeddedDnsServerTest.java @@ -0,0 +1,164 @@ +package io.github.hectorvent.floci.core.common.dns; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.nio.ByteBuffer; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class EmbeddedDnsServerTest { + + private EmbeddedDnsServer dns; + + @BeforeEach + void setUp() { + dns = new EmbeddedDnsServer(List.of("localhost.floci.io")); + } + + // ── matchesSuffix ───────────────────────────────────────────────────────── + + @Test + void matchesSuffix_exactMatch() { + assertTrue(dns.matchesSuffix("localhost.floci.io")); + } + + @Test + void matchesSuffix_singleSubdomain() { + assertTrue(dns.matchesSuffix("my-bucket.localhost.floci.io")); + } + + @Test + void matchesSuffix_deeplyNested() { + assertTrue(dns.matchesSuffix("deeply.nested.bucket.localhost.floci.io")); + } + + @Test + void matchesSuffix_caseInsensitive() { + assertTrue(dns.matchesSuffix("My-Bucket.Localhost.Floci.IO")); + } + + @Test + void matchesSuffix_noMatch() { + assertFalse(dns.matchesSuffix("my-bucket.s3.amazonaws.com")); + } + + @Test + void matchesSuffix_partialSuffixNoMatch() { + assertFalse(dns.matchesSuffix("floci.io")); + } + + @Test + void matchesSuffix_nullAndEmpty() { + assertFalse(dns.matchesSuffix(null)); + assertFalse(dns.matchesSuffix("")); + } + + // ── readName ────────────────────────────────────────────────────────────── + + @Test + void readName_simple() { + // my-bucket.localhost.floci.io encoded as DNS labels + byte[] encoded = encodeName("my-bucket.localhost.floci.io"); + ByteBuffer buf = ByteBuffer.wrap(encoded); + assertEquals("my-bucket.localhost.floci.io", dns.readName(buf, encoded)); + } + + @Test + void readName_singleLabel() { + byte[] encoded = encodeName("floci"); + ByteBuffer buf = ByteBuffer.wrap(encoded); + assertEquals("floci", dns.readName(buf, encoded)); + } + + @Test + void readName_withCompressionPointer() { + // Build a buffer where the name at offset 12 is "floci.io" and + // a pointer at offset 0 points to it. + byte[] data = new byte[20]; + // pointer at offset 0 → offset 4 + data[0] = (byte) 0xC0; + data[1] = 0x04; + // "floci.io" at offset 4 + byte[] name = encodeName("floci.io"); + System.arraycopy(name, 0, data, 4, name.length); + + ByteBuffer buf = ByteBuffer.wrap(data); + assertEquals("floci.io", dns.readName(buf, data)); + } + + // ── buildAResponse ──────────────────────────────────────────────────────── + + @Test + void buildAResponse_hasCorrectTransactionId() { + byte[] query = buildQuery("my-bucket.localhost.floci.io", (short) 0x1234); + byte[] response = dns.buildAResponse(query, (short) 0x1234, 12, query.length, "172.19.0.2"); + short txId = ByteBuffer.wrap(response).getShort(0); + assertEquals((short) 0x1234, txId); + } + + @Test + void buildAResponse_flagsIndicateResponse() { + byte[] query = buildQuery("bucket.localhost.floci.io", (short) 1); + byte[] response = dns.buildAResponse(query, (short) 1, 12, query.length, "10.0.0.1"); + short flags = ByteBuffer.wrap(response).getShort(2); + assertTrue((flags & 0x8000) != 0, "QR bit must be set"); + } + + @Test + void buildAResponse_answerCountIsOne() { + byte[] query = buildQuery("bucket.localhost.floci.io", (short) 2); + byte[] response = dns.buildAResponse(query, (short) 2, 12, query.length, "10.0.0.1"); + short ancount = ByteBuffer.wrap(response).getShort(6); + assertEquals(1, ancount); + } + + @Test + void buildAResponse_ipAddressIsCorrect() { + byte[] query = buildQuery("bucket.localhost.floci.io", (short) 3); + byte[] response = dns.buildAResponse(query, (short) 3, 12, query.length, "172.19.0.42"); + // IP starts at offset: 12 (header) + questionLength + 2+2+2+4+2 = questionLength + 24 + int questionLength = query.length - 12; + ByteBuffer resp = ByteBuffer.wrap(response); + resp.position(12 + questionLength + 10); // skip header + question + name-ptr(2) + type(2) + class(2) + ttl(4) + short rdlen = resp.getShort(); + assertEquals(4, rdlen); + assertEquals((byte) 172, resp.get()); + assertEquals((byte) 19, resp.get()); + assertEquals((byte) 0, resp.get()); + assertEquals((byte) 42, resp.get()); + } + + // ── helpers ─────────────────────────────────────────────────────────────── + + private byte[] encodeName(String name) { + String[] labels = name.split("\\."); + int len = 1; // trailing zero + for (String l : labels) len += 1 + l.length(); + byte[] buf = new byte[len]; + int pos = 0; + for (String label : labels) { + buf[pos++] = (byte) label.length(); + for (char c : label.toCharArray()) buf[pos++] = (byte) c; + } + buf[pos] = 0; + return buf; + } + + private byte[] buildQuery(String name, short txId) { + byte[] encodedName = encodeName(name); + // header(12) + name + type(2) + class(2) + ByteBuffer buf = ByteBuffer.allocate(12 + encodedName.length + 4); + buf.putShort(txId); + buf.putShort((short) 0x0100); // standard query, RD=1 + buf.putShort((short) 1); // qdcount + buf.putShort((short) 0); + buf.putShort((short) 0); + buf.putShort((short) 0); + buf.put(encodedName); + buf.putShort((short) 1); // type A + buf.putShort((short) 1); // class IN + return buf.array(); + } +} 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 4b5c428ee9..037da6dad7 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 @@ -294,6 +294,8 @@ class EventBridgeSchedulerIntegrationTest { @Override public StorageConfig storage() { return null; } @Override + public DnsConfig dns() { return Optional::empty; } + @Override public AuthConfig auth() { return null; } @Override public ServicesConfig services() { return null; } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java index 90dafb9888..9150775c75 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/launcher/ContainerLauncherTest.java @@ -1,6 +1,7 @@ package io.github.hectorvent.floci.services.lambda.launcher; import io.github.hectorvent.floci.config.EmulatorConfig; +import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer; import io.github.hectorvent.floci.core.common.docker.ContainerBuilder; import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager; import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer; @@ -41,6 +42,7 @@ class ContainerLauncherTest { @Mock DockerHostResolver dockerHostResolver; @Mock EmulatorConfig config; @Mock EcrRegistryManager ecrRegistryManager; + @Mock EmbeddedDnsServer embeddedDnsServer; @Mock RuntimeApiServer runtimeApiServer; @Mock DockerClient dockerClient; @@ -64,7 +66,9 @@ class ContainerLauncherTest { when(docker.logMaxSize()).thenReturn("10m"); when(docker.logMaxFile()).thenReturn("3"); - ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver); + when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty()); + + ContainerBuilder containerBuilder = new ContainerBuilder(config, dockerHostResolver, embeddedDnsServer); launcher = new ContainerLauncher(containerBuilder, lifecycleManager, logStreamer, imageResolver, runtimeApiServerFactory, dockerHostResolver, config, ecrRegistryManager);