Light, fluffy, and always free - The AWS Local Emulator alternative
fix(config): enforce safe default network binding (#3684)
Niels Kootstra1831f1010593
diff --git a/docker/Dockerfile b/docker/Dockerfileindex bbe287a99d..3368010e69 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -81,4 +81,5 @@ HEALTHCHECK --interval=5s --timeout=3s --retries=5 \CMD wget -q --spider http://localhost:4566/_floci/health || exit 1ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]-CMD ["java", "--enable-native-access=ALL-UNNAMED", "-jar", "/app/quarkus-app/quarkus-run.jar"]+# A published port needs 0.0.0.0 inside the container, which Floci only accepts with explicit consent.+CMD ["java", "--enable-native-access=ALL-UNNAMED", "-Dquarkus.http.host=0.0.0.0", "-Dfloci.security.allow-unsafe-network-exposure=true", "-jar", "/app/quarkus-app/quarkus-run.jar"]diff --git a/docker/Dockerfile.compat b/docker/Dockerfile.compatindex 25867fdc0f..1ea281e24e 100644--- a/docker/Dockerfile.compat+++ b/docker/Dockerfile.compat@@ -98,6 +98,10 @@ FROM toolsARG VERSIONENV FLOCI_VERSION=${VERSION}ENV FLOCI_STORAGE_PERSISTENT_PATH=/app/data+# The compatibility image can be built on top of an older native image during+# CI. An environment variable is ignored by older binaries and enables the+# network guard in images that support it.+ENV FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE=trueCOPY --from=native --chown=1001:root /app/ /app/VOLUME /app/data@@ -111,6 +115,7 @@ EXPOSE 4566HEALTHCHECK --interval=5s --timeout=3s --retries=5 CMD ["/usr/local/bin/healthcheck.sh"]ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]+# A published port needs 0.0.0.0 inside the container, which Floci only accepts with explicit consent.CMD ["/app/application", "-Dquarkus.http.host=0.0.0.0"]-USER 1001\ No newline at end of file+USER 1001diff --git a/docker/Dockerfile.jvm-package b/docker/Dockerfile.jvm-packageindex 33cf69e617..8bcc0fcfda 100644--- a/docker/Dockerfile.jvm-package+++ b/docker/Dockerfile.jvm-package@@ -80,4 +80,5 @@ HEALTHCHECK --interval=5s --timeout=3s --retries=5 \CMD wget -q --spider http://localhost:4566/_floci/health || exit 1ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]-CMD ["java", "--enable-native-access=ALL-UNNAMED", "-jar", "/app/quarkus-app/quarkus-run.jar"]+# A published port needs 0.0.0.0 inside the container, which Floci only accepts with explicit consent.+CMD ["java", "--enable-native-access=ALL-UNNAMED", "-Dquarkus.http.host=0.0.0.0", "-Dfloci.security.allow-unsafe-network-exposure=true", "-jar", "/app/quarkus-app/quarkus-run.jar"]diff --git a/docker/Dockerfile.native b/docker/Dockerfile.nativeindex 0f8db2c817..3f7d257b68 100644--- a/docker/Dockerfile.native+++ b/docker/Dockerfile.native@@ -46,4 +46,5 @@ COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/docker-entrypoint.shCOPY --chmod=755 docker/localstack-parity.sh docker/healthcheck.sh /usr/local/bin/ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]-CMD ["/app/application"]+# A published port needs 0.0.0.0 inside the container, which Floci only accepts with explicit consent.+CMD ["/app/application", "-Dquarkus.http.host=0.0.0.0", "-Dfloci.security.allow-unsafe-network-exposure=true"]diff --git a/docker/Dockerfile.native-package b/docker/Dockerfile.native-packageindex 2d32e65cbc..eabea62c0f 100644--- a/docker/Dockerfile.native-package+++ b/docker/Dockerfile.native-package@@ -43,4 +43,5 @@ EXPOSE 4566HEALTHCHECK --interval=5s --timeout=3s --retries=5 CMD ["/usr/local/bin/healthcheck.sh"]ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]-CMD ["/app/application", "-Dquarkus.http.host=0.0.0.0"]+# A published port needs 0.0.0.0 inside the container, which Floci only accepts with explicit consent.+CMD ["/app/application", "-Dquarkus.http.host=0.0.0.0", "-Dfloci.security.allow-unsafe-network-exposure=true"]diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex b1393e5591..b9d205e1b6 100755--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -73,11 +73,13 @@ fi# ignores its argv entirely, so this keeps drop-in parity.# The default matches the CMD of the image variant: native images ship# /app/application, JVM images ship /app/quarkus-app/quarkus-run.jar.+# Both listen on 0.0.0.0 so a published port reaches Floci, which it only+# accepts with explicit consent. The JVM reads -D options only before -jar.if [ $# -eq 0 ]; thenif [ -x /app/application ]; then- set -- /app/application -Dquarkus.http.host=0.0.0.0+ set -- /app/application -Dquarkus.http.host=0.0.0.0 -Dfloci.security.allow-unsafe-network-exposure=trueelse- set -- java -jar /app/quarkus-app/quarkus-run.jar -Dquarkus.http.host=0.0.0.0+ set -- java -Dquarkus.http.host=0.0.0.0 -Dfloci.security.allow-unsafe-network-exposure=true -jar /app/quarkus-app/quarkus-run.jarfifidiff --git a/docker/localstack-parity.sh b/docker/localstack-parity.shindex 3f79c5dd19..9c3a1a6e12 100644--- a/docker/localstack-parity.sh+++ b/docker/localstack-parity.sh@@ -19,8 +19,12 @@ fi_ls_host="${LOCALSTACK_HOST:-${LOCALSTACK_HOSTNAME:-}}"[ -n "${_ls_host}" ] && export FLOCI_HOSTNAME="${FLOCI_HOSTNAME:-${_ls_host}}"-# Bind address — GATEWAY_LISTEN → QUARKUS_HTTP_HOST-[ -n "${GATEWAY_LISTEN:-}" ] && export QUARKUS_HTTP_HOST="${QUARKUS_HTTP_HOST:-${GATEWAY_LISTEN}}"+# Bind address — GATEWAY_LISTEN → QUARKUS_HTTP_HOST. LocalStack listens there with no further+# opt-in, so GATEWAY_LISTEN also gives the consent Floci requires for a non-loopback address.+if [ -n "${GATEWAY_LISTEN:-}" ]; then+ export QUARKUS_HTTP_HOST="${QUARKUS_HTTP_HOST:-${GATEWAY_LISTEN}}"+ export FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE="${FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE:-true}"+fi# Log level — LS_LOG / DEBUG=1 → QUARKUS_LOG_LEVELif [ -n "${LS_LOG:-}" ]; thendiff --git a/docker/test-entrypoint.sh b/docker/test-entrypoint.shindex f8ab5c1148..a2eed75fd3 100644--- a/docker/test-entrypoint.sh+++ b/docker/test-entrypoint.sh@@ -88,7 +88,7 @@ assert_eq "explicit java command bypasses the fallback" \# Quarkus runner jar with the same arguments as the published image CMD.if [ ! -e /app/application ]; thenassert_eq "empty argv falls back to the JVM default command" \- "java -jar /app/quarkus-app/quarkus-run.jar -Dquarkus.http.host=0.0.0.0" \+ "java -Dquarkus.http.host=0.0.0.0 -Dfloci.security.allow-unsafe-network-exposure=true -jar /app/quarkus-app/quarkus-run.jar" \"$(PATH="${WORK}/bin:${PATH}" LOCALSTACK_PARITY=false sh "${SCRIPT}")"elseprintf '[SKIP] empty argv falls back to the JVM default command (/app/application exists on this host)\n'@@ -111,7 +111,7 @@ EOFfiif [ "${NATIVE_TESTABLE}" = 'true' ]; thenassert_eq "empty argv prefers the native binary when present" \- "/app/application -Dquarkus.http.host=0.0.0.0" \+ "/app/application -Dquarkus.http.host=0.0.0.0 -Dfloci.security.allow-unsafe-network-exposure=true" \"$(LOCALSTACK_PARITY=false sh "${SCRIPT}")"elseprintf '[SKIP] empty argv prefers the native binary when present (/app not writable)\n'diff --git a/docker/test-localstack-parity.sh b/docker/test-localstack-parity.shindex c9628778e7..2f7e6cf547 100755--- a/docker/test-localstack-parity.sh+++ b/docker/test-localstack-parity.sh@@ -76,6 +76,18 @@ assert_eq "GATEWAY_LISTEN sets QUARKUS_HTTP_HOST" \"0.0.0.0" \"$(_run QUARKUS_HTTP_HOST GATEWAY_LISTEN=0.0.0.0)"+assert_eq "GATEWAY_LISTEN allows a non-loopback address" \+ "true" \+ "$(_run FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE GATEWAY_LISTEN=0.0.0.0)"++assert_eq "FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE wins over GATEWAY_LISTEN" \+ "false" \+ "$(_run FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE GATEWAY_LISTEN=0.0.0.0 FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE=false)"++assert_eq "no GATEWAY_LISTEN leaves network exposure unallowed" \+ "" \+ "$(_run FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE)"+# --- LOG LEVEL ---assert_eq "LS_LOG sets QUARKUS_LOG_LEVEL" \"WARN" \diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.mdindex fc80e0f894..de4c5ae62a 100644--- a/docs/configuration/environment-variables.md+++ b/docs/configuration/environment-variables.md@@ -23,6 +23,21 @@ Floci is configured exclusively through environment variables. Every option belo| `FLOCI_AUTH_VALIDATE_SIGNATURES` | `false` | When `true`, verifies S3 presigned URL signatures || `FLOCI_AUTH_PRESIGN_SECRET` | `local-emulator-secret` | Secret used to sign and verify pre-signed URLs |+## Network Exposure++| Variable | Default | Description |+|---|---|---|+| `QUARKUS_HTTP_HOST` | `127.0.0.1` | Address Floci listens on. With TLS enabled, the proxy serving HTTP and HTTPS on `FLOCI_PORT` listens here |+| `FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE` | `false` | Allow listening outside loopback (`127.0.0.0/8`, `::1`, `localhost`). Without it, Floci refuses to start on any other address |++Anyone who can reach Floci's port can call its APIs. The Docker images listen on `0.0.0.0` inside the container and pass both settings in their default command, so who can reach Floci depends on how you publish the port. Publish it on loopback unless other machines need it:++```bash+docker run --rm -p 127.0.0.1:4566:4566 floci/floci:latest+```++Running Floci directly on a Linux host (not in a container) with services that start containers, such as Lambda functions or ECS tasks, needs a non-loopback address. Those containers reach Floci through `host.docker.internal`, which resolves to the Docker bridge gateway (`172.17.0.1` by default) rather than to the host's loopback. Set `QUARKUS_HTTP_HOST=0.0.0.0` and `FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE=true`, and keep port 4566 closed to other networks with a firewall. See also [Lambda on native Linux Docker](../getting-started/quick-start.md#lambda-on-native-linux-docker-ufw).+## Browser CORS| Variable | Default | Description |diff --git a/docs/configuration/tls.md b/docs/configuration/tls.mdindex 74520b9c43..79a1db9daa 100644--- a/docs/configuration/tls.md+++ b/docs/configuration/tls.md@@ -50,6 +50,8 @@ Disabling verification (`--no-verify-ssl`, `verify=False`, `NODE_TLS_REJECT_UNAU| `FLOCI_TLS_KEY_PATH` | *(unset)* | Path to PEM private key file || `FLOCI_TLS_SELF_SIGNED` | `true` | Auto-generate a server certificate signed by Floci's local CA when no cert/key paths provided |+With TLS enabled, the proxy that accepts HTTP and HTTPS on Floci's ports listens on `QUARKUS_HTTP_HOST` (`127.0.0.1` by default). As without TLS, any address outside loopback also needs `FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE=true`; see [Network Exposure](./environment-variables.md#network-exposure).+## Local CA and Server CertificateWhen `FLOCI_TLS_ENABLED=true` and no custom certificate is provided, Floci keeps a local root CA at `{persistent-path}/tls/floci-root-ca.crt` (key `floci-root-ca.key`, owner-only) and issues its server certificate `floci-server.crt` from it at startup. The server certificate:diff --git a/docs/getting-started/migrate-from-localstack.md b/docs/getting-started/migrate-from-localstack.mdindex 883af77084..93834407f3 100644--- a/docs/getting-started/migrate-from-localstack.md+++ b/docs/getting-started/migrate-from-localstack.md@@ -60,7 +60,7 @@ The port (`4566`), credentials (`test` / `test`), and AWS SDK configuration are| `PERSISTENCE=1` | `FLOCI_STORAGE_MODE=persistent` | Enable disk persistence || `PERSIST_STATE=1` | `FLOCI_STORAGE_MODE=persistent` | Alias for `PERSISTENCE` — same effect || `EDGE_PORT` | `FLOCI_PORT` | Bind port override |-| `GATEWAY_LISTEN` | `QUARKUS_HTTP_HOST` | Bind address override |+| `GATEWAY_LISTEN` | `QUARKUS_HTTP_HOST` | Bind address override. Also sets `FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE=true`, since LocalStack needs no opt-in for a non-loopback address || `LS_LOG` / `DEBUG=1` | `QUARKUS_LOG_LEVEL` | Log verbosity || `DOCKER_HOST` | `FLOCI_DOCKER_DOCKER_HOST` | Docker daemon socket path or TCP address || `LAMBDA_DOCKER_NETWORK` | `FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK` | Network for Lambda containers |diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 0b10cd7369..0a620ef263 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -209,6 +209,15 @@ public interface EmulatorConfig {*/@WithDefault("false")boolean corsAllowPrivateNetwork();++ /**+ * Whether Floci may listen outside loopback (127.0.0.0/8, ::1, localhost), through+ * {@code quarkus.http.host} or the TLS proxy that uses it. Anyone who can reach such an+ * address can call Floci's APIs, so startup fails unless this is set; see+ * {@link NetworkExposureGuard}.+ */+ @WithDefault("false")+ boolean allowUnsafeNetworkExposure();}interface StorageConfig {diff --git a/src/main/java/io/github/hectorvent/floci/config/NetworkExposureGuard.java b/src/main/java/io/github/hectorvent/floci/config/NetworkExposureGuard.javanew file mode 100644index 0000000000..43562892a2--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/config/NetworkExposureGuard.java@@ -0,0 +1,138 @@+package io.github.hectorvent.floci.config;++import io.quarkus.runtime.StartupEvent;+import jakarta.annotation.Priority;+import jakarta.enterprise.context.ApplicationScoped;+import jakarta.enterprise.event.Observes;+import jakarta.inject.Inject;+import jakarta.interceptor.Interceptor;+import org.eclipse.microprofile.config.Config;+import org.eclipse.microprofile.config.ConfigValue;+import org.eclipse.microprofile.config.spi.ConfigSource;++import java.net.InetAddress;+import java.net.UnknownHostException;+import java.util.regex.Pattern;++/**+ * Refuses to start Floci on an address outside loopback unless+ * {@code floci.security.allow-unsafe-network-exposure} is set: anyone who can reach Floci's port+ * can call its APIs.+ *+ * <p>The check runs before every other startup observer and before Quarkus opens its HTTP socket.+ * In TLS mode {@link TlsProxyServer} owns the public port and applies the same check before it binds.+ */+@ApplicationScoped+public class NetworkExposureGuard {++ private static final String HTTP_HOST = "quarkus.http.host";+ /** Quarkus's own production default, for a configuration that sets no host at all. */+ private static final String QUARKUS_DEFAULT_HOST = "0.0.0.0";+ private static final Pattern IPV4 = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}");+ // Starts with a hex digit or a colon, which InetAddress parses as a literal and never resolves.+ private static final Pattern IPV6 = Pattern.compile("[0-9a-fA-F]*:[0-9a-fA-F:.]*");+ private static final Pattern HOSTNAME = Pattern.compile(+ "(?=.{1,253}$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?"+ + "(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*");++ private final EmulatorConfig config;+ private final Config mpConfig;++ @Inject+ public NetworkExposureGuard(EmulatorConfig config, Config mpConfig) {+ this.config = config;+ this.mpConfig = mpConfig;+ }++ void onStart(@Observes @Priority(Interceptor.Priority.PLATFORM_BEFORE) StartupEvent ignored) {+ requireConsent(publicHost(mpConfig), config.security());+ }++ /**+ * The address Floci's public listener binds: Quarkus itself, or {@link TlsProxyServer} in TLS+ * mode. {@link TlsConfigSource} pins {@code quarkus.http.host} to loopback for the internal+ * backends, so when the effective value is that pin the configured host is the next source's.+ */+ static String publicHost(Config config) {+ ConfigValue effective = config.getConfigValue(HTTP_HOST);+ if (effective.getValue() != null && !TlsConfigSource.NAME.equals(effective.getSourceName())) {+ return effective.getValue();+ }+ for (ConfigSource source : config.getConfigSources()) {+ String host = source.getValue(HTTP_HOST);+ if (host != null && !TlsConfigSource.NAME.equals(source.getName())) {+ return host;+ }+ }+ return QUARKUS_DEFAULT_HOST;+ }++ static void requireConsent(String host, EmulatorConfig.SecurityConfig security) {+ if (!isValidHost(host)) {+ throw new IllegalStateException("Refusing to listen on malformed host: " + host);+ }+ if (isLoopback(host) || security.allowUnsafeNetworkExposure()) {+ return;+ }+ throw new IllegalStateException("Refusing to listen on " + host+ + ": it is not a loopback address, so anyone who can reach it can call Floci's APIs."+ + " Set quarkus.http.host (QUARKUS_HTTP_HOST) to 127.0.0.1, or set"+ + " floci.security.allow-unsafe-network-exposure (FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE)"+ + " to true to allow it.");+ }++ /** True for 127.0.0.0/8, ::1 and localhost. Only IP literals are parsed; no name is resolved. */+ static boolean isLoopback(String host) {+ String literal = host.strip();+ if (literal.startsWith("[") && literal.endsWith("]")) {+ literal = literal.substring(1, literal.length() - 1);+ }+ if (literal.equalsIgnoreCase("localhost")) {+ return true;+ }+ if (IPV4.matcher(literal).matches()) {+ return literal.startsWith("127.");+ }+ if (!IPV6.matcher(literal).matches()) {+ return false;+ }+ try {+ return InetAddress.getByName(literal).isLoopbackAddress();+ } catch (UnknownHostException e) {+ return false;+ }+ }++ private static boolean isValidHost(String host) {+ if (host == null || host.isBlank()) {+ return false;+ }+ String literal = host.strip();+ boolean bracketed = literal.startsWith("[") || literal.endsWith("]");+ if (bracketed) {+ if (!(literal.startsWith("[") && literal.endsWith("]"))) {+ return false;+ }+ literal = literal.substring(1, literal.length() - 1);+ }+ if (IPV4.matcher(literal).matches()) {+ for (String part : literal.split("\\.")) {+ if (Integer.parseInt(part) > 255) {+ return false;+ }+ }+ return !bracketed;+ }+ if (literal.indexOf(':') >= 0) {+ if (!IPV6.matcher(literal).matches()) {+ return false;+ }+ try {+ return InetAddress.getByName(literal).getHostAddress() != null;+ } catch (UnknownHostException e) {+ return false;+ }+ }+ return !bracketed && HOSTNAME.matcher(literal).matches();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.javaindex 51ccba9255..e608197dcb 100644--- a/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java+++ b/src/main/java/io/github/hectorvent/floci/config/TlsConfigSource.java@@ -45,6 +45,8 @@ public class TlsConfigSource implements ConfigSource {private static final Logger LOG = Logger.getLogger(TlsConfigSource.class);+ static final String NAME = "FlociTlsConfigSource";+/*** Internal ports Quarkus binds when TLS is enabled. {@link TlsProxyServer} listens on the* public Floci port and routes to these by protocol, so the two classes must agree; they are@@ -169,7 +171,7 @@ public class TlsConfigSource implements ConfigSource {@Overridepublic String getName() {- return "FlociTlsConfigSource";+ return NAME;}/**diff --git a/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java b/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.javaindex 37e7763805..87ea73d8d4 100644--- a/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java+++ b/src/main/java/io/github/hectorvent/floci/config/TlsProxyServer.java@@ -10,6 +10,7 @@ import io.vertx.core.net.NetSocket;import jakarta.annotation.PreDestroy;import jakarta.enterprise.context.ApplicationScoped;import jakarta.inject.Inject;+import org.eclipse.microprofile.config.Config;import org.jboss.logging.Logger;import java.util.ArrayList;@@ -40,6 +41,10 @@ import java.util.concurrent.CompletionException;* so they PUT to 443 regardless of Floci's configured port; binding 443 lets those callbacks* reach Floci. The extra binding is skipped when the port is {@code 0} or equals the public port.*+ * <p>Both listen on the configured {@code quarkus.http.host}, not the loopback pin+ * {@link TlsConfigSource} applies to Quarkus itself, and a non-loopback host needs the same consent+ * as without TLS; see {@link NetworkExposureGuard}.+ ** <p>This bean is only active when {@code floci.tls.enabled=true}. When TLS is disabled,* Quarkus serves HTTP directly on port 4566 and this proxy is not started.*/@@ -57,6 +62,7 @@ public class TlsProxyServer {private final Vertx vertx;private final EmulatorConfig config;+ private final String host;private final int httpBackendPort;private final int httpsBackendPort;private final List<NetServer> proxyServers = new ArrayList<>();@@ -82,14 +88,15 @@ public class TlsProxyServer {private NetClient client;@Inject- public TlsProxyServer(Vertx vertx, EmulatorConfig config) {- this(vertx, config, HTTP_BACKEND_PORT, HTTPS_BACKEND_PORT);+ public TlsProxyServer(Vertx vertx, EmulatorConfig config, Config mpConfig) {+ this(vertx, config, NetworkExposureGuard.publicHost(mpConfig), HTTP_BACKEND_PORT, HTTPS_BACKEND_PORT);}/** Visible for testing — lets tests point the proxy at backends on non-default ports. */- TlsProxyServer(Vertx vertx, EmulatorConfig config, int httpBackendPort, int httpsBackendPort) {+ TlsProxyServer(Vertx vertx, EmulatorConfig config, String host, int httpBackendPort, int httpsBackendPort) {this.vertx = vertx;this.config = config;+ this.host = host;this.httpBackendPort = httpBackendPort;this.httpsBackendPort = httpsBackendPort;startIfTlsEnabled();@@ -100,12 +107,14 @@ public class TlsProxyServer {return;}+ NetworkExposureGuard.requireConsent(host, config.security());+client = vertx.createNetClient();Handler<NetSocket> connectHandler = buildConnectHandler();for (int port : listenPorts()) {NetServerOptions options = new NetServerOptions()- .setHost("0.0.0.0")+ .setHost(host).setPort(port);NetServer server = vertx.createNetServer(options);server.connectHandler(connectHandler);@@ -114,8 +123,8 @@ public class TlsProxyServer {bind.onComplete(ar -> {if (ar.succeeded()) {failedPorts.remove(port);- LOG.infov("TLS proxy: listening on port {0} (HTTP→{1}, HTTPS→{2})",- String.valueOf(port), String.valueOf(httpBackendPort), String.valueOf(httpsBackendPort));+ LOG.infov("TLS proxy: listening on {0}:{1} (HTTP→{2}, HTTPS→{3})",+ host, String.valueOf(port), String.valueOf(httpBackendPort), String.valueOf(httpsBackendPort));} else if (port == config.port()) {LOG.errorv("TLS proxy: failed to start on public port {0}: {1}",String.valueOf(port), ar.cause().getMessage());diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 6f870f6dcd..df3532e8ab 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -12,18 +12,21 @@ quarkus:http:port: ${floci.port}- host: 0.0.0.0+ # Loopback by default. Any other address (0.0.0.0, a LAN IP) also needs+ # floci.security.allow-unsafe-network-exposure, or Floci refuses to start.+ # Env var: QUARKUS_HTTP_HOST=0.0.0.0+ host: 127.0.0.1# Quarkus 3.38 added a Host-header validation filter (DNS-rebinding protection for a dev server)- # that it switches on by itself whenever the server is bound to loopback, which Floci does in- # TLS mode: Quarkus listens on 127.0.0.1:4510/4511 behind the TCP proxy on 4566, and the proxy- # passes the client's Host header through untouched. The filter is an exact-match set with no+ # that it switches on by itself whenever the server is bound to loopback, which Floci is by+ # default. In TLS mode Quarkus listens on 127.0.0.1:4510/4511 behind the TCP proxy on 4566, and+ # the proxy passes the client's Host header through untouched. The filter is an exact-match set with no# wildcard support, and with require-localhost it admits only localhost, 127.0.0.1 and [::1].# An emulator has to answer under the names it documents and puts in its certificate# (localhost.floci.io, *.localhost.floci.io, *.execute-api.localhost.floci.io,# host.docker.internal) and under whatever a compose file calls it (FLOCI_HOSTNAME), none of# which an exact-match allow-list can express. Disabling the check restores the behaviour of- # every release before Quarkus 3.39 and of the non-TLS mode, where Quarkus never enables it;- # the access boundary of a local emulator is the IAM and signature enforcement configuration.+ # every release before Quarkus 3.39; the access boundary of a local emulator is the IAM and+ # signature enforcement configuration.host-validation:require-localhost: falselimits:@@ -246,6 +249,11 @@ floci:# Grant Private Network Access preflights (Access-Control-Allow-Private-Network)# so a page on a public/secure origin can reach this loopback backend.cors-allow-private-network: false+ # Allow quarkus.http.host, and the TLS proxy that uses it, to listen outside loopback+ # (127.0.0.0/8, ::1, localhost). Anyone who can reach that address can call Floci's APIs.+ # The Docker images set it, since they listen on 0.0.0.0 inside the container.+ # Env var: FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE=true+ allow-unsafe-network-exposure: falsetls:enabled: false # FLOCI_TLS_ENABLED (default: false)diff --git a/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java b/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.javaindex 0e3694ad97..1c3e3119f0 100644--- a/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/ApplicationDefaultsTest.java@@ -56,6 +56,22 @@ class ApplicationDefaultsTest {"the EmulatorConfig fallback should match the AWS SQS maximum too");}+ @Test+ void productionConfigListensOnLoopbackWithoutNetworkExposureConsent() throws IOException, NoSuchMethodException {+ JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());++ assertEquals("127.0.0.1", config.path("quarkus").path("http").path("host").asText(),+ "production application.yml should listen on loopback by default");+ assertFalse(config.path("floci").path("security").path("allow-unsafe-network-exposure").asBoolean(true),+ "production application.yml should not allow a non-loopback listener by default");++ WithDefault fallback = EmulatorConfig.SecurityConfig.class+ .getMethod("allowUnsafeNetworkExposure")+ .getAnnotation(WithDefault.class);+ assertNotNull(fallback, "allowUnsafeNetworkExposure should declare a fallback default");+ assertEquals("false", fallback.value(), "the EmulatorConfig fallback should refuse exposure too");+ }+@Testvoid productionConfigDoesNotSeedIamDeployerPrincipalByDefault() throws IOException {JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());diff --git a/src/test/java/io/github/hectorvent/floci/config/IotMqttWebSocketProxyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/config/IotMqttWebSocketProxyIntegrationTest.javaindex 271d829768..c3eb57919b 100644--- a/src/test/java/io/github/hectorvent/floci/config/IotMqttWebSocketProxyIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/IotMqttWebSocketProxyIntegrationTest.java@@ -112,7 +112,7 @@ class IotMqttWebSocketProxyIntegrationTest {when(config.tls()).thenReturn(tls);when(tls.enabled()).thenReturn(true);when(tls.awsHttpsPort()).thenReturn(0);- proxy = new TlsProxyServer(vertx, config, testHttpPort, testSslPort);+ proxy = new TlsProxyServer(vertx, config, "127.0.0.1", testHttpPort, testSslPort);long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);while (true) {try (Socket probe = new Socket("127.0.0.1", publicPort)) {diff --git a/src/test/java/io/github/hectorvent/floci/config/NetworkExposureGuardTest.java b/src/test/java/io/github/hectorvent/floci/config/NetworkExposureGuardTest.javanew file mode 100644index 0000000000..f553693354--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/config/NetworkExposureGuardTest.java@@ -0,0 +1,107 @@+package io.github.hectorvent.floci.config;++import io.smallrye.config.PropertiesConfigSource;+import io.smallrye.config.SmallRyeConfig;+import io.smallrye.config.SmallRyeConfigBuilder;+import org.eclipse.microprofile.config.Config;+import org.eclipse.microprofile.config.ConfigValue;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import java.nio.file.Path;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+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.Mockito.mock;+import static org.mockito.Mockito.when;++class NetworkExposureGuardTest {++ @TempDir+ Path tempDir;++ @AfterEach+ void cleanup() {+ System.clearProperty("floci.tls.enabled");+ System.clearProperty("floci.tls.self-signed");+ System.clearProperty("floci.storage.persistent-path");+ }++ private static EmulatorConfig.SecurityConfig security(boolean allowExposure) {+ EmulatorConfig.SecurityConfig security = mock(EmulatorConfig.SecurityConfig.class);+ when(security.allowUnsafeNetworkExposure()).thenReturn(allowExposure);+ return security;+ }++ @ParameterizedTest+ @ValueSource(strings = {"127.0.0.1", "127.10.0.3", "::1", "[::1]", "localhost", "LOCALHOST"})+ void loopbackHostNeedsNoConsent(String host) {+ assertDoesNotThrow(() -> NetworkExposureGuard.requireConsent(host, security(false)));+ }++ @ParameterizedTest+ @ValueSource(strings = {"0.0.0.0", "::", "192.168.1.20", "172.17.0.1", "floci.internal"})+ void nonLoopbackHostWithoutConsentNamesTheSettingToChange(String host) {+ IllegalStateException e = assertThrows(IllegalStateException.class,+ () -> NetworkExposureGuard.requireConsent(host, security(false)));++ assertTrue(e.getMessage().contains(host), e.getMessage());+ assertTrue(e.getMessage().contains("floci.security.allow-unsafe-network-exposure"), e.getMessage());+ assertTrue(e.getMessage().contains("FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE"), e.getMessage());+ }++ @Test+ void nonLoopbackHostWithConsentIsAllowed() {+ assertDoesNotThrow(() -> NetworkExposureGuard.requireConsent("0.0.0.0", security(true)));+ }++ @Test+ void startupRefusesMalformedHostEvenWithNetworkExposureConsent() {+ Config config = mock(Config.class);+ ConfigValue host = mock(ConfigValue.class);+ when(host.getValue()).thenReturn("999.999.999.999");+ when(config.getConfigValue("quarkus.http.host")).thenReturn(host);+ EmulatorConfig emulatorConfig = mock(EmulatorConfig.class);+ EmulatorConfig.SecurityConfig security = security(true);+ when(emulatorConfig.security()).thenReturn(security);++ NetworkExposureGuard guard = new NetworkExposureGuard(emulatorConfig, config);++ IllegalStateException exception = assertThrows(IllegalStateException.class,+ () -> guard.onStart(null));++ assertTrue(exception.getMessage().contains("malformed"), exception.getMessage());+ }++ @Test+ void publicHostIsTheConfiguredHost() {+ SmallRyeConfig config = new SmallRyeConfigBuilder()+ .withSources(new PropertiesConfigSource(Map.of("quarkus.http.host", "127.0.0.1"), "yml", 255))+ .withSources(new PropertiesConfigSource(Map.of("quarkus.http.host", "0.0.0.0"), "sysprops", 400))+ .build();++ assertEquals("0.0.0.0", NetworkExposureGuard.publicHost(config));+ }++ @Test+ void publicHostIgnoresTheLoopbackPinTlsModeAppliesToQuarkus() {+ System.setProperty("floci.tls.enabled", "true");+ System.setProperty("floci.tls.self-signed", "true");+ System.setProperty("floci.storage.persistent-path", tempDir.toString());+ SmallRyeConfig config = new SmallRyeConfigBuilder()+ .withSources(new TlsConfigSource())+ .withSources(new PropertiesConfigSource(Map.of("quarkus.http.host", "0.0.0.0"), "yml", 255))+ .build();++ assertEquals("127.0.0.1", config.getValue("quarkus.http.host", String.class),+ "precondition: TLS mode keeps Quarkus itself on loopback behind the proxy");+ assertEquals("0.0.0.0", NetworkExposureGuard.publicHost(config),+ "the proxy must listen where the user asked, not on the internal pin");+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerReservedPortTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerReservedPortTest.javaindex 1a0a1809bf..16fc29a1ff 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerReservedPortTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerReservedPortTest.java@@ -43,7 +43,7 @@ class TlsProxyServerReservedPortTest {when(vertx.createNetClient()).thenReturn(mock(NetClient.class));when(vertx.createNetServer(any())).thenReturn(server);- return new TlsProxyServer(vertx, config, 4510, 4511);+ return new TlsProxyServer(vertx, config, "127.0.0.1", 4510, 4511);}/**@@ -76,7 +76,7 @@ class TlsProxyServerReservedPortTest {when(vertx.createNetClient()).thenReturn(mock(NetClient.class));when(vertx.createNetServer(any())).thenReturn(server);- TlsProxyServer proxy = new TlsProxyServer(vertx, config, 4510, 4511);+ TlsProxyServer proxy = new TlsProxyServer(vertx, config, "127.0.0.1", 4510, 4511);beforeStart.accept(proxy);return proxy;}diff --git a/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java b/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.javaindex 7a663c8dec..09deb260da 100644--- a/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java+++ b/src/test/java/io/github/hectorvent/floci/config/TlsProxyServerTest.java@@ -8,17 +8,25 @@ import org.junit.jupiter.api.Test;import org.junit.jupiter.api.Timeout;import java.io.IOException;+import java.net.Inet4Address;+import java.net.InetAddress;+import java.net.InetSocketAddress;+import java.net.NetworkInterface;import java.net.ServerSocket;import java.net.Socket;+import java.net.SocketException;import java.nio.charset.StandardCharsets;+import java.util.Collections;import java.util.Set;import java.util.concurrent.CompletableFuture;import java.util.concurrent.TimeUnit;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.junit.jupiter.api.Assertions.fail;+import static org.junit.jupiter.api.Assumptions.assumeTrue;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.when;@@ -62,27 +70,66 @@ class TlsProxyServerTest {when(config.tls()).thenReturn(tls);when(tls.enabled()).thenReturn(tlsEnabled);when(tls.awsHttpsPort()).thenReturn(awsHttpsPort);+ when(config.security()).thenReturn(mock(EmulatorConfig.SecurityConfig.class));return config;}@Testvoid listenPorts_includesPublicAndAwsHttpsPort() {- proxy = new TlsProxyServer(vertx, configWith(false, 4566, 443), 4510, 4511);+ proxy = new TlsProxyServer(vertx, configWith(false, 4566, 443), "127.0.0.1", 4510, 4511);assertEquals(Set.of(4566, 443), proxy.listenPorts());}@Testvoid listenPorts_dropsAwsHttpsPortWhenZero() {- proxy = new TlsProxyServer(vertx, configWith(false, 4566, 0), 4510, 4511);+ proxy = new TlsProxyServer(vertx, configWith(false, 4566, 0), "127.0.0.1", 4510, 4511);assertEquals(Set.of(4566), proxy.listenPorts());}@Testvoid listenPorts_dedupesWhenAwsHttpsPortEqualsPublic() {- proxy = new TlsProxyServer(vertx, configWith(false, 4566, 4566), 4510, 4511);+ proxy = new TlsProxyServer(vertx, configWith(false, 4566, 4566), "127.0.0.1", 4510, 4511);assertEquals(Set.of(4566), proxy.listenPorts());}+ @Test+ @Timeout(20)+ void bindsTheConfiguredHost_notEveryInterface() throws Exception {+ InetAddress external = nonLoopbackIpv4();+ assumeTrue(external != null, "needs a non-loopback IPv4 interface");+ int publicPort = freePort();++ proxy = new TlsProxyServer(vertx, configWith(true, publicPort, 0), "127.0.0.1", 4510, 4511);++ awaitListening(publicPort);+ assertFalse(accepts(external, publicPort),+ "a proxy configured for 127.0.0.1 must not be reachable on " + external.getHostAddress());+ }++ @Test+ @Timeout(20)+ void nonLoopbackHostWithoutConsent_refusesToListen() throws Exception {+ int publicPort = freePort();++ IllegalStateException e = assertThrows(IllegalStateException.class,+ () -> new TlsProxyServer(vertx, configWith(true, publicPort, 0), "0.0.0.0", 4510, 4511));++ assertTrue(e.getMessage().contains("FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE"), e.getMessage());+ assertFalse(portAccepts(publicPort), "a refused proxy must not listen");+ }++ @Test+ @Timeout(20)+ void nonLoopbackHostWithConsent_listens() throws Exception {+ int publicPort = freePort();+ EmulatorConfig config = configWith(true, publicPort, 0);+ when(config.security().allowUnsafeNetworkExposure()).thenReturn(true);++ proxy = new TlsProxyServer(vertx, config, "0.0.0.0", 4510, 4511);++ awaitListening(publicPort);+ }+@Test@Timeout(20)void bindsBothPorts_andRoutesByFirstByte() throws Exception {@@ -93,7 +140,7 @@ class TlsProxyServerTest {httpBackend = startMarkerBackend(httpBe, "PLAIN");httpsBackend = startMarkerBackend(httpsBe, "TLS");- proxy = new TlsProxyServer(vertx, configWith(true, publicPort, awsHttpsPort), httpBe, httpsBe);+ proxy = new TlsProxyServer(vertx, configWith(true, publicPort, awsHttpsPort), "127.0.0.1", httpBe, httpsBe);// Public port: TLS ClientHello → HTTPS backend; anything else → HTTP backend.assertEquals("TLS", roundTrip(publicPort, TLS_HANDSHAKE));@@ -107,7 +154,7 @@ class TlsProxyServerTest {@Timeout(20)void tlsDisabled_bindsNothing() throws Exception {int publicPort = freePort();- proxy = new TlsProxyServer(vertx, configWith(false, publicPort, 443), 4510, 4511);+ proxy = new TlsProxyServer(vertx, configWith(false, publicPort, 443), "127.0.0.1", 4510, 4511);assertFalse(portAccepts(publicPort), "no proxy should listen when TLS is disabled");}@@ -162,6 +209,29 @@ class TlsProxyServerTest {}}+ private static boolean accepts(InetAddress address, int port) {+ try (Socket s = new Socket()) {+ s.connect(new InetSocketAddress(address, port), 1000);+ return true;+ } catch (IOException e) {+ return false;+ }+ }++ private static InetAddress nonLoopbackIpv4() throws SocketException {+ for (NetworkInterface nic : Collections.list(NetworkInterface.getNetworkInterfaces())) {+ if (!nic.isUp() || nic.isLoopback()) {+ continue;+ }+ for (InetAddress address : Collections.list(nic.getInetAddresses())) {+ if (address instanceof Inet4Address) {+ return address;+ }+ }+ }+ return null;+ }+private static void closeBackend(NetServer server) {if (server != null) {server.close();diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerCaBundleDockerIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerCaBundleDockerIntegrationTest.javaindex 7f24e6e091..d772072145 100644--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerCaBundleDockerIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerCaBundleDockerIntegrationTest.java@@ -159,7 +159,8 @@ class ContainerCaBundleDockerIntegrationTest {"quarkus.tls.key-store.pem.0.cert", CERT_FILE.toString(),"quarkus.tls.key-store.pem.0.key", KEY_FILE.toString(),"quarkus.http.insecure-requests", "enabled",- "quarkus.http.host", "0.0.0.0");+ "quarkus.http.host", "0.0.0.0",+ "floci.security.allow-unsafe-network-exposure", "true");}}}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex da90ed2ece..9721c395b5 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -2,6 +2,9 @@ quarkus:http:port: 0test-port: 0+ # Integration signatures use localhost as the public test authority. Keep the test listener+ # explicit so the production loopback default does not change the signed host.+ host: 0.0.0.0limits:max-body-size: ${floci.protocols.max-request-size}M# Groovy (a REST Assured dependency) starts DFA-cache-cleaner threads that never stop.@@ -96,6 +99,9 @@ floci:extra-cors-allowed-headers: ${EXTRA_CORS_ALLOWED_HEADERS:}extra-cors-expose-headers: ${EXTRA_CORS_EXPOSE_HEADERS:}disable-cors-headers: false+ # The test listener binds all interfaces so Quarkus keeps localhost as its test authority.+ # This is test-only; production keeps the loopback default.+ allow-unsafe-network-exposure: trueinit-hooks:shell-executable: /bin/sh