feat(core): translate LocalStack variables in Java instead of the entrypoint (#5851)

* feat(core): translate LocalStack variables in Java instead of the entrypoint

The LocalStack-to-Floci variable mapping (PERSISTENCE, EDGE_PORT,
LOCALSTACK_HOST, GATEWAY_LISTEN, LS_LOG/DEBUG, the Lambda and Docker
variables, the DNS suffixes, USE_SSL, CUSTOM_SSL_CERT_PATH) lived in
docker/localstack-parity.sh, sourced by the image's entrypoint. A JVM run or
a native binary on the host never saw it.

LocalStackParity now computes the same mapping and LocalStackParityConfigSource
serves it at ordinal 301, just above environment variables, as the exported
variables did. A key is produced only when its Floci variable is unset, so an
explicit Floci setting still wins; the DNS suffixes are still appended to any
configured ones; LOCALSTACK_PARITY=false still turns it all off.
TlsConfigSource, which reads its properties before the configuration exists,
consults the mapping too.

The script, its shell test and every Dockerfile copy of it are removed; the
test cases move to LocalStackParityTest.

Refs #5767

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(core): keep TLS backends on loopback, keep configured DNS suffixes, and pass LocalStack settings to hooks

Review follow-ups for the Java LocalStack translation:

- Dockerfile.compat took docker-entrypoint.sh from the published native
  image, which still sourced the removed localstack-parity.sh, so the compat
  image never became healthy. It now copies the entrypoint from the build
  context, as it already does healthcheck.sh.
- At ordinal 301 the parity source outranked TlsConfigSource's loopback pin
  (300): with TLS on and GATEWAY_LISTEN set, the backends bound the gateway
  address while the proxy dialled 127.0.0.1. It now sits at 299, below
  environment variables and the TLS source and above .env and
  config/application.yml, where the exported variables used to be.
- floci.dns.extra-suffixes is no longer a translated property, which on JVM
  and native runs replaced suffixes set in application.yml. The five
  readers append LocalStack's and Floci's suffixes to the configured list
  through LocalStackParity.withDnsSuffixes instead.
- GATEWAY_LISTEN=0.0.0.0:4566 (or [::]:4566, or a list) gives the host to
  quarkus.http.host and the port to floci.port when EDGE_PORT is unset,
  instead of a host Floci rejects as malformed.
- Init hooks get the translation as FLOCI_*/QUARKUS_* variables again, as
  they did when the entrypoint exported them.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

* fix(core): parse LOCALSTACK_HOST and GATEWAY_LISTEN the way LocalStack does

Both take LocalStack's host-and-port forms (HostAndPort.parse in its
config.py): host:port, host, :port, [v6]:port and [v6].

- LOCALSTACK_HOST is <hostname>:<port>, localhost.localstack.cloud:4566 by
  default. Its port went into floci.hostname, so the base URL came out as
  http://localhost.localstack.cloud:4566:4566. floci.hostname now gets the
  host alone.
- GATEWAY_LISTEN=:4566, LocalStack's default host on 4566, did not match
  and stopped startup with "Refusing to listen on malformed host". An empty
  host now keeps Floci's own bind address and takes just the port.

Signed-off-by: Hector Ventura <hectorvent@gmail.com>

---------

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-10-17 17:37:15 -04:00
1 parent 9e6be8ff21
commit 9dcb1b65ae
22 files changed
+470 -252

No files matched your search

@@ -0,0 +1,200 @@
package io.github.hectorvent.floci.config;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Translates LocalStack Community environment variables into the Floci configuration they mean,
* so a LocalStack setup works unchanged in the image and in a binary on the host alike.
*
* <p>An explicitly set Floci variable always wins: a mapping is produced only when the matching
* {@code FLOCI_*} or {@code QUARKUS_*} environment variable is absent. The DNS suffixes are the
* one exception: LocalStack's and Floci's hostname suffixes are appended to the configured ones,
* wherever those are set ({@link #withDnsSuffixes}). The whole translation is off when
* {@code LOCALSTACK_PARITY=false}.
*/
public final class LocalStackParity {
private static final Logger LOG = Logger.getLogger(LocalStackParity.class);
static final List<String> PARITY_SUFFIXES = List.of("localhost.localstack.cloud", "localhost.floci.io");
private static final Pattern BRACKETED_IPV6 = Pattern.compile("^\\[([^\\]]+)\\](?::(\\d+))?$");
/** One translated setting: the Floci variable it stands for, its property, and its value. */
record Mapping(String variable, String property, String value) {
}
/** A host and a port, either of which may be absent (LocalStack then uses its default). */
record HostAndPort(String host, String port) {
}
private LocalStackParity() {
}
public static boolean enabled(Map<String, String> env) {
return !"false".equals(env.get("LOCALSTACK_PARITY"));
}
/** The translation for this process's environment, as configuration property names. */
public static Map<String, String> forCurrentEnvironment() {
return translate(System.getenv());
}
/**
* @return property name to value, for every LocalStack variable present whose Floci
* counterpart is not set; empty when parity is disabled
*/
public static Map<String, String> translate(Map<String, String> env) {
Map<String, String> out = new LinkedHashMap<>();
for (Mapping mapping : mappings(env)) {
out.put(mapping.property(), mapping.value());
}
return out;
}
/**
* The same translation as {@code FLOCI_*}/{@code QUARKUS_*} variables, for child processes such
* as init hooks: the entrypoint script used to export them, so hooks inherited them. Includes
* {@code FLOCI_DNS_EXTRA_SUFFIXES} with the LocalStack suffixes appended, as the script did.
*/
public static Map<String, String> environment(Map<String, String> env) {
Map<String, String> out = new LinkedHashMap<>();
if (!enabled(env)) {
return out;
}
for (Mapping mapping : mappings(env)) {
out.put(mapping.variable(), mapping.value());
}
String suffixes = env.get("FLOCI_DNS_EXTRA_SUFFIXES");
out.put("FLOCI_DNS_EXTRA_SUFFIXES", String.join(",", withDnsSuffixes(
isSet(suffixes) ? Optional.of(List.of(suffixes.split(","))) : Optional.empty(), env).orElseThrow()));
return out;
}
/** The configured extra DNS suffixes, plus LocalStack's and Floci's when parity is on. */
public static Optional<List<String>> withDnsSuffixes(Optional<List<String>> configured) {
return withDnsSuffixes(configured, System.getenv());
}
static Optional<List<String>> withDnsSuffixes(Optional<List<String>> configured, Map<String, String> env) {
if (!enabled(env)) {
return configured;
}
Set<String> suffixes = new LinkedHashSet<>(configured.orElse(List.of()));
suffixes.addAll(PARITY_SUFFIXES);
return Optional.of(List.copyOf(suffixes));
}
private static List<Mapping> mappings(Map<String, String> env) {
List<Mapping> out = new ArrayList<>();
if (!enabled(env)) {
return out;
}
String persist = firstSet(env, "PERSISTENCE", "PERSIST_STATE");
if ("1".equals(persist) || "true".equals(persist)) {
put(out, env, "FLOCI_STORAGE_MODE", "floci.storage.mode", "persistent");
}
// LocalStack listens on GATEWAY_LISTEN with no further opt-in, so it also gives the
// consent Floci requires for a non-loopback address. Its first entry may carry a port,
// which stands in for EDGE_PORT when that is unset.
// An empty host (":4566") keeps Floci's own bind address and takes just the port.
String gatewayListen = env.get("GATEWAY_LISTEN");
HostAndPort gateway = isSet(gatewayListen)
? parseHostAndPort(gatewayListen.split(",")[0])
: new HostAndPort(null, null);
String gatewayHost = gateway.host();
put(out, env, "FLOCI_PORT", "floci.port", isSet(env.get("EDGE_PORT")) ? env.get("EDGE_PORT") : gateway.port());
// LOCALSTACK_HOST is <hostname>:<port> (default localhost.localstack.cloud:4566); Floci's
// hostname is the host alone, its port comes from floci.port.
String localstackHost = firstSet(env, "LOCALSTACK_HOST", "LOCALSTACK_HOSTNAME");
put(out, env, "FLOCI_HOSTNAME", "floci.hostname",
isSet(localstackHost) ? parseHostAndPort(localstackHost).host() : null);
if (isSet(gatewayHost)) {
put(out, env, "QUARKUS_HTTP_HOST", "quarkus.http.host", gatewayHost);
put(out, env, "FLOCI_SECURITY_ALLOW_UNSAFE_NETWORK_EXPOSURE",
"floci.security.allow-unsafe-network-exposure", "true");
}
String lsLog = env.get("LS_LOG");
if (isSet(lsLog)) {
put(out, env, "QUARKUS_LOG_LEVEL", "quarkus.log.level", lsLog);
} else if ("1".equals(env.get("DEBUG"))) {
put(out, env, "QUARKUS_LOG_LEVEL", "quarkus.log.level", "DEBUG");
}
put(out, env, "FLOCI_SERVICES_LAMBDA_DOCKER_NETWORK", "floci.services.lambda.docker-network",
env.get("LAMBDA_DOCKER_NETWORK"));
String removeContainers = env.get("LAMBDA_REMOVE_CONTAINERS");
if ("1".equals(removeContainers) || "true".equals(removeContainers)) {
put(out, env, "FLOCI_SERVICES_LAMBDA_EPHEMERAL", "floci.services.lambda.ephemeral", "true");
}
if (isSet(env.get("LAMBDA_REMOTE_DOCKER"))) {
LOG.warn("LAMBDA_REMOTE_DOCKER is not fully supported by Floci. Use S3Bucket=hot-reload per function"
+ " instead. See https://floci.io/docs/services/lambda");
}
put(out, env, "FLOCI_DOCKER_DOCKER_HOST", "floci.docker.docker-host", env.get("DOCKER_HOST"));
// Shared by every container-backed service; per-service networks still take precedence.
put(out, env, "FLOCI_SERVICES_DOCKER_NETWORK", "floci.services.docker-network", env.get("DOCKER_NETWORK"));
if ("1".equals(env.get("USE_SSL"))) {
put(out, env, "FLOCI_TLS_ENABLED", "floci.tls.enabled", "true");
}
// LocalStack takes one combined PEM (certificate and key); Floci accepts it in both fields.
String customCert = env.get("CUSTOM_SSL_CERT_PATH");
put(out, env, "FLOCI_TLS_CERT_PATH", "floci.tls.cert-path", customCert);
put(out, env, "FLOCI_TLS_KEY_PATH", "floci.tls.key-path", customCert);
// LAMBDA_EXECUTOR and SERVICES are intentionally ignored.
return out;
}
/**
* Parses the forms LocalStack's {@code HostAndPort.parse} accepts: {@code host:port},
* {@code host}, {@code :port}, {@code [v6]:port} and {@code [v6]}. A missing part is null.
*/
static HostAndPort parseHostAndPort(String input) {
String value = input.trim();
Matcher ipv6 = BRACKETED_IPV6.matcher(value);
if (ipv6.matches()) {
return new HostAndPort(ipv6.group(1), ipv6.group(2));
}
int colon = value.indexOf(':');
if (colon < 0) {
return new HostAndPort(value.isEmpty() ? null : value, null);
}
String host = value.substring(0, colon).trim();
String port = value.substring(colon + 1).trim();
return new HostAndPort(host.isEmpty() ? null : host, port.isEmpty() ? null : port);
}
private static void put(List<Mapping> out, Map<String, String> env, String flociVariable,
String property, String value) {
if (isSet(value) && !isSet(env.get(flociVariable))) {
out.add(new Mapping(flociVariable, property, value));
}
}
private static String firstSet(Map<String, String> env, String first, String second) {
String value = env.get(first);
return isSet(value) ? value : env.get(second);
}
private static boolean isSet(String value) {
return value != null && !value.isEmpty();
}
}
@@ -0,0 +1,56 @@
package io.github.hectorvent.floci.config;
import org.eclipse.microprofile.config.spi.ConfigSource;
import java.util.Map;
import java.util.Set;
/**
* Serves {@link LocalStackParity}'s translation as configuration.
*
* <p>The ordinal (299) sits just below environment variables (300), and above {@code .env} (295)
* and {@code config/application.yml} (265), as the {@code FLOCI_*} variables the replaced shell
* script exported did. A translated key is only present when its Floci variable is unset, so it
* never shadows one. Staying below 300 also keeps {@link TlsConfigSource}'s loopback pin of
* {@code quarkus.http.host} in force when TLS is on and {@code GATEWAY_LISTEN} names the public
* address, which {@link NetworkExposureGuard#publicHost} still reads from here.
*/
public class LocalStackParityConfigSource implements ConfigSource {
static final int ORDINAL = 299;
private final Map<String, String> properties;
public LocalStackParityConfigSource() {
this(LocalStackParity.forCurrentEnvironment());
}
LocalStackParityConfigSource(Map<String, String> properties) {
this.properties = Map.copyOf(properties);
}
@Override
public Map<String, String> getProperties() {
return properties;
}
@Override
public Set<String> getPropertyNames() {
return properties.keySet();
}
@Override
public String getValue(String propertyName) {
return properties.get(propertyName);
}
@Override
public String getName() {
return "floci-localstack-parity";
}
@Override
public int getOrdinal() {
return ORDINAL;
}
}
@@ -250,7 +250,7 @@ public class TlsCertificateManager implements Resettable {
} catch (RuntimeException e) {
LOG.debugv("TLS: floci.base-url {0} has no usable host: {1}", config.baseUrl(), e.getMessage());
}
config.dns().extraSuffixes().ifPresent(list -> list.forEach(s -> suffixes.add(s.toLowerCase(Locale.ROOT))));
LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()).ifPresent(list -> list.forEach(s -> suffixes.add(s.toLowerCase(Locale.ROOT))));
String bare = name.startsWith("*.") ? name.substring(2) : name;
for (String suffix : suffixes) {
if (DomainNames.isWithin(bare, suffix)) {
@@ -207,6 +207,11 @@ public class TlsConfigSource implements ConfigSource {
if (value != null && !value.isBlank())
return value;
// 3. A LocalStack variable that means the same thing (USE_SSL, CUSTOM_SSL_CERT_PATH)
value = LocalStackParity.forCurrentEnvironment().get(key);
if (value != null && !value.isBlank())
return value;
return defaultValue;
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.core.common.dns;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.LocalStackParity;
import io.github.hectorvent.floci.config.TlsConfigSource;
import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -157,7 +158,7 @@ public class EmbeddedDnsServer {
suffixes.addAll(BUILTIN_SUFFIXES);
config.hostname().ifPresent(suffixes::add);
config.dns().extraSuffixes().ifPresent(suffixes::addAll);
LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()).ifPresent(suffixes::addAll);
if (config.dns().spoofAwsEndpoints()) {
suffixes.addAll(TlsConfigSource.awsEndpointSuffixes());
if (shouldWarnSpoofInvisibleToTls(true, TlsConfigSource.tlsEnabledVisibleToTls(),
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.lifecycle.inithook;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.LocalStackParity;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -39,7 +40,11 @@ public class HookScriptExecutor {
LOG.debugv("Executing hook script {0} via {1}", scriptFileName, command.getFirst());
// Inherit parent I/O so script output is streamed directly and does not block on unconsumed buffers.
final Process process = new ProcessBuilder(command).directory(hookDirectory).inheritIO().start();
final ProcessBuilder builder = new ProcessBuilder(command).directory(hookDirectory).inheritIO();
// The entrypoint script used to export the translated LocalStack settings as FLOCI_*
// variables, and hooks read them; the translation now lives in Java, so pass it on.
LocalStackParity.environment(System.getenv()).forEach(builder.environment()::putIfAbsent);
final Process process = builder.start();
run(process, scriptFileName);
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudfront;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.LocalStackParity;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.CloudFrontEdgeDomain;
import io.github.hectorvent.floci.core.common.RegionResolver;
@@ -473,7 +474,7 @@ public class CloudFrontService implements ServerCertificateReferenceProvider {
endpointHosts.add("localhost");
EmbeddedDnsServer.BUILTIN_SUFFIXES.forEach(endpointHosts::add);
config.hostname().ifPresent(endpointHosts::add);
config.dns().extraSuffixes().ifPresent(endpointHosts::addAll);
LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()).ifPresent(endpointHosts::addAll);
return endpointHosts.stream()
.map(host -> ".cloudfront." + host.toLowerCase(Locale.ROOT))
.toList();
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.route53;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.LocalStackParity;
import io.github.hectorvent.floci.core.common.DomainNames;
import io.github.hectorvent.floci.core.common.dns.DnsAnswer;
import io.github.hectorvent.floci.core.common.dns.DnsLookupHelper;
@@ -60,7 +61,7 @@ public class Route53DnsRecordSource implements DnsRecordSource {
if (config != null) {
config.hostname().ifPresent(this.flociSuffixes::add);
if (config.dns() != null) {
config.dns().extraSuffixes().ifPresent(this.flociSuffixes::addAll);
LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()).ifPresent(this.flociSuffixes::addAll);
}
}
}
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.config.LocalStackParity;
import io.github.hectorvent.floci.core.common.AwsPartitions;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.RequestHost;
@@ -76,7 +77,7 @@ public class S3VirtualHostFilter implements ContainerRequestFilter {
.orElseGet(() -> containerDetector.isRunningInContainer()
? EmbeddedDnsServer.DEFAULT_SUFFIX
: extractHostnameFromUrl(config.baseUrl()));
this.serviceHostSuffixes = buildServiceHostSuffixes(config.hostname(), config.dns().extraSuffixes());
this.serviceHostSuffixes = buildServiceHostSuffixes(config.hostname(), LocalStackParity.withDnsSuffixes(config.dns().extraSuffixes()));
this.s3ServiceInstance = s3ServiceInstance;
}