fix(ui): reconnect the UI sidecar without restarting Floci (#2718)

* fix(ui): reconnect the UI sidecar without restarting Floci

The floci-ui sidecar's FLOCI_ENDPOINT is baked in at container-create
time, but Floci's container IP changes on every restart. adoptExisting()
took over a surviving sidecar verbatim and never compared its endpoint
against the current one, so the sidecar kept polling the previous
instance's address indefinitely. The dashboard reported "Not connected"
with ECONNREFUSED and the only way out was to recreate the sidecar by
hand -- in practice, by restarting the emulator alongside it.

Detect that drift on adoption and recreate the sidecar instead, so
recovery stays entirely within the sidecar's own lifecycle and never
requires disturbing Floci.

Two supporting changes:

- status() re-arms ensureStarted() when the readiness probe fails.
  started was a one-way latch, so a sidecar that was removed, crashed,
  or turned out to be stale left Floci with no path back. The UI polls
  status continuously, which supplies the retry cadence.

- UiServiceConfig gains endpoint() and insecureSkipTlsVerify(). With TLS
  on, the derived endpoint is https://<floci-container-ip>:<port>, which
  the sidecar's Node/Bun proxy rejects: the self-signed certificate has
  no IP SAN for Floci's own container address, so verification fails with
  ERR_TLS_CERT_ALTNAME_INVALID even once the CA is trusted. Trusting the
  CA alone is therefore not enough. endpoint() lets an operator point the
  sidecar at http://<ip>:<port> -- the same server, via the port's
  HTTP/HTTPS protocol detection, with TLS left enabled -- and
  insecureSkipTlsVerify() covers the case where https must be kept. A
  blank or malformed override is a hard error, not a silent fall back to
  the derived endpoint.

* fix(ui): derive http for the sidecar when the host is a bare IP

With TLS enabled the endpoint handed to the UI sidecar was derived as
https://<floci's own container IP>:4566. That address can never appear in
the self-signed certificate: it is assigned at container-create time and
changes on every recreate, and the certificate is generated by a
ConfigSource that runs before CDI, with no Docker client to ask what the
address will be. Every connection therefore failed altname verification —
not chain trust, so mounting the CA would not have helped either — and the
dashboard sat at "Not connected" with no path back. Nothing in the manager
notices: the sidecar is running, so the re-arm added in 8f4fd900 correctly
declines to replace it, and the readiness probe only checks the sidecar's
own port, never the hop that is broken.

Floci's listener does HTTP/HTTPS protocol detection on the same port, so
http:// reaches it with TLS left enabled. That is one hop on an internal
Docker network, not the emulator, and it is the only scheme that works
unattended on the default configuration.

A named host such as host.docker.internal is a DNS SAN on the certificate
and keeps https. So does an IP literal when insecure-skip-tls-verify is
set, since the operator has said explicitly that they want TLS on this hop
and verification is no longer the obstacle.

isIpLiteral mirrors the iPAddress/dNSName distinction CertificateGenerator
already draws, kept local so this package does not depend on the ACM
service for one predicate.

* fix(ui): bracket an IPv6 host so the sidecar endpoint parses

The endpoint was built by concatenating host and port, which produces
http://fd00::2:4566 when the resolver hands back an IPv6 literal — the
port separator is indistinguishable from the address's own colons and no
client can parse it. DockerHostResolver reaches that case through
InetAddress.getLocalHost().getHostAddress() on an IPv6-only host.

Bracket the authority host. Names and IPv4 literals are unchanged.

* fix(ui): reset the async re-arm latch and stop swallowing pre-start failures

Local code review (review-local.ts) against FlociUiManager.java found two
HIGH-severity bugs before this branch reached a PR:

- ensureStartedAsync()'s kicked latch was only reset after a FAILED start,
  never after a successful one. status()'s self-recovery path sets
  started=false and calls ensureStartedAsync() when the sidecar is gone, but
  after any prior successful async start that CAS always failed silently --
  the documented "recovers without Floci being restarted" behavior could
  never actually fire.

- findByName() and replaceIfEndpointDrifted() ran before ensureStarted()'s
  try/catch. A container-runtime failure there (e.g. an unreachable Docker
  socket) escaped uncaught to a synchronous caller, or vanished into a
  discarded Future on the async path, leaving status() reporting
  {started:false, ready:false, error:null} with no diagnostic.

Reset kicked whenever status() re-arms a lost sidecar, and move the whole
body of ensureStarted() into the try/catch so every failure is routed
through lastError. A misconfigured endpoint override's own validation
message (set by replaceIfEndpointDrifted before it rethrows) is preserved
rather than overwritten by the generic describeStartFailure() message.

* fix(ui): validate endpoint override authority and capture fresh-start errors

- validateEndpointOverride() now rejects http:// URLs with no authority
  (e.g. "http://", "http:///path"), which previously passed the bare
  prefix check and were injected as an unreachable FLOCI_ENDPOINT.
- ensureStarted()'s IllegalStateException handler now fills lastError
  when nothing more specific was already recorded, so a fresh start
  (no existing sidecar to adopt) with a blank/malformed endpoint
  override surfaces the validation message instead of error=null.
- Document the new endpoint and insecure-skip-tls-verify settings in
  application.yml's floci.services.ui block.
This commit is contained in:
Sam Fakhreddine authored and GitHub committed 2026-08-30 15:05:47 -05:00
1 parent ff36141c19
commit 02f9754ac7
5 files changed
+707 -15

No files matched your search

@@ -5,21 +5,31 @@ import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.docker.ContainerBuilder;
import io.github.hectorvent.floci.core.common.docker.ContainerDetector;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.ContainerPresence;
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.EndpointInfo;
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.DockerHostResolver;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
import org.junit.jupiter.api.Test;
import java.net.BindException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
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.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class FlociUiManagerTest {
@@ -28,6 +38,17 @@ class FlociUiManagerTest {
private final DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class);
private final EmulatorConfig config = mock(EmulatorConfig.class);
private final EmulatorConfig.TlsConfig tls = mock(EmulatorConfig.TlsConfig.class);
private final EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
private final EmulatorConfig.UiServiceConfig ui = mock(EmulatorConfig.UiServiceConfig.class);
private final RegionResolver regionResolver = mock(RegionResolver.class);
/** Wires config.services().ui() with the defaults every UI test starts from. */
private void withUiConfig() {
when(config.services()).thenReturn(services);
when(services.ui()).thenReturn(ui);
when(ui.endpoint()).thenReturn(Optional.empty());
when(ui.insecureSkipTlsVerify()).thenReturn(false);
}
private FlociUiManager newManager() {
return new FlociUiManager(
@@ -38,11 +59,12 @@ class FlociUiManagerTest {
mock(CurrentContainerNetworkResolver.class),
dockerHostResolver,
config,
mock(RegionResolver.class));
regionResolver);
}
@Test
void containerizedUsesResolvedContainerIpNotHostDockerInternal() {
withUiConfig();
when(containerDetector.isRunningInContainer()).thenReturn(true);
when(config.hostname()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
@@ -55,6 +77,7 @@ class FlociUiManagerTest {
@Test
void explicitHostnameWinsWhenContainerized() {
withUiConfig();
when(containerDetector.isRunningInContainer()).thenReturn(true);
when(config.hostname()).thenReturn(Optional.of("floci"));
when(config.effectiveBaseUrl()).thenReturn("http://floci:4566");
@@ -64,6 +87,7 @@ class FlociUiManagerTest {
@Test
void onHostFallsBackToHostDockerInternal() {
withUiConfig();
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
@@ -73,6 +97,67 @@ class FlociUiManagerTest {
assertEquals("http://host.docker.internal:4566", newManager().resolveFlociEndpoint());
}
@Test
void tlsEnabledDerivesHttpForAnIpLiteralHost() {
// The self-signed certificate carries no IP SAN for the container address the resolver
// returns, so https:// to it can only ever fail altname verification. Port 4566 does
// HTTP/HTTPS protocol detection, so http:// reaches the same listener with TLS left on.
withUiConfig();
when(containerDetector.isRunningInContainer()).thenReturn(true);
when(config.hostname()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(true);
when(dockerHostResolver.resolve()).thenReturn("10.88.3.252");
assertEquals("http://10.88.3.252:4566", newManager().resolveFlociEndpoint());
}
@Test
void tlsEnabledKeepsHttpsForANamedHostTheCertificateCovers() {
// host.docker.internal is a DNS SAN on the self-signed certificate. Nothing to work
// around, so the downgrade must not reach it.
withUiConfig();
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(true);
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
assertEquals("https://host.docker.internal:4566", newManager().resolveFlociEndpoint());
}
@Test
void tlsEnabledKeepsHttpsForAnIpLiteralWhenVerificationIsSkipped() {
// An operator who opted into skipping verification has said they want TLS on this hop;
// the altname gap no longer blocks it, so honour the explicit choice.
withUiConfig();
when(ui.insecureSkipTlsVerify()).thenReturn(true);
when(containerDetector.isRunningInContainer()).thenReturn(true);
when(config.hostname()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(true);
when(dockerHostResolver.resolve()).thenReturn("10.88.3.252");
assertEquals("https://10.88.3.252:4566", newManager().resolveFlociEndpoint());
}
@Test
void anIpv6LiteralHostIsBracketedSoTheEndpointStaysAParseableUrl() {
// Without brackets the port colon is indistinguishable from the address colons and the
// sidecar gets a URL no client can parse.
withUiConfig();
when(containerDetector.isRunningInContainer()).thenReturn(true);
when(config.hostname()).thenReturn(Optional.empty());
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(false);
when(dockerHostResolver.resolve()).thenReturn("fd00::2");
assertEquals("http://[fd00::2]:4566", newManager().resolveFlociEndpoint());
}
@Test
void probeUsesSidecarContainerIpWhenContainerized() {
// In a container the published host port is not reachable via localhost; the
@@ -170,6 +255,7 @@ class FlociUiManagerTest {
@Test
void usesHttpsSchemeWhenTlsEnabled() {
withUiConfig();
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
@@ -178,4 +264,281 @@ class FlociUiManagerTest {
assertEquals("https://host.docker.internal:4566", newManager().resolveFlociEndpoint());
}
// --- endpoint drift: an adopted sidecar must not keep pointing at a dead Floci ---
@Test
void endpointDriftDetectedWhenAdoptedContainerPointsAtAnotherAddress() {
// The sidecar outlives Floci and is re-adopted after a restart, but its
// FLOCI_ENDPOINT was baked in at create time against the previous container IP.
List<String> staleEnv = List.of("PORT=4500", "FLOCI_ENDPOINT=http://10.88.4.98:4566");
assertTrue(FlociUiManager.endpointDrifted(staleEnv, "http://10.88.3.252:4566"),
"an adopted sidecar pointing at a previous Floci IP must be treated as drifted");
}
@Test
void noEndpointDriftWhenAdoptedContainerAlreadyMatches() {
List<String> env = List.of("PORT=4500", "FLOCI_ENDPOINT=http://10.88.3.252:4566");
assertFalse(FlociUiManager.endpointDrifted(env, "http://10.88.3.252:4566"),
"a sidecar already pointing at the current endpoint must be adopted as-is");
}
@Test
void endpointDriftDetectedWhenAdoptedContainerHasNoEndpointAtAll() {
// Missing is not "fine" — it is unknown, and adopting it would strand the UI.
assertTrue(FlociUiManager.endpointDrifted(List.of("PORT=4500"), "http://10.88.3.252:4566"));
assertTrue(FlociUiManager.endpointDrifted(null, "http://10.88.3.252:4566"));
}
@Test
void endpointDriftDetectedAcrossSchemeChange() {
// TLS toggled between runs: same host, different scheme, still unreachable.
List<String> env = List.of("FLOCI_ENDPOINT=http://10.88.3.252:4566");
assertTrue(FlociUiManager.endpointDrifted(env, "https://10.88.3.252:4566"));
}
@Test
void unreadableEnvironmentAdoptsRatherThanDestroyingAPossiblyHealthySidecar() {
// A failed inspect says nothing about the sidecar. Treating "I could not read it" as
// drift would let one transient container-runtime hiccup destroy a working sidecar.
assertFalse(FlociUiManager.shouldReplace(Optional.empty(), "http://10.88.3.252:4566"));
}
@Test
void readableEnvironmentStillReplacesOnDrift() {
Optional<List<String>> env = Optional.of(List.of("FLOCI_ENDPOINT=http://10.88.4.98:4566"));
assertTrue(FlociUiManager.shouldReplace(env, "http://10.88.3.252:4566"));
}
@Test
void readableMatchingEnvironmentIsAdopted() {
Optional<List<String>> env = Optional.of(List.of("FLOCI_ENDPOINT=http://10.88.3.252:4566"));
assertFalse(FlociUiManager.shouldReplace(env, "http://10.88.3.252:4566"));
}
// --- re-arming a lost sidecar (must not churn a healthy one) ---
@Test
void removedSidecarReArmsSoTheDashboardRecoversOnItsOwn() {
assertTrue(FlociUiManager.shouldReArm(ContainerPresence.ABSENT));
}
@Test
void exitedSidecarReArms() {
assertTrue(FlociUiManager.shouldReArm(ContainerPresence.STOPPED));
}
@Test
void bootingSidecarThatIsNotAnsweringYetIsLeftAlone() {
// The probe fails for the whole of a cold boot. Re-arming here would re-adopt the
// container on every poll — a log-stream reattach per poll, forever, for a sidecar
// that was about to come up on its own.
assertFalse(FlociUiManager.shouldReArm(ContainerPresence.RUNNING));
}
@Test
void unknownPresenceIsNotTreatedAsAMissingSidecar() {
assertFalse(FlociUiManager.shouldReArm(ContainerPresence.UNKNOWN));
}
// --- explicit endpoint override ---
@Test
void configuredEndpointOverrideWinsOverDerivation() {
withUiConfig();
when(ui.endpoint()).thenReturn(Optional.of("http://10.88.3.252:4566"));
when(containerDetector.isRunningInContainer()).thenReturn(true);
assertEquals("http://10.88.3.252:4566", newManager().resolveFlociEndpoint());
}
@Test
void blankEndpointOverrideFailsFastRatherThanSilentlyFallingBack() {
withUiConfig();
when(ui.endpoint()).thenReturn(Optional.of(" "));
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> newManager().resolveFlociEndpoint());
assertTrue(e.getMessage().contains("floci.services.ui.endpoint"), e.getMessage());
}
@Test
void malformedEndpointOverrideFailsFast() {
withUiConfig();
when(ui.endpoint()).thenReturn(Optional.of("10.88.3.252:4566"));
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> newManager().resolveFlociEndpoint());
assertTrue(e.getMessage().contains("http://"), e.getMessage());
}
// --- TLS trust for the sidecar's Node/Bun proxy ---
@Test
void insecureSkipTlsVerifyInjectsNodeTlsRejectUnauthorized() {
// Floci's self-signed cert has no IP SAN for its own container IP, so the sidecar
// fails ERR_TLS_CERT_ALTNAME_INVALID even with the CA trusted. Only disabling
// verification outright clears both the chain and the altname check.
withUiConfig();
when(ui.insecureSkipTlsVerify()).thenReturn(true);
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(true);
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
assertTrue(newManager().injectedEnv().contains("NODE_TLS_REJECT_UNAUTHORIZED=0"));
}
@Test
void tlsVerificationLeftIntactByDefault() {
withUiConfig();
when(containerDetector.isRunningInContainer()).thenReturn(false);
when(config.port()).thenReturn(4566);
when(config.tls()).thenReturn(tls);
when(tls.enabled()).thenReturn(true);
when(dockerHostResolver.resolve()).thenReturn("host.docker.internal");
when(regionResolver.getDefaultRegion()).thenReturn("us-east-1");
List<String> env = newManager().injectedEnv();
assertFalse(env.stream().anyMatch(v -> v.startsWith("NODE_TLS_REJECT_UNAUTHORIZED")),
"TLS verification must stay on unless explicitly opted out, was: " + env);
}
// --- re-arming after an async start must not get stuck ---
@Test
void statusReArmsAfterAnAsyncStartActuallyRestartsTheSidecar() {
// The sidecar's first start goes through ensureStartedAsync() (the interstitial-page
// path). Once it is gone and status() wants to bring it back, the second restart is
// also kicked through ensureStartedAsync() — that second kick must not be silently
// dropped just because the first one already ran to completion.
withUiConfig();
when(ui.enabled()).thenReturn(true);
when(ui.containerName()).thenReturn("floci-ui");
when(ui.endpoint()).thenReturn(Optional.of("http://custom:4566"));
when(containerDetector.isRunningInContainer()).thenReturn(false);
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
Container existing = mock(Container.class);
when(existing.getId()).thenReturn("abc123");
when(lifecycleManager.findByName("floci-ui")).thenReturn(Optional.of(existing));
when(lifecycleManager.containerEnv("abc123")).thenReturn(Optional.empty());
EndpointInfo endpoint = new EndpointInfo("localhost", 4500);
when(lifecycleManager.adopt("abc123", List.of(4500)))
.thenReturn(new ContainerLifecycleManager.ContainerInfo("abc123", Map.of(4500, endpoint)));
when(lifecycleManager.presenceOf("abc123")).thenReturn(ContainerPresence.ABSENT);
FlociUiManager manager = new FlociUiManager(
mock(ContainerBuilder.class),
lifecycleManager,
mock(ContainerLogStreamer.class),
containerDetector,
mock(CurrentContainerNetworkResolver.class),
dockerHostResolver,
config,
regionResolver);
manager.ensureStartedAsync();
await().atMost(2, TimeUnit.SECONDS)
.untilAsserted(() -> verify(lifecycleManager, times(1)).adopt("abc123", List.of(4500)));
// The sidecar is gone (ABSENT) and unreachable (nothing listens on localhost:4500), so
// status() must trigger a second async restart.
manager.status();
await().atMost(2, TimeUnit.SECONDS)
.untilAsserted(() -> verify(lifecycleManager, times(2)).adopt("abc123", List.of(4500)));
}
// --- a start that fails before the try block must not vanish silently ---
@Test
void ensureStartedRecordsTheFailureWhenTheContainerRuntimeIsUnreachable() {
// findByName runs before the try/catch in ensureStarted(). If the container runtime is
// unreachable it throws there, and the failure must still be captured for status() --
// not escape uncaught (synchronous callers) or vanish into a discarded Future (the
// ensureStartedAsync() path).
withUiConfig();
when(ui.enabled()).thenReturn(true);
when(ui.containerName()).thenReturn("floci-ui");
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.findByName("floci-ui"))
.thenThrow(new com.github.dockerjava.api.exception.DockerClientException(
"Cannot connect to the Docker daemon"));
FlociUiManager manager = new FlociUiManager(
mock(ContainerBuilder.class),
lifecycleManager,
mock(ContainerLogStreamer.class),
containerDetector,
mock(CurrentContainerNetworkResolver.class),
dockerHostResolver,
config,
regionResolver);
manager.ensureStarted();
assertEquals(false, manager.status().started());
assertTrue(manager.status().error() != null && manager.status().error().contains("Docker"),
"expected a captured error mentioning the Docker runtime, was: " + manager.status().error());
}
@Test
void endpointOverrideWithNoAuthorityFailsFast() {
// "http://" and "http:///path" both pass a bare prefix check but carry no host, so the
// sidecar would be started with an endpoint it can never connect to.
withUiConfig();
when(ui.endpoint()).thenReturn(Optional.of("http://"));
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> newManager().resolveFlociEndpoint());
assertTrue(e.getMessage().contains("http://"), e.getMessage());
}
@Test
void endpointOverrideWithPathOnlyAndNoAuthorityFailsFast() {
withUiConfig();
when(ui.endpoint()).thenReturn(Optional.of("http:///path"));
IllegalStateException e = assertThrows(IllegalStateException.class,
() -> newManager().resolveFlociEndpoint());
assertTrue(e.getMessage().contains("http:///path"), e.getMessage());
}
@Test
void ensureStartedRecordsTheFailureFromAFreshStartWithNoExistingSidecarToAdopt() {
// findByName finds nothing, so replaceIfEndpointDrifted (which records its own message)
// never runs -- injectedEnv()/resolveFlociEndpoint() throws IllegalStateException
// directly out of the try block on a blank/malformed override, and that catch must
// still populate lastError instead of leaving status() reporting error=null forever.
withUiConfig();
when(ui.enabled()).thenReturn(true);
when(ui.containerName()).thenReturn("floci-ui");
when(ui.endpoint()).thenReturn(Optional.of("not-a-url"));
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
when(lifecycleManager.findByName("floci-ui")).thenReturn(Optional.empty());
FlociUiManager manager = new FlociUiManager(
mock(ContainerBuilder.class, RETURNS_DEEP_STUBS),
lifecycleManager,
mock(ContainerLogStreamer.class),
containerDetector,
mock(CurrentContainerNetworkResolver.class),
dockerHostResolver,
config,
regionResolver);
manager.ensureStarted();
assertEquals(false, manager.status().started());
assertTrue(manager.status().error() != null && manager.status().error().contains("http://"),
"expected a captured error mentioning the required http:// scheme, was: "
+ manager.status().error());
}
}