Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(ui): add a bind address for the web console sidecar (#4175)

Abhigya899c6f5ec16c
diff --git a/README.md b/README.md
index b61c4100b3..4c8ac959cb 100644
--- a/README.md
+++ b/README.md
@@ -156,6 +156,7 @@ services:
| `FLOCI_SERVICES_UI_IMAGE` | `floci/floci-ui:latest` | Console image to run |
| `FLOCI_SERVICES_UI_CONTAINER_NAME` | `floci-ui` | Name of the sidecar container |
| `FLOCI_SERVICES_UI_PORT` | `4500` | Host port the console is published on |
+| `FLOCI_SERVICES_UI_BIND_ADDRESS` | _(none)_ | Host interface that port is published on. Unset publishes on every interface; set `127.0.0.1` when Floci's own port is loopback-only |
| `FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave the sidecar running when Floci stops |
### Running a different console
diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md
index 660b13eff0..c17becfdbd 100644
--- a/docs/configuration/environment-variables.md
+++ b/docs/configuration/environment-variables.md
@@ -507,6 +507,7 @@ Floci starts the web console as a sidecar container the first time `/_floci/ui`
| `FLOCI_SERVICES_UI_IMAGE` | `floci/floci-ui:latest` | Console image to run |
| `FLOCI_SERVICES_UI_CONTAINER_NAME` | `floci-ui` | Name of the sidecar container |
| `FLOCI_SERVICES_UI_PORT` | `4500` | Host port the console is published on |
+| `FLOCI_SERVICES_UI_BIND_ADDRESS` | _(none)_ | Host interface that port is published on. Unset publishes on every interface; set `127.0.0.1` when Floci's own port is loopback-only |
| `FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave the sidecar running when Floci stops |
| `FLOCI_SERVICES_UI_DOCKER_NETWORK` | _(none)_ | Docker network for the sidecar (overrides `FLOCI_SERVICES_DOCKER_NETWORK`) |
| `FLOCI_SERVICES_UI_ENDPOINT` | _(derived)_ | Floci endpoint handed to the console, instead of deriving it from the Docker host and TLS settings |
diff --git a/docs/ui/index.md b/docs/ui/index.md
index 192753f177..724408e44d 100644
--- a/docs/ui/index.md
+++ b/docs/ui/index.md
@@ -30,6 +30,18 @@ Console container logs are streamed into CloudWatch Logs under the log group `/f
Port `4500` is bound on the host by Docker, not by Floci, so it needs **no** `ports:` entry in your
`docker-compose.yml`. See [Ports Reference](../configuration/ports.md).
+Docker publishes it on every interface, the same as a bare `"4500:4500"` mapping. If you
+deliberately keep Floci itself on loopback, with a `"127.0.0.1:4566:4566"` mapping rather than
+`"4566:4566"`, set the console to match:
+
+```yaml
+environment:
+ FLOCI_SERVICES_UI_BIND_ADDRESS: "127.0.0.1"
+```
+
+The console is unauthenticated and can drive every emulated service, so without this it would be
+reachable from the network that the API mapping was narrowed to keep it off.
+
## Configuration
All keys live under `floci.services.ui.*`, so `FLOCI_SERVICES_UI_*` as environment variables.
@@ -40,6 +52,7 @@ All keys live under `floci.services.ui.*`, so `FLOCI_SERVICES_UI_*` as environme
| `FLOCI_SERVICES_UI_IMAGE` | `floci/floci-ui:latest` | Console image to run |
| `FLOCI_SERVICES_UI_CONTAINER_NAME` | `floci-ui` | Name of the sidecar container |
| `FLOCI_SERVICES_UI_PORT` | `4500` | Host port the console is published on |
+| `FLOCI_SERVICES_UI_BIND_ADDRESS` | _(none)_ | Host interface that port is published on (see [Ports](#ports)) |
| `FLOCI_SERVICES_UI_KEEP_RUNNING_ON_SHUTDOWN` | `false` | Leave the sidecar running when Floci stops |
| `FLOCI_SERVICES_UI_DOCKER_NETWORK` | _(none)_ | Docker network for the sidecar (overrides `FLOCI_SERVICES_DOCKER_NETWORK`) |
| `FLOCI_SERVICES_UI_ENDPOINT` | _(derived)_ | Floci endpoint handed to the console, instead of deriving it from the Docker host and TLS settings |
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 115184fe6a..d9fea803d0 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -2313,6 +2313,21 @@ public interface EmulatorConfig {
@WithDefault("4500")
int port();
+ /**
+ * Host interface {@link #port()} is published on.
+ * Env: {@code FLOCI_SERVICES_UI_BIND_ADDRESS}
+ *
+ * <p>Unset by default, which is Docker's own default of publishing on every interface.
+ * Set it to {@code 127.0.0.1} when Floci's own port is published on loopback only
+ * (a {@code "127.0.0.1:4566:4566"} mapping, say): the console is unauthenticated and
+ * drives every emulated service, so leaving it on every interface would hand out an
+ * authority the API deliberately withholds.
+ *
+ * <p>A blank value is a hard error rather than a silent fall back to the wildcard: an
+ * operator who set the key meant to choose an address.
+ */
+ Optional<String> bindAddress();
+
/**
* Port the console listens on <em>inside</em> its container, published as {@link #port()}.
* Env: {@code FLOCI_SERVICES_UI_INTERNAL_PORT}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
index d8e44278b6..e9cb506fa7 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerBuilder.java
@@ -132,6 +132,7 @@ public class ContainerBuilder {
private boolean readonlyRootfs;
private final Map<Integer, Integer> portBindings = new HashMap<>();
private final List<Integer> loopbackPortBindings = new ArrayList<>();
+ private final Map<Integer, String> portBindingHostIps = new HashMap<>();
private final List<Integer> exposedPorts = new ArrayList<>();
private String networkMode;
private final List<Mount> mounts = new ArrayList<>();
@@ -263,6 +264,21 @@ public class ContainerBuilder {
return this;
}
+ /**
+ * Adds a port binding to a specific host port on a specific host interface.
+ *
+ * <p>Use this for a port whose reachability is an operator decision rather than a fixed
+ * property of the container: the caller passes the configured address through, and a null
+ * or blank one falls back to Docker's own default of publishing on every interface.
+ */
+ public Builder withPortBinding(int containerPort, int hostPort, String hostIp) {
+ withPortBinding(containerPort, hostPort);
+ if (hostIp != null && !hostIp.isBlank()) {
+ this.portBindingHostIps.put(containerPort, hostIp.strip());
+ }
+ return this;
+ }
+
/**
* Publishes a container port to the host loopback interface only.
*
@@ -657,7 +673,8 @@ public class ContainerBuilder {
nanoCpus,
cpuShares,
readonlyRootfs,
- List.copyOf(linkLocalIps)
+ List.copyOf(linkLocalIps),
+ Map.copyOf(portBindingHostIps)
);
}
}
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
index 2285080b31..bc2e6027a4 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManager.java
@@ -63,6 +63,9 @@ public class ContainerLifecycleManager {
private static final long NANO_CPUS_PER_CPU = 1_000_000_000L;
+ /** Host interface a port marked loopback-only publishes on. */
+ private static final String LOOPBACK_HOST_IP = "127.0.0.1";
+
private final DockerClient dockerClient;
private final ImageCacheService imageCacheService;
private final ContainerDetector containerDetector;
@@ -999,10 +1002,7 @@ public class ContainerLifecycleManager {
hostPort = portAllocator.allocateAny();
}
- Ports.Binding binding = spec.loopbackPortBindings().contains(containerPort)
- ? Ports.Binding.bindIpAndPort("127.0.0.1", hostPort)
- : Ports.Binding.bindPort(hostPort);
- ports.bind(ExposedPort.tcp(containerPort), binding);
+ ports.bind(ExposedPort.tcp(containerPort), bindingFor(spec, containerPort, hostPort));
LOG.debugv("Port binding: {0} -> {1}", String.valueOf(containerPort), String.valueOf(hostPort));
}
hostConfig.withPortBindings(ports);
@@ -1058,6 +1058,27 @@ public class ContainerLifecycleManager {
return hostConfig;
}
+ /**
+ * The host interface a published port binds to.
+ *
+ * <p>An explicit address from {@code portBindingHostIps} wins, so a caller that reads the
+ * address from configuration keeps control of it. {@code loopbackPortBindings} is the fixed
+ * form of the same decision, for a port that is an implementation detail and must never leave
+ * the host. A port in neither binds every interface, which is Docker's own default and what
+ * every caller that does not ask has always got.
+ */
+ private static Ports.Binding bindingFor(ContainerSpec spec, int containerPort, int hostPort) {
+ String hostIp = spec.portBindingHostIps() == null
+ ? null
+ : spec.portBindingHostIps().get(containerPort);
+ if (hostIp != null && !hostIp.isBlank()) {
+ return Ports.Binding.bindIpAndPort(hostIp, hostPort);
+ }
+ return spec.loopbackPortBindings().contains(containerPort)
+ ? Ports.Binding.bindIpAndPort(LOOPBACK_HOST_IP, hostPort)
+ : Ports.Binding.bindPort(hostPort);
+ }
+
/**
* Holds a CPU quota to what the daemon will accept. Docker rejects a NanoCpus above the
* host's CPU count ("range of CPUs is from 0.01 to 8.00, as there are only 8 CPUs
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java
index 9b5e455c53..46651db08c 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/ContainerSpec.java
@@ -43,6 +43,8 @@ import java.util.regex.Pattern;
* @param cpuShares Relative CPU weight against other containers (null = daemon default)
* @param readonlyRootfs Whether the container's own filesystem is mounted read only
* @param linkLocalIps Link-local IPv4 addresses assigned to the container's endpoint on the configured network
+ * @param portBindingHostIps Host interface each published port binds to, keyed by container port.
+ * A port with no entry here, and not in {@code loopbackPortBindings}, binds every interface
*/
public record ContainerSpec(
String image,
@@ -71,7 +73,8 @@ public record ContainerSpec(
Long nanoCpus,
Integer cpuShares,
boolean readonlyRootfs,
- List<String> linkLocalIps
+ List<String> linkLocalIps,
+ Map<Integer, String> portBindingHostIps
) {
private static final Pattern LINK_LOCAL_IPV4 = Pattern.compile("^169\\.254\\.(\\d{1,3})\\.(\\d{1,3})$");
private static final Set<String> NETWORKS_WITHOUT_ENDPOINT_IPAM = Set.of("bridge", "default", "host", "none");
@@ -90,7 +93,7 @@ public record ContainerSpec(
public ContainerSpec(String image) {
this(image, null, List.of(), null, null, null, Map.of(), List.of(), List.of(), null,
List.of(), List.of(), List.of(), List.of(), Map.of(), null, false, null, List.of(),
- null, null, List.of(), List.of(), null, null, false, List.of());
+ null, null, List.of(), List.of(), null, null, false, List.of(), Map.of());
}
/**
@@ -121,7 +124,8 @@ public record ContainerSpec(
) {
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, List.of(), exposedPorts,
networkMode, mounts, binds, List.of(), extraHosts, labels, logConfig, privileged,
- cgroupnsMode, dnsServers, workingDir, user, groupAdd, List.of(), null, null, false, List.of());
+ cgroupnsMode, dnsServers, workingDir, user, groupAdd, List.of(), null, null, false,
+ List.of(), Map.of());
}
/**
@@ -155,7 +159,7 @@ public record ContainerSpec(
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings,
exposedPorts, networkMode, mounts, binds, List.of(), extraHosts, labels, logConfig,
privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, List.of(),
- null, null, false, List.of());
+ null, null, false, List.of(), Map.of());
}
/**
@@ -189,7 +193,7 @@ public record ContainerSpec(
this(image, name, env, cmd, entrypoint, memoryBytes, portBindings, loopbackPortBindings,
exposedPorts, networkMode, mounts, binds, List.of(), extraHosts, labels, logConfig,
privileged, cgroupnsMode, dnsServers, workingDir, user, groupAdd, deviceRequests,
- null, null, false, List.of());
+ null, null, false, List.of(), Map.of());
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManager.java b/src/main/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManager.java
index b420a2c470..a45cd898d3 100644
--- a/src/main/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManager.java
+++ b/src/main/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManager.java
@@ -174,6 +174,9 @@ public class FlociUiManager {
this.lastError = null;
String image = config.services().ui().image();
try {
+ // Before the image pull: a rejected bind address is a configuration error, and
+ // downloading a console that is not going to be published is wasted work.
+ String bindAddress = resolveBindAddress(config.services().ui().bindAddress());
this.profile = resolveProfile(image);
String name = ContainerStorageHelper.dockerName(config, config.services().ui().containerName());
@@ -190,7 +193,7 @@ public class FlociUiManager {
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
.withName(name)
.withEnv(injectedEnv(profile))
- .withPortBinding(internalPort, chosenPort)
+ .withPortBinding(internalPort, chosenPort, bindAddress)
.withDockerNetwork(resolveDockerNetwork())
.withLogRotation();
if (!containerDetector.isRunningInContainer()) {
@@ -205,8 +208,13 @@ public class FlociUiManager {
this.probeUrl = resolveProbeUrl(profile, endpoint, hostPort);
this.started = true;
this.lastError = null;
- LOG.infov("Started web console sidecar {0} from {1} on host port {2}",
- name, image, String.valueOf(hostPort));
+ if (bindAddress == null) {
+ LOG.infov("Started web console sidecar {0} from {1} on host port {2}",
+ name, image, String.valueOf(hostPort));
+ } else {
+ LOG.infov("Started web console sidecar {0} from {1} on {2}:{3}",
+ name, image, bindAddress, String.valueOf(hostPort));
+ }
attachLogStream(false);
} catch (IllegalStateException e) {
// replaceIfEndpointDrifted() records its own specific message for a container with an
@@ -499,6 +507,31 @@ public class FlociUiManager {
return value;
}
+ /**
+ * The host interface the console is published on, or null to publish on every interface.
+ *
+ * <p>Unset is the default and is Docker's own behaviour, which is what the console has always
+ * had. Setting it is how an operator who keeps Floci's own port on loopback keeps the console
+ * there too: the console is unauthenticated and drives every emulated service, so a wildcard
+ * publish would hand out an authority the API mapping deliberately withholds.
+ *
+ * <p>A blank value is an error rather than a silent fall back to the wildcard: an operator who
+ * set the key meant to choose an address, and substituting a different one is how a binding
+ * ends up somewhere nobody intended.
+ */
+ static String resolveBindAddress(Optional<String> configured) {
+ if (configured.isEmpty()) {
+ return null;
+ }
+ String value = configured.get().trim();
+ if (value.isEmpty()) {
+ throw new IllegalStateException(
+ "floci.services.ui.bind-address is set but blank: remove it to publish the "
+ + "console on every interface, or give it a host address to bind.");
+ }
+ return value;
+ }
+
/**
* Whether an adoption candidate must be destroyed and recreated rather than adopted.
*
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 3d80cc3a13..8aa679e287 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -566,6 +566,10 @@ floci:
image: "floci/floci-ui:latest"
container-name: floci-ui
port: 4500
+ # bind-address: unset by default, so Docker publishes the console on every interface.
+ # Set it to 127.0.0.1 when Floci's own port is published on loopback only, so the
+ # unauthenticated console is not reachable where the API deliberately is not.
+ # Env var: FLOCI_SERVICES_UI_BIND_ADDRESS=127.0.0.1
keep-running-on-shutdown: false
# endpoint: unset by default — Floci derives the sidecar's callback address automatically.
# Set an absolute http:// or https:// URL here only to override that derivation.
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java
index 55718394ea..15cab6c6d7 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerNetworkTest.java
@@ -162,6 +162,6 @@ class ContainerLifecycleManagerNetworkTest {
"busybox:stable", null, List.of(), null, null, null, portBindings, List.of(),
List.of(), "test-network", List.of(), List.of(), List.of(), List.of(), Map.of(), null,
false, null, List.of(), null, null, List.of(), List.of(), null, null, false,
- List.of(LINK_LOCAL_IP));
+ List.of(LINK_LOCAL_IP), Map.of());
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerPortBindingTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerPortBindingTest.java
new file mode 100644
index 0000000000..8e36d67e46
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/ContainerLifecycleManagerPortBindingTest.java
@@ -0,0 +1,127 @@
+package io.github.hectorvent.floci.core.common.docker;
+
+import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.command.CreateContainerCmd;
+import com.github.dockerjava.api.command.CreateContainerResponse;
+import com.github.dockerjava.api.model.ExposedPort;
+import com.github.dockerjava.api.model.HostConfig;
+import com.github.dockerjava.api.model.Ports;
+import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.dns.EmbeddedDnsServer;
+import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import java.util.Optional;
+import java.util.function.UnaryOperator;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.RETURNS_SELF;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Pins which host interface a published port lands on. A port bound to every interface is
+ * reachable by anyone who can reach the host, so the difference between a null host IP and an
+ * explicit one is a security boundary rather than a formatting detail.
+ */
+class ContainerLifecycleManagerPortBindingTest {
+
+ @Test
+ void aPlainPortBindingPublishesOnEveryInterface() {
+ Ports.Binding binding = bindingFor(builder -> builder.withPortBinding(8080, 18_080), 8080);
+
+ assertNull(binding.getHostIp(), "Docker's own default is every interface");
+ assertEquals("18080", binding.getHostPortSpec());
+ }
+
+ @Test
+ void aLoopbackPortBindingPublishesOnLoopbackOnly() {
+ Ports.Binding binding = bindingFor(
+ builder -> builder.withLoopbackPortBinding(5050, 5050), 5050);
+
+ assertEquals("127.0.0.1", binding.getHostIp());
+ assertEquals("5050", binding.getHostPortSpec());
+ }
+
+ @Test
+ void anExplicitHostIpReachesTheBinding() {
+ Ports.Binding binding = bindingFor(
+ builder -> builder.withPortBinding(4500, 4500, "127.0.0.1"), 4500);
+
+ assertEquals("127.0.0.1", binding.getHostIp());
+ assertEquals("4500", binding.getHostPortSpec());
+ }
+
+ @Test
+ void anExplicitWildcardHostIpIsPassedThroughAsAsked() {
+ Ports.Binding binding = bindingFor(
+ builder -> builder.withPortBinding(4500, 4500, "0.0.0.0"), 4500);
+
+ assertEquals("0.0.0.0", binding.getHostIp());
+ }
+
+ @Test
+ void aBlankHostIpFallsBackToDockersOwnDefault() {
+ Ports.Binding binding = bindingFor(
+ builder -> builder.withPortBinding(4500, 4500, " "), 4500);
+
+ assertNull(binding.getHostIp());
+ }
+
+ @Test
+ void oneBoundInterfaceDoesNotLeakOntoTheOtherPorts() {
+ ContainerSpec spec = specFor(builder -> builder
+ .withPortBinding(4500, 4500, "127.0.0.1")
+ .withPortBinding(9000, 9000));
+ Ports ports = portsOf(spec);
+
+ assertEquals("127.0.0.1", only(ports, 4500).getHostIp());
+ assertNull(only(ports, 9000).getHostIp());
+ }
+
+ private static Ports.Binding bindingFor(UnaryOperator<ContainerBuilder.Builder> customizer,
+ int containerPort) {
+ return only(portsOf(specFor(customizer)), containerPort);
+ }
+
+ private static Ports.Binding only(Ports ports, int containerPort) {
+ Ports.Binding[] bindings = ports.getBindings().get(ExposedPort.tcp(containerPort));
+ assertEquals(1, bindings.length, "expected exactly one binding for port " + containerPort);
+ return bindings[0];
+ }
+
+ private static ContainerSpec specFor(UnaryOperator<ContainerBuilder.Builder> customizer) {
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
+ ContainerBuilder builder = new ContainerBuilder(
+ config, mock(DockerHostResolver.class), mock(EmbeddedDnsServer.class));
+ return customizer.apply(builder.newContainer("app:latest")).build();
+ }
+
+ private static Ports portsOf(ContainerSpec spec) {
+ EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
+ when(config.docker().resourceNamespace()).thenReturn(Optional.empty());
+ DockerClient dockerClient = mock(DockerClient.class);
+ CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
+ when(dockerClient.createContainerCmd("app:latest")).thenReturn(createCmd);
+ CreateContainerResponse response = mock(CreateContainerResponse.class);
+ when(response.getId()).thenReturn("app-id");
+ when(createCmd.exec()).thenReturn(response);
+ ImageCacheService imageCacheService = mock(ImageCacheService.class);
+ when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
+ PortAllocator portAllocator = mock(PortAllocator.class);
+ ContainerLifecycleManager manager = new ContainerLifecycleManager(
+ dockerClient, imageCacheService, mock(ContainerDetector.class), portAllocator, config);
+
+ manager.create(spec);
+
+ ArgumentCaptor<HostConfig> hostConfig = ArgumentCaptor.forClass(HostConfig.class);
+ verify(createCmd).withHostConfig(hostConfig.capture());
+ return hostConfig.getValue().getPortBindings();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManagerTest.java
index 71cda8ce31..341d327b5f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManagerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/floci/ui/FlociUiManagerTest.java
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.E
import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
+import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import com.github.dockerjava.api.exception.DockerClientException;
@@ -41,6 +42,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -74,6 +76,8 @@ class FlociUiManagerTest {
when(ui.statusReadyField()).thenReturn(Optional.empty());
when(ui.statusReadyValue()).thenReturn(Optional.empty());
when(ui.statusUnavailableValue()).thenReturn(Optional.empty());
+ when(ui.bindAddress()).thenReturn(Optional.empty());
+ when(ui.dockerNetwork()).thenReturn(Optional.empty());
}
private FlociUiManager newManager() {
@@ -896,6 +900,104 @@ class FlociUiManagerTest {
"a pre-contract sidecar must be recreated so it gains the canonical variable");
}
+ // --- where the console is published ---
+
+ @Test
+ void anUnsetBindAddressLeavesDockersOwnDefault() {
+ // Unset is what the console has always had: published on every interface, the same as a
+ // bare "4500:4500" mapping, which is what the documented compose files give the API too.
+ withUiConfig();
+ when(ui.enabled()).thenReturn(true);
+ when(ui.image()).thenReturn("floci/floci-ui:latest");
+ when(ui.containerName()).thenReturn("floci-ui");
+ when(ui.port()).thenReturn(4500);
+ when(ui.endpoint()).thenReturn(Optional.of("http://custom:4566"));
+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
+
+ ContainerBuilder.Builder specBuilder = newStartedSidecar();
+
+ verify(specBuilder).withPortBinding(4500, 4500, null);
+ }
+
+ @Test
+ void aConfiguredBindAddressReachesThePortBinding() {
+ withUiConfig();
+ when(ui.enabled()).thenReturn(true);
+ when(ui.image()).thenReturn("floci/floci-ui:latest");
+ when(ui.containerName()).thenReturn("floci-ui");
+ when(ui.port()).thenReturn(4500);
+ when(ui.endpoint()).thenReturn(Optional.of("http://custom:4566"));
+ when(ui.bindAddress()).thenReturn(Optional.of("127.0.0.1"));
+ when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
+
+ ContainerBuilder.Builder specBuilder = newStartedSidecar();
+
+ verify(specBuilder).withPortBinding(4500, 4500, "127.0.0.1");
+ }
+
+ @Test
+ void anUnsetBindAddressResolvesToNoAddressAtAll() {
+ assertNull(FlociUiManager.resolveBindAddress(Optional.empty()));
+ }
+
+ @Test
+ void aConfiguredBindAddressIsTakenAsGiven() {
+ assertEquals("127.0.0.1", FlociUiManager.resolveBindAddress(Optional.of("127.0.0.1")));
+ assertEquals("0.0.0.0", FlociUiManager.resolveBindAddress(Optional.of("0.0.0.0")));
+ assertEquals("192.168.1.10", FlociUiManager.resolveBindAddress(Optional.of(" 192.168.1.10 ")));
+ }
+
+ @Test
+ void aBlankBindAddressFailsFastRatherThanSilentlyPickingOne() {
+ assertThrows(IllegalStateException.class,
+ () -> FlociUiManager.resolveBindAddress(Optional.of("")));
+ assertThrows(IllegalStateException.class,
+ () -> FlociUiManager.resolveBindAddress(Optional.of(" ")));
+ }
+
+ @Test
+ void aBlankBindAddressIsReportedInsteadOfStartingTheConsole() {
+ withUiConfig();
+ when(ui.enabled()).thenReturn(true);
+ when(ui.image()).thenReturn("floci/floci-ui:latest");
+ when(ui.bindAddress()).thenReturn(Optional.of(" "));
+ ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
+
+ FlociUiManager manager = new FlociUiManager(
+ mock(ContainerBuilder.class), lifecycleManager, logStreamer, containerDetector,
+ mock(CurrentContainerNetworkResolver.class), dockerHostResolver,
+ new LaunchedContainerAwsEnv(mock(ContainerReachableEndpoint.class)),
+ config, regionResolver, new ObjectMapper());
+ manager.ensureStarted();
+
+ assertFalse(manager.status().started());
+ assertTrue(manager.status().error().contains("floci.services.ui.bind-address"),
+ manager.status().error());
+ // Rejected before the image is resolved, so a console that is not going to be published
+ // is never pulled.
+ verify(lifecycleManager, times(0)).findByName(anyString());
+ }
+
+ /**
+ * Runs a full {@code ensureStarted()} against a stubbed builder and returns the spec builder,
+ * so a test can assert on how the container was asked to be published.
+ */
+ private ContainerBuilder.Builder newStartedSidecar() {
+ String image = "floci/floci-ui:latest";
+ ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
+ ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
+ ContainerSpec spec = new ContainerSpec(image);
+ when(containerBuilder.resolveImage(image)).thenReturn(image);
+ when(containerBuilder.newContainer(image)).thenReturn(specBuilder);
+ when(specBuilder.build()).thenReturn(spec);
+ when(lifecycleManager.imageLabels(image)).thenReturn(Optional.empty());
+ when(lifecycleManager.createAndStart(spec)).thenReturn(
+ new ContainerInfo("ui-container", Map.of(4500, new EndpointInfo("127.0.0.1", 4500))));
+
+ newManager(containerBuilder).ensureStarted();
+ return specBuilder;
+ }
+
/** Adopts a console that resolves to the built-in floci-ui profile. */
private FlociUiManager adoptSidecar(int port) {
return adoptSidecar(port, "floci/floci-ui:latest",
@@ -926,6 +1028,7 @@ class FlociUiManagerTest {
when(ui.statusReadyValue()).thenReturn(readyValue);
when(ui.statusUnavailableValue()).thenReturn(Optional.empty());
when(ui.endpoint()).thenReturn(Optional.of("http://custom:4566"));
+ when(ui.bindAddress()).thenReturn(Optional.empty());
ContainerBuilder containerBuilder = mock(ContainerBuilder.class);
when(containerBuilder.resolveImage(image)).thenReturn(image);