fix(config): enforce safe default network binding (#3684)

* fix: enforce safe default network binding

* fix(config): keep signed test authority stable

Pin the integration-test listener to the existing all-interface test bind and
opt into that bind only in the test profile. This preserves localhost-based
SigV4 fixtures while production keeps the loopback default.

* fix(config): keep compat image backward compatible

* chore: retrigger CI

* fix(config): mirror JVM image network binding
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-16 14:46:09 -04:00
1 parent a1419b9e69
commit 1831f10105
24 files changed
+444 -34

No files matched your search

+2 -1
View File
@@ -81,4 +81,5 @@ HEALTHCHECK --interval=5s --timeout=3s --retries=5 \
CMD wget -q --spider http://localhost:4566/_floci/health || exit 1
ENTRYPOINT ["/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"]
+6 -1
View File
@@ -98,6 +98,10 @@ FROM tools
ARG VERSION
ENV 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=true
COPY --from=native --chown=1001:root /app/ /app/
VOLUME /app/data
@@ -111,6 +115,7 @@ EXPOSE 4566
HEALTHCHECK --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
USER 1001
+2 -1
View File
@@ -80,4 +80,5 @@ HEALTHCHECK --interval=5s --timeout=3s --retries=5 \
CMD wget -q --spider http://localhost:4566/_floci/health || exit 1
ENTRYPOINT ["/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"]
+2 -1
View File
@@ -46,4 +46,5 @@ COPY --chmod=755 docker/entrypoint.sh /usr/local/bin/docker-entrypoint.sh
COPY --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"]
+2 -1
View File
@@ -43,4 +43,5 @@ EXPOSE 4566
HEALTHCHECK --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"]
+4 -2
View File
@@ -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 ]; then
if [ -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=true
else
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.jar
fi
fi
+6 -2
View File
@@ -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_LEVEL
if [ -n "${LS_LOG:-}" ]; then
+2 -2
View File
@@ -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 ]; then
assert_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}")"
else
printf '[SKIP] empty argv falls back to the JVM default command (/app/application exists on this host)\n'
@@ -111,7 +111,7 @@ EOF
fi
if [ "${NATIVE_TESTABLE}" = 'true' ]; then
assert_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}")"
else
printf '[SKIP] empty argv prefers the native binary when present (/app not writable)\n'
+12
View File
@@ -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" \
@@ -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 |
+2
View File
@@ -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 Certificate
When `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:
@@ -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 |
@@ -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 {
@@ -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();
}
}
@@ -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 {
@Override
public String getName() {
return "FlociTlsConfigSource";
return NAME;
}
/**
@@ -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());
+14 -6
View File
@@ -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: false
limits:
@@ -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: false
tls:
enabled: false # FLOCI_TLS_ENABLED (default: false)
@@ -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");
}
@Test
void productionConfigDoesNotSeedIamDeployerPrincipalByDefault() throws IOException {
JsonNode config = new YAMLMapper().readTree(Path.of("src/main/resources/application.yml").toFile());
@@ -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)) {
@@ -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");
}
}
@@ -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;
}
@@ -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;
}
@Test
void 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());
}
@Test
void 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());
}
@Test
void 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();
@@ -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");
}
}
}
+6
View File
@@ -2,6 +2,9 @@ quarkus:
http:
port: 0
test-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.0
limits:
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: true
init-hooks:
shell-executable: /bin/sh