Skip to content

armgit / floci

Public Imported from GitHub
0

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

feat(floci-core): resolve active Docker context when DOCKER_HOST is unset (#3197)

Matheus Oliveirae31590bba5be
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java b/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
index b65dfb8db1..e9f957f612 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducer.java
@@ -1,16 +1,35 @@
package io.github.hectorvent.floci.core.common.docker;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerClient;
+import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
+import com.github.dockerjava.core.SSLConfig;
+import com.github.dockerjava.core.util.CertificateUtils;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.X509Certificate;
import java.time.Duration;
+import java.util.Optional;
/**
* CDI producer for the DockerClient singleton bean.
@@ -22,11 +41,20 @@ public class DockerClientProducer {
/**
* Docker Desktop's well-known named pipe on native Windows. Unlike the unix-socket default,
- * this isn't reachable by simply bind-mounting a path — Windows has no equivalent of
+ * this isn't reachable by simply bind-mounting a path: Windows has no equivalent of
* {@code /var/run/docker.sock}, so a platform-specific fallback is required.
*/
private static final String WINDOWS_DEFAULT_DOCKER_HOST = "npipe:////./pipe/docker_engine";
+ /**
+ * The name Docker CLI uses for the built-in context that represents the platform default
+ * endpoint. It has no metadata file on disk, so encountering it means "no active context
+ * override; fall through to the hardcoded platform default".
+ */
+ private static final String DEFAULT_CONTEXT_NAME = "default";
+
+ private static final ObjectMapper DOCKER_CONTEXT_JSON_MAPPER = new ObjectMapper();
+
private final EmulatorConfig config;
@Inject
@@ -57,31 +85,278 @@ public class DockerClientProducer {
return normalized;
}
+ /**
+ * The Docker CLI's standard directory-listing for a context's TLS client material, relative
+ * to that context's TLS storage directory: {@code contexts/tls/<context-hash>/docker/}.
+ */
+ private static final String CONTEXT_TLS_ENDPOINT_DIR = "docker";
+
+ /**
+ * The host and, when the active context carries TLS material of its own, the directory
+ * holding it ({@code ca.pem}, {@code cert.pem}, {@code key.pem}), resolved together so both
+ * can be applied consistently to the {@link DefaultDockerClientConfig.Builder}. {@code
+ * skipTlsVerify} mirrors the context's own {@code SkipTLSVerify} setting: when true, the
+ * client certificate is still presented, but the daemon's server certificate is not
+ * validated against the context's CA, matching what the Docker CLI itself does for such
+ * a context.
+ */
+ record ResolvedDockerConnection(String host, Optional<Path> tlsCertPath, boolean skipTlsVerify) {
+ }
+
+ /**
+ * Resolves the effective Docker host to use when creating the client, reading the active
+ * Docker context from the current user's {@code ~/.docker} directory.
+ *
+ * @see #resolveEffectiveDockerHost(String, String, boolean, Path, String)
+ */
+ static String resolveEffectiveDockerHost(String configuredHost, String dockerHostEnv, boolean isWindows) {
+ return resolveEffectiveDockerHost(configuredHost, dockerHostEnv, isWindows, defaultDockerConfigDir(),
+ System.getenv("DOCKER_CONTEXT"));
+ }
+
+ /**
+ * @see #resolveEffectiveDockerHost(String, String, boolean, Path, String)
+ */
+ static String resolveEffectiveDockerHost(
+ String configuredHost, String dockerHostEnv, boolean isWindows, Path dockerConfigDir) {
+ return resolveEffectiveDockerHost(configuredHost, dockerHostEnv, isWindows, dockerConfigDir, null);
+ }
+
/**
* Resolves the effective Docker host to use when creating the client.
*
* Priority:
* 1. If {@code floci.docker.docker-host} is explicitly configured (non-default), use it.
* 2. Otherwise fall back to the standard {@code DOCKER_HOST} env var (normalized).
- * 3. Otherwise use the platform default: the unix socket on Linux/macOS, or Docker Desktop's
- * named pipe on native Windows — which has no {@code /var/run/docker.sock} equivalent, so
+ * 3. Otherwise resolve the active Docker context (e.g. Colima, OrbStack, Rancher Desktop,
+ * Podman) from {@code dockerConfigDir}, the way the Docker CLI and Testcontainers do, and
+ * use its endpoint if one is found. The active context is the standard {@code
+ * DOCKER_CONTEXT} env var when set and non-blank, otherwise {@code config.json}'s
+ * {@code currentContext} field.
+ * 4. Otherwise use the platform default: the unix socket on Linux/macOS, or Docker Desktop's
+ * named pipe on native Windows, which has no {@code /var/run/docker.sock} equivalent, so
* the unix-socket default is unreachable there unless a user overrides it manually.
*
* Both the configured value and the env var are normalized to ensure a valid URI scheme.
*/
- static String resolveEffectiveDockerHost(String configuredHost, String dockerHostEnv, boolean isWindows) {
+ static String resolveEffectiveDockerHost(
+ String configuredHost, String dockerHostEnv, boolean isWindows, Path dockerConfigDir,
+ String dockerContextEnv) {
+ return resolveDockerConnection(configuredHost, dockerHostEnv, isWindows, dockerConfigDir, dockerContextEnv)
+ .host();
+ }
+
+ /**
+ * Resolves the effective Docker host together with the active context's TLS material, when
+ * it has any. See {@link #resolveEffectiveDockerHost(String, String, boolean, Path, String)}
+ * for the host resolution priority; TLS material is only ever sourced from an active,
+ * non-default context, never from {@code floci.docker.docker-host} or {@code DOCKER_HOST}
+ * (both of those already flow through docker-java's own {@code DOCKER_TLS_VERIFY} /
+ * {@code DOCKER_CERT_PATH} env-var handling).
+ */
+ static ResolvedDockerConnection resolveDockerConnection(
+ String configuredHost, String dockerHostEnv, boolean isWindows, Path dockerConfigDir,
+ String dockerContextEnv) {
String normalizedEnvHost = normalizeDockerHost(dockerHostEnv);
boolean atDefault = "unix:///var/run/docker.sock".equals(configuredHost);
if (atDefault && normalizedEnvHost != null && !normalizedEnvHost.isBlank()) {
- return normalizedEnvHost;
+ return new ResolvedDockerConnection(normalizedEnvHost, Optional.empty(), false);
+ }
+ if (atDefault) {
+ DockerContextEndpoint contextEndpoint =
+ resolveActiveDockerContextEndpoint(dockerConfigDir, dockerContextEnv);
+ if (contextEndpoint != null) {
+ String normalizedContextHost = normalizeDockerHost(contextEndpoint.host());
+ LOG.infov("No DOCKER_HOST override set; using endpoint ''{0}'' from the active "
+ + "Docker context instead of the platform default.", normalizedContextHost);
+ return new ResolvedDockerConnection(normalizedContextHost, contextEndpoint.tlsCertPath(),
+ contextEndpoint.skipTlsVerify());
+ }
}
if (atDefault && isWindows) {
LOG.infov("Docker host is at its unix-socket default on Windows, which has no "
+ "/var/run/docker.sock equivalent; using named pipe ''{0}'' instead.",
WINDOWS_DEFAULT_DOCKER_HOST);
- return WINDOWS_DEFAULT_DOCKER_HOST;
+ return new ResolvedDockerConnection(WINDOWS_DEFAULT_DOCKER_HOST, Optional.empty(), false);
+ }
+ return new ResolvedDockerConnection(normalizeDockerHost(configuredHost), Optional.empty(), false);
+ }
+
+ private static Path defaultDockerConfigDir() {
+ return Paths.get(System.getProperty("user.home", ""), ".docker");
+ }
+
+ /**
+ * Resolves the Docker config directory to use for context discovery, matching the Docker
+ * CLI's own precedence: {@code floci.docker.docker-config-path}, when configured, wins
+ * outright; otherwise the standard {@code DOCKER_CONFIG} env var relocates the whole
+ * {@code ~/.docker} directory; otherwise the {@code ~/.docker} default applies.
+ */
+ static Path resolveDockerConfigDir(Optional<String> configuredDockerConfigPath, String dockerConfigEnv) {
+ if (configuredDockerConfigPath != null && configuredDockerConfigPath.isPresent()
+ && !configuredDockerConfigPath.get().isBlank()) {
+ return Paths.get(configuredDockerConfigPath.get());
+ }
+ if (dockerConfigEnv != null && !dockerConfigEnv.isBlank()) {
+ return Paths.get(dockerConfigEnv);
+ }
+ return defaultDockerConfigDir();
+ }
+
+ private record DockerContextEndpoint(String host, Optional<Path> tlsCertPath, boolean skipTlsVerify) {
+ }
+
+ /**
+ * Resolves the Docker endpoint of the active Docker context, mirroring how the Docker CLI
+ * and Testcontainers' {@code DockerClientProviderStrategy} do it: read the active context
+ * name (the built-in {@code "default"} context has no endpoint of its own, so it is treated
+ * the same as no context being configured at all), then read that context's {@code Host}
+ * endpoint from its metadata file under {@code contexts/meta/}, along with any TLS client
+ * material under {@code contexts/tls/}.
+ *
+ * @return the resolved endpoint, or {@code null} if no active non-default context is
+ * configured, its metadata is missing, or {@code config.json} is missing or malformed
+ */
+ private static DockerContextEndpoint resolveActiveDockerContextEndpoint(
+ Path dockerConfigDir, String dockerContextEnv) {
+ if (dockerConfigDir == null) {
+ return null;
+ }
+ String currentContext = resolveActiveDockerContextName(dockerConfigDir, dockerContextEnv);
+ if (currentContext == null || currentContext.isBlank() || DEFAULT_CONTEXT_NAME.equals(currentContext)) {
+ return null;
+ }
+ String host = readContextDockerHost(dockerConfigDir, currentContext);
+ if (host == null || host.isBlank()) {
+ return null;
+ }
+ return new DockerContextEndpoint(host, resolveActiveDockerContextTlsMaterial(dockerConfigDir, currentContext),
+ readContextSkipTlsVerify(dockerConfigDir, currentContext));
+ }
+
+ /**
+ * Resolves the name of the active Docker context, honoring the standard {@code DOCKER_CONTEXT}
+ * env var override before falling back to {@code config.json}'s {@code currentContext} field,
+ * matching the real Docker CLI's own precedence.
+ */
+ private static String resolveActiveDockerContextName(Path dockerConfigDir, String dockerContextEnv) {
+ if (dockerContextEnv != null && !dockerContextEnv.isBlank()) {
+ return dockerContextEnv;
+ }
+ return readCurrentContextName(dockerConfigDir.resolve("config.json"));
+ }
+
+ private static String readCurrentContextName(Path configJsonPath) {
+ if (!Files.isRegularFile(configJsonPath)) {
+ return null;
+ }
+ try {
+ JsonNode root = DOCKER_CONTEXT_JSON_MAPPER.readTree(configJsonPath.toFile());
+ if (root == null || root.isMissingNode()) {
+ return null;
+ }
+ JsonNode contextNode = root.get("currentContext");
+ return contextNode == null || contextNode.isNull() ? null : contextNode.asText();
+ } catch (IOException e) {
+ LOG.warnv("Could not read Docker config file ''{0}'' to resolve the active context: {1}",
+ configJsonPath, e.getMessage());
+ return null;
+ }
+ }
+
+ private static String readContextDockerHost(Path dockerConfigDir, String contextName) {
+ Path metaFile = dockerConfigDir.resolve("contexts").resolve("meta")
+ .resolve(sha256Hex(contextName)).resolve("meta.json");
+ if (!Files.isRegularFile(metaFile)) {
+ return null;
+ }
+ try {
+ JsonNode root = DOCKER_CONTEXT_JSON_MAPPER.readTree(metaFile.toFile());
+ if (root == null || root.isMissingNode()) {
+ return null;
+ }
+ JsonNode hostNode = root.path("Endpoints").path("docker").get("Host");
+ return hostNode == null || hostNode.isNull() ? null : hostNode.asText();
+ } catch (IOException e) {
+ LOG.warnv("Could not read Docker context metadata file ''{0}'' for context ''{1}'': {2}",
+ metaFile, contextName, e.getMessage());
+ return null;
+ }
+ }
+
+ /**
+ * Reads the context's own {@code SkipTLSVerify} setting, defaulting to {@code false} (the
+ * same default the Docker CLI itself uses) when the field, the metadata file, or the
+ * {@code Endpoints.docker} section is absent or malformed.
+ */
+ private static boolean readContextSkipTlsVerify(Path dockerConfigDir, String contextName) {
+ Path metaFile = dockerConfigDir.resolve("contexts").resolve("meta")
+ .resolve(sha256Hex(contextName)).resolve("meta.json");
+ if (!Files.isRegularFile(metaFile)) {
+ return false;
+ }
+ try {
+ JsonNode root = DOCKER_CONTEXT_JSON_MAPPER.readTree(metaFile.toFile());
+ if (root == null || root.isMissingNode()) {
+ return false;
+ }
+ return root.path("Endpoints").path("docker").path("SkipTLSVerify").asBoolean(false);
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Locates the active context's TLS client-certificate directory, mirroring how the Docker
+ * CLI stores it under {@code contexts/tls/<context-hash>/docker/} alongside the metadata
+ * directory. A context with no TLS material configured (a plaintext remote daemon, or a
+ * context pointing at a local unix socket or named pipe) simply has no such directory, and
+ * is left untouched here. Whether the context's own {@code SkipTLSVerify} setting is honored
+ * once material is found is resolved separately by {@link #readContextSkipTlsVerify}, since
+ * that flag is meaningless without TLS material to apply it to.
+ *
+ * <p>When the directory exists but is incomplete, that is treated as a broken TLS setup
+ * rather than silently connecting without a client certificate or falling back to plaintext.
+ *
+ * @return the TLS directory when all of {@code ca.pem}, {@code cert.pem} and {@code key.pem}
+ * are present, or {@link Optional#empty()} when the context has no TLS material at all
+ * @throws IllegalStateException if the TLS directory exists but is missing one of those files
+ */
+ private static Optional<Path> resolveActiveDockerContextTlsMaterial(Path dockerConfigDir, String contextName) {
+ Path tlsDir = dockerConfigDir.resolve("contexts").resolve("tls")
+ .resolve(sha256Hex(contextName)).resolve(CONTEXT_TLS_ENDPOINT_DIR);
+ if (!Files.isDirectory(tlsDir)) {
+ return Optional.empty();
+ }
+ boolean hasCa = Files.isRegularFile(tlsDir.resolve("ca.pem"));
+ boolean hasCert = Files.isRegularFile(tlsDir.resolve("cert.pem"));
+ boolean hasKey = Files.isRegularFile(tlsDir.resolve("key.pem"));
+ if (hasCa && hasCert && hasKey) {
+ LOG.infov("Docker context ''{0}'' has TLS material at ''{1}''; using it for the "
+ + "Docker client connection.", contextName, tlsDir);
+ return Optional.of(tlsDir);
+ }
+ if (hasCa || hasCert || hasKey) {
+ throw new IllegalStateException(String.format(
+ "Docker context '%s' has an incomplete TLS material directory at '%s' "
+ + "(expected ca.pem, cert.pem and key.pem); refusing to silently fall back "
+ + "to an unauthenticated or unverified connection.", contextName, tlsDir));
+ }
+ return Optional.empty();
+ }
+
+ private static String sha256Hex(String value) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ byte[] hash = digest.digest(value.getBytes(StandardCharsets.UTF_8));
+ StringBuilder hex = new StringBuilder(hash.length * 2);
+ for (byte b : hash) {
+ hex.append(String.format("%02x", b));
+ }
+ return hex.toString();
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 algorithm not available", e);
}
- return normalizeDockerHost(configuredHost);
}
private static DefaultDockerClientConfig.Builder createDockerConfigBuilder() {
@@ -106,8 +381,12 @@ public class DockerClientProducer {
@Produces
@ApplicationScoped
public DockerClient dockerClient() {
- String dockerHost = resolveEffectiveDockerHost(
- config.docker().dockerHost(), System.getenv("DOCKER_HOST"), isWindows());
+ Path dockerConfigDir =
+ resolveDockerConfigDir(config.docker().dockerConfigPath(), System.getenv("DOCKER_CONFIG"));
+ ResolvedDockerConnection connection = resolveDockerConnection(
+ config.docker().dockerHost(), System.getenv("DOCKER_HOST"), isWindows(),
+ dockerConfigDir, System.getenv("DOCKER_CONTEXT"));
+ String dockerHost = connection.host();
LOG.infov("Creating DockerClient for host: {0}", dockerHost);
// createDefaultConfigBuilder() reads DOCKER_HOST directly from System.getenv() and passes
@@ -121,6 +400,18 @@ public class DockerClientProducer {
LOG.infov("Using Docker config path: {0}", path);
builder.withDockerConfig(path);
});
+ connection.tlsCertPath().ifPresent(path -> {
+ if (connection.skipTlsVerify()) {
+ LOG.infov("Using TLS material from the active Docker context at: {0}, with server "
+ + "certificate verification skipped per the context's SkipTLSVerify setting.",
+ path);
+ builder.withCustomSslConfig(new SkipVerifySslConfig(path.toString()));
+ } else {
+ LOG.infov("Using TLS material from the active Docker context at: {0}", path);
+ builder.withDockerTlsVerify(true);
+ builder.withDockerCertPath(path.toString());
+ }
+ });
DefaultDockerClientConfig clientConfig = builder.build();
ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
@@ -132,4 +423,53 @@ public class DockerClientProducer {
return DockerClientImpl.getInstance(clientConfig, httpClient);
}
+
+ /**
+ * Presents the context's client certificate for mutual TLS, like {@code
+ * LocalDirectorySSLConfig}, but trusts the daemon's server certificate unconditionally
+ * instead of validating it against the context's CA. docker-java's own {@code
+ * LocalDirectorySSLConfig} always validates the server certificate, with no built-in way to
+ * skip that step, so a context with {@code SkipTLSVerify: true} needs a dedicated {@link
+ * SSLConfig} to reproduce the Docker CLI's own behavior for it.
+ */
+ private static final class SkipVerifySslConfig implements SSLConfig, Serializable {
+
+ private static final long serialVersionUID = 1L;
+ private static final X509TrustManager TRUST_ALL = new X509TrustManager() {
+ @Override
+ public void checkClientTrusted(X509Certificate[] chain, String authType) {
+ }
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] chain, String authType) {
+ }
+
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return new X509Certificate[0];
+ }
+ };
+
+ private final String dockerCertPath;
+
+ SkipVerifySslConfig(String dockerCertPath) {
+ this.dockerCertPath = dockerCertPath;
+ }
+
+ @Override
+ public SSLContext getSSLContext() {
+ try {
+ String keyPem = Files.readString(Path.of(dockerCertPath, "key.pem"));
+ String certPem = Files.readString(Path.of(dockerCertPath, "cert.pem"));
+ KeyManagerFactory keyManagerFactory =
+ KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ keyManagerFactory.init(CertificateUtils.createKeyStore(keyPem, certPem), "docker".toCharArray());
+ SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
+ sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] {TRUST_ALL}, null);
+ return sslContext;
+ } catch (Exception e) {
+ throw new DockerClientException(e.getMessage(), e);
+ }
+ }
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducerTest.java
index cd40a1088b..9d7e55af07 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/docker/DockerClientProducerTest.java
@@ -1,10 +1,18 @@
package io.github.hectorvent.floci.core.common.docker;
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.MethodSource;
+import java.io.IOException;
import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Optional;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
@@ -19,7 +27,7 @@ import static org.junit.jupiter.api.Assertions.*;
* bare host:port values so they become valid URIs.
*
* EXPECTED OUTCOME on unfixed code: Test FAILS (compilation failure or
- * assertion failure — normalizeDockerHost method does not exist yet,
+ * assertion failure, normalizeDockerHost method does not exist yet,
* confirming the missing normalization logic).
*/
class DockerClientProducerTest {
@@ -43,7 +51,7 @@ class DockerClientProducerTest {
}
/**
- * Bug Condition — Bare host:port values are normalized with tcp:// prefix.
+ * Bug Condition: Bare host:port values are normalized with tcp:// prefix.
*
* For each bare host:port input, normalizeDockerHost should return "tcp://" + input,
* and the result should be a valid URI (URI.create does not throw).
@@ -56,7 +64,7 @@ class DockerClientProducerTest {
assertEquals("tcp://" + input, result,
"Bare host:port '" + input + "' should be normalized with tcp:// prefix");
- // The normalized value must be a valid URI — URI.create must not throw
+ // The normalized value must be a valid URI: URI.create must not throw
URI uri = assertDoesNotThrow(() -> URI.create(result),
"Normalized value '" + result + "' should be a valid URI");
assertNotNull(uri.getScheme(), "Normalized URI should have a scheme");
@@ -77,7 +85,7 @@ class DockerClientProducerTest {
}
/**
- * Preservation — Schemed URIs are passed through unchanged.
+ * Preservation: Schemed URIs are passed through unchanged.
*
* For any Docker host value that already contains a recognized URI scheme
* (tcp://, unix://, npipe://), normalizeDockerHost should return the value
@@ -100,7 +108,7 @@ class DockerClientProducerTest {
/**
* Edge case: null input handling.
*
- * normalizeDockerHost should handle null gracefully — either return null
+ * normalizeDockerHost should handle null gracefully: either return null
* or throw a clear exception, but not produce an invalid result.
*/
@Test
@@ -112,7 +120,7 @@ class DockerClientProducerTest {
/**
* Edge case: empty string input handling.
*
- * normalizeDockerHost should handle empty string gracefully — return it
+ * normalizeDockerHost should handle empty string gracefully: return it
* unchanged since there is no meaningful host to normalize.
*/
@Test
@@ -131,7 +139,7 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_dockerHostEnvBareHostPort_usesNormalizedEnv() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "unix:///var/run/docker.sock", "10.37.124.101:2375", false);
+ "unix:///var/run/docker.sock", "10.37.124.101:2375", false, null);
assertEquals("tcp://10.37.124.101:2375", result,
"Bare DOCKER_HOST env var should be normalized and used when config is at its default");
}
@@ -143,7 +151,7 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_dockerHostEnvTcpUri_usedDirectly() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "unix:///var/run/docker.sock", "tcp://10.37.124.101:2375", false);
+ "unix:///var/run/docker.sock", "tcp://10.37.124.101:2375", false, null);
assertEquals("tcp://10.37.124.101:2375", result,
"Valid tcp:// DOCKER_HOST env var should be used when config is at its default");
}
@@ -155,7 +163,7 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_explicitFlociConfig_takesPriorityOverEnv() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "tcp://custom-daemon:2376", "10.37.124.101:2375", false);
+ "tcp://custom-daemon:2376", "10.37.124.101:2375", false, null);
assertEquals("tcp://custom-daemon:2376", result,
"Explicit floci.docker.docker-host should take priority over DOCKER_HOST env var");
}
@@ -167,7 +175,7 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_noEnvVar_nonWindows_usesUnixSocketDefault() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "unix:///var/run/docker.sock", null, false);
+ "unix:///var/run/docker.sock", null, false, null);
assertEquals("unix:///var/run/docker.sock", result,
"Default unix socket should be used on non-Windows platforms when DOCKER_HOST is not set");
}
@@ -179,13 +187,13 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_blankEnvVar_nonWindows_usesUnixSocketDefault() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "unix:///var/run/docker.sock", "", false);
+ "unix:///var/run/docker.sock", "", false, null);
assertEquals("unix:///var/run/docker.sock", result,
"Default unix socket should be used on non-Windows platforms when DOCKER_HOST is blank");
}
/**
- * Bug: on native Windows, /var/run/docker.sock has no equivalent — Docker Desktop exposes
+ * Bug: on native Windows, /var/run/docker.sock has no equivalent. Docker Desktop exposes
* its API via a named pipe instead. When floci.docker.docker-host is still at its unix-socket
* default and no DOCKER_HOST override is set, Windows must fall back to the named pipe rather
* than the unreachable unix-socket path (issue floci-io/floci#2006).
@@ -193,7 +201,7 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_noEnvVar_windows_usesNamedPipeDefault() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "unix:///var/run/docker.sock", null, true);
+ "unix:///var/run/docker.sock", null, true, null);
assertEquals("npipe:////./pipe/docker_engine", result,
"Windows should fall back to the named pipe when the unix-socket default is unreachable");
}
@@ -204,7 +212,7 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_blankEnvVar_windows_usesNamedPipeDefault() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "unix:///var/run/docker.sock", "", true);
+ "unix:///var/run/docker.sock", "", true, null);
assertEquals("npipe:////./pipe/docker_engine", result,
"Windows should fall back to the named pipe when DOCKER_HOST is blank");
}
@@ -215,7 +223,7 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_envVarSet_windows_usesEnvNotNamedPipe() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "unix:///var/run/docker.sock", "tcp://10.0.0.5:2375", true);
+ "unix:///var/run/docker.sock", "tcp://10.0.0.5:2375", true, null);
assertEquals("tcp://10.0.0.5:2375", result,
"An explicit DOCKER_HOST should take priority over the Windows named-pipe fallback");
}
@@ -227,8 +235,379 @@ class DockerClientProducerTest {
@Test
void resolveEffectiveDockerHost_explicitFlociConfig_windows_takesPriorityOverNamedPipe() {
String result = DockerClientProducer.resolveEffectiveDockerHost(
- "tcp://custom-daemon:2376", null, true);
+ "tcp://custom-daemon:2376", null, true, null);
assertEquals("tcp://custom-daemon:2376", result,
"An explicitly-configured docker-host should take priority over the Windows named-pipe fallback");
}
+
+ private static void writeContextFixture(Path dockerConfigDir, String contextName, String host)
+ throws IOException {
+ writeContextFixture(dockerConfigDir, contextName, host, false);
+ }
+
+ private static void writeContextFixture(
+ Path dockerConfigDir, String contextName, String host, boolean skipTlsVerify) throws IOException {
+ Files.createDirectories(dockerConfigDir);
+ Files.writeString(dockerConfigDir.resolve("config.json"),
+ "{\"currentContext\":\"" + contextName + "\"}");
+ Path metaDir = dockerConfigDir.resolve("contexts").resolve("meta").resolve(sha256Hex(contextName));
+ Files.createDirectories(metaDir);
+ Files.writeString(metaDir.resolve("meta.json"),
+ "{\"Name\":\"" + contextName + "\",\"Metadata\":{},"
+ + "\"Endpoints\":{\"docker\":{\"Host\":\"" + host + "\",\"SkipTLSVerify\":"
+ + skipTlsVerify + "}}}");
+ }
+
+ private static String sha256Hex(String value) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ byte[] hash = digest.digest(value.getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ StringBuilder hex = new StringBuilder(hash.length * 2);
+ for (byte b : hash) {
+ hex.append(String.format("%02x", b));
+ }
+ return hex.toString();
+ } catch (NoSuchAlgorithmException e) {
+ throw new IllegalStateException("SHA-256 algorithm not available", e);
+ }
+ }
+
+ /**
+ * When floci.docker.docker-host is at its default and DOCKER_HOST is unset, the endpoint of
+ * the active Docker context (e.g. Colima) is resolved from ~/.docker/config.json and its
+ * context metadata file, and used instead of the hardcoded unix-socket default.
+ */
+ @Test
+ void resolveEffectiveDockerHost_activeNonDefaultContext_usesContextEndpoint(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "colima", "unix:///Users/dev/.colima/default/docker.sock");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir);
+
+ assertEquals("unix:///Users/dev/.colima/default/docker.sock", result,
+ "The active Docker context's endpoint should be used when no explicit override is set");
+ }
+
+ /**
+ * An explicitly-configured floci.docker.docker-host still takes priority over the active
+ * Docker context's endpoint.
+ */
+ @Test
+ void resolveEffectiveDockerHost_explicitFlociConfig_takesPriorityOverContext(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "colima", "unix:///Users/dev/.colima/default/docker.sock");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "tcp://custom-daemon:2376", null, false, tempDir);
+
+ assertEquals("tcp://custom-daemon:2376", result,
+ "Explicit floci.docker.docker-host should take priority over the active Docker context");
+ }
+
+ /**
+ * An explicit DOCKER_HOST env var still takes priority over the active Docker context's
+ * endpoint.
+ */
+ @Test
+ void resolveEffectiveDockerHost_dockerHostEnv_takesPriorityOverContext(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "colima", "unix:///Users/dev/.colima/default/docker.sock");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", "tcp://10.0.0.5:2375", false, tempDir);
+
+ assertEquals("tcp://10.0.0.5:2375", result,
+ "DOCKER_HOST env var should take priority over the active Docker context");
+ }
+
+ /**
+ * When the active context is the built-in "default" context (no metadata file on disk), it
+ * carries no endpoint of its own, so resolution falls through to the platform default.
+ */
+ @Test
+ void resolveEffectiveDockerHost_defaultContext_fallsThroughToPlatformDefault(@TempDir Path tempDir)
+ throws IOException {
+ Files.writeString(tempDir.resolve("config.json"), "{\"currentContext\":\"default\"}");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir);
+
+ assertEquals("unix:///var/run/docker.sock", result,
+ "The built-in default context should fall through to the platform default");
+ }
+
+ /**
+ * When ~/.docker/config.json does not exist at all, resolution falls through gracefully to
+ * the platform default rather than throwing.
+ */
+ @Test
+ void resolveEffectiveDockerHost_missingDockerConfig_fallsThroughToPlatformDefault(@TempDir Path tempDir) {
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir.resolve("does-not-exist"));
+
+ assertEquals("unix:///var/run/docker.sock", result,
+ "A missing Docker config directory should fall through to the platform default");
+ }
+
+ /**
+ * When ~/.docker/config.json is malformed JSON, resolution falls through gracefully to the
+ * platform default rather than throwing.
+ */
+ @Test
+ void resolveEffectiveDockerHost_malformedDockerConfig_fallsThroughToPlatformDefault(@TempDir Path tempDir)
+ throws IOException {
+ Files.writeString(tempDir.resolve("config.json"), "{not valid json");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir);
+
+ assertEquals("unix:///var/run/docker.sock", result,
+ "A malformed Docker config file should fall through to the platform default");
+ }
+
+ /**
+ * When the active context is set but its metadata file is missing from disk, resolution
+ * falls through gracefully to the platform default rather than throwing.
+ */
+ @Test
+ void resolveEffectiveDockerHost_missingContextMetadata_fallsThroughToPlatformDefault(@TempDir Path tempDir)
+ throws IOException {
+ Files.writeString(tempDir.resolve("config.json"), "{\"currentContext\":\"orbstack\"}");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir);
+
+ assertEquals("unix:///var/run/docker.sock", result,
+ "A missing context metadata file should fall through to the platform default");
+ }
+
+ /**
+ * On Windows, the active Docker context's endpoint still takes priority over the named-pipe
+ * default.
+ */
+ @Test
+ void resolveEffectiveDockerHost_activeContext_windows_takesPriorityOverNamedPipe(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "rancher-desktop", "npipe:////./pipe/rancher_desktop");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, true, tempDir);
+
+ assertEquals("npipe:////./pipe/rancher_desktop", result,
+ "The active Docker context's endpoint should take priority over the Windows named-pipe default");
+ }
+
+ /**
+ * An empty {@code config.json} makes Jackson's {@code readTree} return {@code null} rather
+ * than throwing. Resolution must treat that the same as "no context configured" instead of
+ * dereferencing the null root, which previously crashed emulator startup with an NPE.
+ */
+ @Test
+ void resolveEffectiveDockerHost_emptyConfigJson_fallsThroughToPlatformDefault(@TempDir Path tempDir)
+ throws IOException {
+ Files.writeString(tempDir.resolve("config.json"), "");
+
+ String result = assertDoesNotThrow(() -> DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir));
+
+ assertEquals("unix:///var/run/docker.sock", result,
+ "An empty config.json should fall through to the platform default rather than crashing");
+ }
+
+ /**
+ * Same as above, but with a whitespace-only file rather than a fully empty one.
+ */
+ @Test
+ void resolveEffectiveDockerHost_whitespaceOnlyConfigJson_fallsThroughToPlatformDefault(@TempDir Path tempDir)
+ throws IOException {
+ Files.writeString(tempDir.resolve("config.json"), " \n\t ");
+
+ String result = assertDoesNotThrow(() -> DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir));
+
+ assertEquals("unix:///var/run/docker.sock", result,
+ "A whitespace-only config.json should fall through to the platform default rather than crashing");
+ }
+
+ /**
+ * When {@code floci.docker.docker-config-path} is explicitly configured, it wins outright,
+ * even over a {@code DOCKER_CONFIG} env var pointing elsewhere.
+ */
+ @Test
+ void resolveDockerConfigDir_explicitConfigProperty_takesPriorityOverDockerConfigEnv(@TempDir Path tempDir) {
+ Path configuredDir = tempDir.resolve("explicit-config");
+ Path envDir = tempDir.resolve("env-config");
+
+ Path result = DockerClientProducer.resolveDockerConfigDir(
+ Optional.of(configuredDir.toString()), envDir.toString());
+
+ assertEquals(configuredDir, result,
+ "An explicitly configured docker-config-path should take priority over DOCKER_CONFIG");
+ }
+
+ /**
+ * When no explicit config property is set, the standard {@code DOCKER_CONFIG} env var
+ * relocates the whole Docker config directory, matching the Docker CLI's own behavior.
+ */
+ @Test
+ void resolveDockerConfigDir_dockerConfigEnv_usedWhenNoExplicitConfig(@TempDir Path tempDir) {
+ Path envDir = tempDir.resolve("env-config");
+
+ Path result = DockerClientProducer.resolveDockerConfigDir(Optional.empty(), envDir.toString());
+
+ assertEquals(envDir, result, "DOCKER_CONFIG should be honored when no explicit override is configured");
+ }
+
+ /**
+ * When neither the explicit config property nor DOCKER_CONFIG is set, the standard
+ * {@code ~/.docker} default applies.
+ */
+ @Test
+ void resolveDockerConfigDir_noOverrides_usesDockerHomeDefault() {
+ Path result = DockerClientProducer.resolveDockerConfigDir(Optional.empty(), null);
+
+ assertEquals(Paths.get(System.getProperty("user.home", ""), ".docker"), result,
+ "With no overrides, the default ~/.docker directory should be used");
+ }
+
+ /**
+ * The standard {@code DOCKER_CONTEXT} env var must take priority over {@code config.json}'s
+ * {@code currentContext} field, matching real Docker CLI behavior.
+ */
+ @Test
+ void resolveEffectiveDockerHost_dockerContextEnv_overridesConfigJsonCurrentContext(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "colima", "unix:///Users/dev/.colima/default/docker.sock");
+ writeContextFixture(tempDir, "orbstack", "unix:///Users/dev/.orbstack/run/docker.sock");
+ Files.writeString(tempDir.resolve("config.json"), "{\"currentContext\":\"colima\"}");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir, "orbstack");
+
+ assertEquals("unix:///Users/dev/.orbstack/run/docker.sock", result,
+ "DOCKER_CONTEXT should override config.json's currentContext");
+ }
+
+ /**
+ * A blank {@code DOCKER_CONTEXT} env var is treated as unset, falling back to
+ * {@code config.json}'s {@code currentContext} field.
+ */
+ @Test
+ void resolveEffectiveDockerHost_blankDockerContextEnv_fallsBackToConfigJson(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "colima", "unix:///Users/dev/.colima/default/docker.sock");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", null, false, tempDir, "");
+
+ assertEquals("unix:///Users/dev/.colima/default/docker.sock", result,
+ "A blank DOCKER_CONTEXT should fall back to config.json's currentContext");
+ }
+
+ /**
+ * An explicit DOCKER_HOST env var still takes priority over DOCKER_CONTEXT.
+ */
+ @Test
+ void resolveEffectiveDockerHost_dockerHostEnv_takesPriorityOverDockerContextEnv(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "orbstack", "unix:///Users/dev/.orbstack/run/docker.sock");
+
+ String result = DockerClientProducer.resolveEffectiveDockerHost(
+ "unix:///var/run/docker.sock", "tcp://10.0.0.5:2375", false, tempDir, "orbstack");
+
+ assertEquals("tcp://10.0.0.5:2375", result,
+ "DOCKER_HOST env var should take priority over DOCKER_CONTEXT");
+ }
+
+ private static void writeContextTlsFixture(
+ Path dockerConfigDir, String contextName, boolean withCa, boolean withCert, boolean withKey)
+ throws IOException {
+ Path tlsDir = dockerConfigDir.resolve("contexts").resolve("tls")
+ .resolve(sha256Hex(contextName)).resolve("docker");
+ Files.createDirectories(tlsDir);
+ if (withCa) {
+ Files.writeString(tlsDir.resolve("ca.pem"), "-----BEGIN CERTIFICATE-----\nca\n-----END CERTIFICATE-----");
+ }
+ if (withCert) {
+ Files.writeString(tlsDir.resolve("cert.pem"),
+ "-----BEGIN CERTIFICATE-----\ncert\n-----END CERTIFICATE-----");
+ }
+ if (withKey) {
+ Files.writeString(tlsDir.resolve("key.pem"),
+ "-----BEGIN PRIVATE KEY-----\nkey\n-----END PRIVATE KEY-----");
+ }
+ }
+
+ /**
+ * When the active context's TLS storage directory holds a complete set of client-certificate
+ * material (ca.pem, cert.pem, key.pem, exactly as the Docker CLI lays it out), it is
+ * surfaced alongside the resolved host so it can be applied to the Docker client.
+ */
+ @Test
+ void resolveDockerConnection_contextWithCompleteTlsMaterial_returnsTlsCertPath(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "remote-tls", "tcp://remote-docker:2376");
+ writeContextTlsFixture(tempDir, "remote-tls", true, true, true);
+
+ DockerClientProducer.ResolvedDockerConnection result = DockerClientProducer.resolveDockerConnection(
+ "unix:///var/run/docker.sock", null, false, tempDir, null);
+
+ assertEquals("tcp://remote-docker:2376", result.host());
+ assertTrue(result.tlsCertPath().isPresent(), "TLS material should be surfaced when present");
+ assertEquals(tempDir.resolve("contexts").resolve("tls").resolve(sha256Hex("remote-tls")).resolve("docker"),
+ result.tlsCertPath().get());
+ assertFalse(result.skipTlsVerify(), "SkipTLSVerify defaults to false and should be reported as such");
+ }
+
+ /**
+ * A context with {@code SkipTLSVerify: true} must surface that flag alongside its TLS
+ * material, so the client certificate is presented but the daemon's server certificate is
+ * not validated, matching the Docker CLI's own behavior for such a context.
+ */
+ @Test
+ void resolveDockerConnection_contextWithSkipTlsVerify_reportsSkipTlsVerifyTrue(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "remote-tls", "tcp://remote-docker:2376", true);
+ writeContextTlsFixture(tempDir, "remote-tls", true, true, true);
+
+ DockerClientProducer.ResolvedDockerConnection result = DockerClientProducer.resolveDockerConnection(
+ "unix:///var/run/docker.sock", null, false, tempDir, null);
+
+ assertTrue(result.tlsCertPath().isPresent(), "TLS material should still be surfaced");
+ assertTrue(result.skipTlsVerify(), "SkipTLSVerify: true in the context metadata should be honored");
+ }
+
+ /**
+ * A context with no TLS storage directory at all (the common case: a plaintext remote
+ * daemon, or a context pointing at a local unix socket / named pipe) resolves without any
+ * TLS material, and does not fail.
+ */
+ @Test
+ void resolveDockerConnection_contextWithoutTlsMaterial_returnsEmptyTlsCertPath(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "colima", "unix:///Users/dev/.colima/default/docker.sock");
+
+ DockerClientProducer.ResolvedDockerConnection result = DockerClientProducer.resolveDockerConnection(
+ "unix:///var/run/docker.sock", null, false, tempDir, null);
+
+ assertEquals("unix:///Users/dev/.colima/default/docker.sock", result.host());
+ assertTrue(result.tlsCertPath().isEmpty(), "A context without TLS material should not report any");
+ }
+
+ /**
+ * A context whose TLS storage directory exists but is missing one of the required files
+ * indicates a broken TLS setup. Rather than silently connecting without a client certificate
+ * (or falling back to plaintext), resolution fails loudly.
+ */
+ @Test
+ void resolveDockerConnection_contextWithIncompleteTlsMaterial_throwsIllegalStateException(@TempDir Path tempDir)
+ throws IOException {
+ writeContextFixture(tempDir, "remote-tls", "tcp://remote-docker:2376");
+ writeContextTlsFixture(tempDir, "remote-tls", true, false, false);
+
+ assertThrows(IllegalStateException.class, () -> DockerClientProducer.resolveDockerConnection(
+ "unix:///var/run/docker.sock", null, false, tempDir, null),
+ "An incomplete TLS material directory should fail loudly rather than connect insecurely");
+ }
}