From 004ceb7b09679d72dd4c1323ffc2c2fb99d8aef1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:57:00 +0700 Subject: [PATCH] feat(docker): reach a daemon named by an ssh:// Docker host through an SSH tunnel (#9531) --- docs/configuration/docker.md | 11 + docs/getting-started/installation.md | 10 +- .../io/floci/aws/config/EmulatorConfig.java | 9 + .../docker/ContainerLifecycleManager.java | 21 +- .../common/docker/DockerClientProducer.java | 69 ++- .../common/docker/FlociDockerHttpClient.java | 5 +- .../core/common/docker/SshDockerEndpoint.java | 189 ++++++++ .../core/common/docker/SshStdioSocket.java | 434 ++++++++++++++++++ src/main/resources/application.yml | 6 + .../aws/config/ApplicationDefaultsTest.java | 12 + .../docker/DockerClientProducerTest.java | 93 +++- .../common/docker/SshDockerEndpointTest.java | 167 +++++++ .../common/docker/SshStdioSocketTest.java | 250 ++++++++++ 13 files changed, 1242 insertions(+), 34 deletions(-) create mode 100644 src/main/java/io/floci/aws/core/common/docker/SshDockerEndpoint.java create mode 100644 src/main/java/io/floci/aws/core/common/docker/SshStdioSocket.java create mode 100644 src/test/java/io/floci/aws/core/common/docker/SshDockerEndpointTest.java create mode 100644 src/test/java/io/floci/aws/core/common/docker/SshStdioSocketTest.java diff --git a/docs/configuration/docker.md b/docs/configuration/docker.md index eac660a19b..e2f040f793 100644 --- a/docs/configuration/docker.md +++ b/docs/configuration/docker.md @@ -16,6 +16,16 @@ floci: Environment variable: `FLOCI_DOCKER_DOCKER_HOST` +An `ssh://` Docker host (from `docker-host`, `DOCKER_HOST`, or the active Docker context) is opt-in and refused at startup by default, because each Docker connection runs an `ssh` process (`ssh docker system dial-stdio`). Set `allow-ssh-host` to `true` to allow it: + +```yaml +floci: + docker: + allow-ssh-host: true +``` + +Environment variable: `FLOCI_DOCKER_ALLOW_SSH_HOST` + When running Floci inside Docker Compose, mount the host socket: ```yaml @@ -454,6 +464,7 @@ caller keeps its existing failure handling after retries are exhausted. | Environment variable | Default | Description | |---|---|---| | `FLOCI_DOCKER_DOCKER_HOST` | `unix:///var/run/docker.sock` | Docker daemon socket | +| `FLOCI_DOCKER_ALLOW_SSH_HOST` | `false` | Allow an `ssh://` Docker host (off by default because each Docker connection runs an `ssh` process; refused at startup until enabled) | | `FLOCI_DOCKER_DOCKER_CONFIG_PATH` | _(unset)_ | Path to directory containing Docker's `config.json` | | `FLOCI_DOCKER_MAX_CONNECTIONS` | `1024` | Connection pool size for Floci's short Docker calls | | `FLOCI_DOCKER_BREAKER_FAILURE_THRESHOLD` | `3` | Docker call attempts in a row (each retry counts) that fail before the daemon answers, after which a failed ping makes every Docker call fail at once until the daemon answers again; `0` turns this off | diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 0cbd7546f4..c0271c19da 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -111,7 +111,15 @@ gh attestation verify "$ASSET" --repo floci-io/floci registry, CodeArtifact, Verified Permissions). Floci logs one warning at startup naming the affected services when Docker is unreachable. With Docker, the binary finds the daemon the way the Docker CLI does: `DOCKER_HOST`, then the active Docker context (Docker Desktop, - OrbStack, Colima, Podman), then the default socket. + OrbStack, Colima, Podman), then the default socket. A daemon on another machine named by an `ssh://` + endpoint (`docker context create --docker host=ssh://user@host`) is opt-in and refused at startup + until `floci.docker.allow-ssh-host` (`FLOCI_DOCKER_ALLOW_SSH_HOST=true`) is set. Once enabled, it + is reached the way the Docker CLI + reaches it: each connection runs `ssh docker system dial-stdio` with your own `~/.ssh/config` + and keys, so key-based login must work without a prompt and the `docker` CLI must be installed on + that host. Container ports are then published + on the remote host, so Floci connects to them at that host's address, which must be reachable from where + Floci runs. Bind mounts of local paths, as Lambda and ECS use, are not carried to the remote host. ### Where state goes diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 5f4fbcdf85..353b87e829 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -4612,6 +4612,15 @@ public interface EmulatorConfig { @WithDefault("unix:///var/run/docker.sock") String dockerHost(); + /** + * Opt-in: allow an {@code ssh://} Docker host (from {@code docker-host}, {@code DOCKER_HOST}, + * or the active Docker context). Off by default, because each Docker connection runs an + * {@code ssh} process on the Floci host; an {@code ssh://} endpoint is refused at startup + * until this is set to {@code true}. + */ + @WithDefault("false") + boolean allowSshHost(); + /** * Size of the connection pool behind the shared Docker client. Every short Docker call * leases a connection from it; streams that stay open while a container or a command runs diff --git a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java index 5c7da84623..17e140f9d1 100644 --- a/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java +++ b/src/main/java/io/floci/aws/core/common/docker/ContainerLifecycleManager.java @@ -102,6 +102,7 @@ public class ContainerLifecycleManager { private final LongSupplier nanoTime; private final CreateWait createWait; private final GelfLogListener gelfLogListener; + private final SshDockerEndpoint sshEndpoint; /** Volumes whose shared-ownership root has already been initialised this process (run-once guard). */ private final ConcurrentHashMap initializedSharedVolumes = new ConcurrentHashMap<>(); @@ -118,10 +119,11 @@ public class ContainerLifecycleManager { ImageCacheService imageCacheService, ContainerDetector containerDetector, EmulatorConfig config, - GelfLogListener gelfLogListener) { + GelfLogListener gelfLogListener, + SshDockerEndpoint sshEndpoint) { this(dockerClient, streamingDockerClient, imageCacheService, containerDetector, config, RetryingTarCopier.DEFAULT_BACKOFF_MS, System::nanoTime, TimeUnit.NANOSECONDS::sleep, - gelfLogListener); + gelfLogListener, sshEndpoint); } public ContainerLifecycleManager(DockerClient dockerClient, @@ -130,7 +132,7 @@ public class ContainerLifecycleManager { ContainerDetector containerDetector, EmulatorConfig config) { this(dockerClient, streamingDockerClient, imageCacheService, containerDetector, config, - GelfLogListener.disabled()); + GelfLogListener.disabled(), SshDockerEndpoint.none()); } ContainerLifecycleManager(DockerClient dockerClient, @@ -150,7 +152,7 @@ public class ContainerLifecycleManager { LongSupplier nanoTime, CreateWait createWait) { this(dockerClient, dockerClient, imageCacheService, containerDetector, config, archiveRetryBackoffMillis, - nanoTime, createWait, GelfLogListener.disabled()); + nanoTime, createWait, GelfLogListener.disabled(), SshDockerEndpoint.none()); } ContainerLifecycleManager(DockerClient dockerClient, @@ -159,7 +161,8 @@ public class ContainerLifecycleManager { EmulatorConfig config, GelfLogListener gelfLogListener) { this(dockerClient, dockerClient, imageCacheService, containerDetector, config, - RetryingTarCopier.DEFAULT_BACKOFF_MS, System::nanoTime, TimeUnit.NANOSECONDS::sleep, gelfLogListener); + RetryingTarCopier.DEFAULT_BACKOFF_MS, System::nanoTime, TimeUnit.NANOSECONDS::sleep, gelfLogListener, + SshDockerEndpoint.none()); } private ContainerLifecycleManager(DockerClient dockerClient, @@ -170,8 +173,10 @@ public class ContainerLifecycleManager { long archiveRetryBackoffMillis, LongSupplier nanoTime, CreateWait createWait, - GelfLogListener gelfLogListener) { + GelfLogListener gelfLogListener, + SshDockerEndpoint sshEndpoint) { this.gelfLogListener = gelfLogListener; + this.sshEndpoint = sshEndpoint; this.dockerClient = dockerClient; this.streamingDockerClient = streamingDockerClient; this.imageCacheService = imageCacheService; @@ -2146,13 +2151,13 @@ public class ContainerLifecycleManager { private EndpointInfo resolveEndpoint(InspectContainerResponse inspect, int containerPort, String preferredNetwork, boolean requireReachable) { if (!containerDetector.isRunningInContainer()) { - // Native mode: use localhost and the bound host port + // Native mode: the bound host port, on the daemon's host Map bindings = inspect.getNetworkSettings().getPorts().getBindings(); Ports.Binding[] binding = bindings.get(ExposedPort.tcp(containerPort)); if (binding != null && binding.length > 0) { int hostPort = Integer.parseInt(binding[0].getHostPortSpec()); - return new EndpointInfo("localhost", hostPort); + return new EndpointInfo(sshEndpoint.publishedPortHost(), hostPort); } if (requireReachable) { throw new IllegalStateException( diff --git a/src/main/java/io/floci/aws/core/common/docker/DockerClientProducer.java b/src/main/java/io/floci/aws/core/common/docker/DockerClientProducer.java index a81b0d3748..01a989acfc 100644 --- a/src/main/java/io/floci/aws/core/common/docker/DockerClientProducer.java +++ b/src/main/java/io/floci/aws/core/common/docker/DockerClientProducer.java @@ -11,10 +11,14 @@ import com.github.dockerjava.core.util.CertificateUtils; import com.github.dockerjava.transport.DockerHttpClient; import io.floci.aws.config.EmulatorConfig; import io.floci.aws.core.common.Digests; +import io.quarkus.runtime.StartupEvent; +import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.Disposes; import jakarta.enterprise.inject.Produces; import jakarta.inject.Inject; +import jakarta.interceptor.Interceptor; import org.jboss.logging.Logger; import javax.net.ssl.KeyManagerFactory; @@ -77,9 +81,31 @@ public class DockerClientProducer { this.breaker = new DockerCircuitBreaker(breakerThreshold, probeInterval); } + void validateDockerHostAtStartup( + @Observes @Priority(Interceptor.Priority.PLATFORM_BEFORE) StartupEvent ignored) { + validateDockerHostAtStartup(System::getenv); + } + + void validateDockerHostAtStartup(Function environment) { + String dockerHost = resolveDockerConnection(config.docker(), environment, false).host(); + requireSshOptIn(dockerHost, config.docker().allowSshHost()); + } + + /** + * Refuses an {@code ssh://} Docker host unless {@code floci.docker.allow-ssh-host} is on, so + * Floci spawns an {@code ssh} process per Docker connection only when explicitly enabled. + */ + static void requireSshOptIn(String dockerHost, boolean allowSshHost) { + if (SshDockerEndpoint.isSshHost(dockerHost) && !allowSshHost) { + throw new IllegalStateException("Refusing to use SSH Docker host '" + dockerHost + + "': each Docker connection runs an ssh process. Set floci.docker.allow-ssh-host" + + " (FLOCI_DOCKER_ALLOW_SSH_HOST) to true to allow it."); + } + } + /** * Normalizes a Docker host value by prepending {@code tcp://} when no recognized - * URI scheme ({@code tcp://}, {@code unix://}, {@code npipe://}) is present. + * URI scheme ({@code tcp://}, {@code unix://}, {@code npipe://}, {@code ssh://}) is present. * * @param dockerHost the raw Docker host configuration value * @return the normalized Docker host value, or the original value if it already has a scheme @@ -92,7 +118,8 @@ public class DockerClientProducer { return dockerHost; } String lower = dockerHost.toLowerCase(); - if (lower.startsWith("tcp://") || lower.startsWith("unix://") || lower.startsWith("npipe://")) { + if (lower.startsWith("tcp://") || lower.startsWith("unix://") || lower.startsWith("npipe://") + || SshDockerEndpoint.isSshHost(lower)) { return dockerHost; } String normalized = "tcp://" + dockerHost; @@ -130,9 +157,14 @@ public class DockerClientProducer { */ public static ResolvedDockerConnection resolveDockerConnection( EmulatorConfig.DockerConfig docker, Function environment) { + return resolveDockerConnection(docker, environment, true); + } + + private static ResolvedDockerConnection resolveDockerConnection( + EmulatorConfig.DockerConfig docker, Function environment, boolean resolveTls) { Path dockerConfigDir = resolveDockerConfigDir(docker.dockerConfigPath(), environment.apply("DOCKER_CONFIG")); return resolveDockerConnection(docker.dockerHost(), environment.apply("DOCKER_HOST"), isWindows(), - dockerConfigDir, environment.apply("DOCKER_CONTEXT")); + dockerConfigDir, environment.apply("DOCKER_CONTEXT"), resolveTls); } /** @@ -189,6 +221,13 @@ public class DockerClientProducer { static ResolvedDockerConnection resolveDockerConnection( String configuredHost, String dockerHostEnv, boolean isWindows, Path dockerConfigDir, String dockerContextEnv) { + return resolveDockerConnection( + configuredHost, dockerHostEnv, isWindows, dockerConfigDir, dockerContextEnv, true); + } + + private static ResolvedDockerConnection resolveDockerConnection( + String configuredHost, String dockerHostEnv, boolean isWindows, Path dockerConfigDir, + String dockerContextEnv, boolean resolveTls) { String normalizedEnvHost = normalizeDockerHost(dockerHostEnv); boolean atDefault = "unix:///var/run/docker.sock".equals(configuredHost); if (atDefault && normalizedEnvHost != null && !normalizedEnvHost.isBlank()) { @@ -196,19 +235,23 @@ public class DockerClientProducer { } if (atDefault) { DockerContextEndpoint contextEndpoint = - resolveActiveDockerContextEndpoint(dockerConfigDir, dockerContextEnv); + resolveActiveDockerContextEndpoint(dockerConfigDir, dockerContextEnv, resolveTls); 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); + if (resolveTls) { + 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); + if (resolveTls) { + 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 new ResolvedDockerConnection(WINDOWS_DEFAULT_DOCKER_HOST, Optional.empty(), false); } return new ResolvedDockerConnection(normalizeDockerHost(configuredHost), Optional.empty(), false); @@ -244,13 +287,13 @@ public class DockerClientProducer { * 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/}. + * material under {@code contexts/tls/} when {@code resolveTls} is true. * * @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) { + Path dockerConfigDir, String dockerContextEnv, boolean resolveTls) { if (dockerConfigDir == null) { return null; } @@ -262,6 +305,9 @@ public class DockerClientProducer { if (host == null || host.isBlank()) { return null; } + if (!resolveTls) { + return new DockerContextEndpoint(host, Optional.empty(), false); + } return new DockerContextEndpoint(host, resolveActiveDockerContextTlsMaterial(dockerConfigDir, currentContext), readContextSkipTlsVerify(dockerConfigDir, currentContext)); } @@ -574,6 +620,7 @@ public class DockerClientProducer { private DefaultDockerClientConfig buildClientConfig() { ResolvedDockerConnection connection = resolveDockerConnection(config.docker(), System::getenv); String dockerHost = connection.host(); + requireSshOptIn(dockerHost, config.docker().allowSshHost()); // createDefaultConfigBuilder() reads DOCKER_HOST directly from System.getenv() and passes // it to withDockerHost(), which calls URI.create() immediately. If DOCKER_HOST is set diff --git a/src/main/java/io/floci/aws/core/common/docker/FlociDockerHttpClient.java b/src/main/java/io/floci/aws/core/common/docker/FlociDockerHttpClient.java index 17aef2fe24..194042c80c 100644 --- a/src/main/java/io/floci/aws/core/common/docker/FlociDockerHttpClient.java +++ b/src/main/java/io/floci/aws/core/common/docker/FlociDockerHttpClient.java @@ -119,7 +119,7 @@ public final class FlociDockerHttpClient implements DockerHttpClient { HttpClientConnectionOperator connectionOperator = createConnectionOperator(dockerHost, sslContext); host = switch (dockerHost.getScheme()) { - case "unix", "npipe" -> new HttpHost(dockerHost.getScheme(), "localhost", 2375); + case "unix", "npipe", "ssh" -> new HttpHost(dockerHost.getScheme(), "localhost", 2375); case "tcp" -> new HttpHost(sslContext != null ? "https" : "http", dockerHost.getHost(), dockerHost.getPort()); default -> throw new IllegalArgumentException("Unsupported protocol scheme: " + dockerHost); }; @@ -183,6 +183,9 @@ public final class FlociDockerHttpClient implements DockerHttpClient { if ("npipe".equalsIgnoreCase(scheme)) { return new FailFastNamedPipeSocket(path); } + if ("ssh".equalsIgnoreCase(scheme)) { + return SshStdioSocket.open(SshDockerEndpoint.dialStdioCommand(dockerHost)); + } return socksProxy == null ? new Socket() : new Socket(socksProxy); }, DefaultSchemePortResolver.INSTANCE, diff --git a/src/main/java/io/floci/aws/core/common/docker/SshDockerEndpoint.java b/src/main/java/io/floci/aws/core/common/docker/SshDockerEndpoint.java new file mode 100644 index 0000000000..d7d8f58874 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/docker/SshDockerEndpoint.java @@ -0,0 +1,189 @@ +package io.floci.aws.core.common.docker; + +import io.floci.aws.config.EmulatorConfig; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * A Docker daemon named by an {@code ssh://[user@]host[:port]} endpoint, as a Docker context created with + * {@code docker context create --docker host=ssh://...} names it. + * + *

docker-java has no SSH transport. As the Docker CLI does, each connection runs the system {@code ssh} client + * with {@code docker system dial-stdio} on the remote host ({@link #dialStdioCommand(URI)}, {@link SshStdioSocket}), + * so the user's own {@code ~/.ssh/config}, keys and agent apply, and the remote host's own Docker settings choose the + * daemon socket. A container port Floci publishes is then bound on the remote host, so {@link #publishedPortHost()} + * names that host in place of {@code localhost}. + */ +@ApplicationScoped +public class SshDockerEndpoint { + + private static final Logger LOG = Logger.getLogger(SshDockerEndpoint.class); + + static final Duration RESOLVE_TIMEOUT = Duration.ofSeconds(10); + private static final String LOCAL_HOST = "localhost"; + + private final Supplier configuredHost; + private final Function, String> commandOutput; + + private volatile String publishedPortHost; + + @Inject + public SshDockerEndpoint(EmulatorConfig config) { + this(() -> DockerClientProducer.resolveDockerConnection(config.docker(), System::getenv).host(), + command -> runForOutput(command, RESOLVE_TIMEOUT)); + } + + SshDockerEndpoint(Supplier configuredHost, Function, String> commandOutput) { + this.configuredHost = configuredHost; + this.commandOutput = commandOutput; + } + + /** An endpoint for a daemon that is never reached over SSH. */ + public static SshDockerEndpoint none() { + return new SshDockerEndpoint(() -> null, command -> null); + } + + static boolean isSshHost(String dockerHost) { + return dockerHost != null && dockerHost.toLowerCase(Locale.ROOT).startsWith("ssh://"); + } + + /** + * The host a natively running Floci reaches a container's published port on: {@code localhost}, or the remote + * host's address when the daemon is reached over SSH. Resolved once; two first callers may both resolve it. + */ + public String publishedPortHost() { + String resolved = publishedPortHost; + if (resolved == null) { + String dockerHost = configuredHost.get(); + resolved = isSshHost(dockerHost) ? resolveHostName(URI.create(dockerHost)) : LOCAL_HOST; + publishedPortHost = resolved; + } + return resolved; + } + + private String resolveHostName(URI sshHost) { + List command = new ArrayList<>(List.of("ssh", "-G")); + command.addAll(destination(sshHost)); + String output = commandOutput.apply(command); + String hostName = output == null ? null : hostNameFromConfig(output); + if (hostName == null) { + LOG.warnv("Could not resolve the address of SSH host {0} with ssh -G; using it as written", + hostOf(sshHost)); + return hostOf(sshHost); + } + return hostName; + } + + /** + * The standard output of {@code command}, or null when it fails or outlasts {@code timeout}. The output is read + * beside the bounded wait, so a process that never closes its output cannot hold the caller past the timeout. + */ + static String runForOutput(List command, Duration timeout) { + Process process; + try { + process = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.DISCARD).start(); + } catch (IOException e) { + LOG.warnv("Could not run {0}: {1}", command, e.getMessage()); + return null; + } + return runForOutput(process, command, timeout); + } + + static String runForOutput(Process process, List command, Duration timeout) { + CompletableFuture output = new CompletableFuture<>(); + Thread.ofVirtual().name("docker-ssh-resolve").start(() -> { + try (InputStream stdout = process.getInputStream()) { + output.complete(new String(stdout.readAllBytes(), StandardCharsets.UTF_8)); + } catch (IOException e) { + output.completeExceptionally(e); + } + }); + try { + if (!process.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS)) { + LOG.warnv("{0} did not finish within {1}s", command, timeout.toSeconds()); + return null; + } + if (process.exitValue() != 0) { + return null; + } + return output.get(timeout.toMillis(), TimeUnit.MILLISECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } catch (ExecutionException | TimeoutException e) { + LOG.warnv("Could not read the output of {0}: {1}", command, e.getMessage()); + return null; + } finally { + process.destroyForcibly(); + } + } + + /** The {@code hostname} of {@code ssh -G} output, where an alias in {@code ~/.ssh/config} names its real address. */ + static String hostNameFromConfig(String sshConfigOutput) { + for (String line : sshConfigOutput.split("\\R")) { + if (line.startsWith("hostname ")) { + String value = line.substring("hostname ".length()).trim(); + return value.isEmpty() ? null : value; + } + } + return null; + } + + /** The command whose standard input and output carry one connection to the daemon of {@code sshHost}. */ + static List dialStdioCommand(URI sshHost) { + List command = new ArrayList<>(List.of("ssh", + "-o", "BatchMode=yes", + "-o", "ConnectTimeout=" + SshStdioSocket.DEFAULT_CONNECT_TIMEOUT_MILLIS / 1000, + "-o", "LogLevel=VERBOSE", + "-o", "ServerAliveInterval=30")); + command.addAll(destination(sshHost)); + command.addAll(List.of("docker", "system", "dial-stdio")); + return command; + } + + /** + * The {@code ssh} arguments naming the host of {@code ssh://[user@]host[:port]}. The authority is split by hand + * rather than through {@link URI#getHost()}, which is null for an {@code ~/.ssh/config} alias that is not a + * valid DNS name, such as one with an underscore. + */ + static List destination(URI sshHost) { + String authority = sshHost.getAuthority(); + if (authority == null || authority.isBlank()) { + throw new IllegalArgumentException("Docker host " + sshHost + " names no SSH host"); + } + List destination = new ArrayList<>(); + int at = authority.lastIndexOf('@'); + if (at >= 0) { + destination.addAll(List.of("-l", authority.substring(0, at))); + authority = authority.substring(at + 1); + } + int colon = authority.lastIndexOf(':'); + if (colon >= 0 && !authority.endsWith("]")) { + destination.addAll(List.of("-p", authority.substring(colon + 1))); + authority = authority.substring(0, colon); + } + destination.add(authority); + return destination; + } + + private static String hostOf(URI sshHost) { + List destination = destination(sshHost); + return destination.get(destination.size() - 1); + } +} diff --git a/src/main/java/io/floci/aws/core/common/docker/SshStdioSocket.java b/src/main/java/io/floci/aws/core/common/docker/SshStdioSocket.java new file mode 100644 index 0000000000..d5c626aa77 --- /dev/null +++ b/src/main/java/io/floci/aws/core/common/docker/SshStdioSocket.java @@ -0,0 +1,434 @@ +package io.floci.aws.core.common.docker; + +import org.jboss.logging.Logger; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; + +/** + * A {@link Socket} whose bytes are the standard input and output of one {@code ssh docker system dial-stdio} + * process: the way the Docker CLI reaches a daemon named by an {@code ssh://} endpoint. Each connection runs its own + * SSH session, so no local port or socket file is opened that another local user could connect to, and a connection + * opened after the network drops starts a fresh session. + * + *

A process stream has no read timeout, so a virtual thread copies the process's output into a bounded queue and + * a read waits on that queue for {@link #setSoTimeout(int)}, failing with {@link SocketTimeoutException} as a socket + * does. httpclient5's stale-connection check, a read with a 1 ms timeout, works the same way. + * + *

Starting the process is not yet a connection: the SSH handshake and login still lie ahead, and a request that + * disables its response timeout, such as a log follow or a container wait, would wait on a stalled handshake forever. + * The session runs with {@code LogLevel=VERBOSE}, so {@code ssh} reports a finished login on its error output + * ({@link #AUTHENTICATED}). Until then, or until the daemon's first byte, a read waits no longer than the connect + * timeout. Once the session is up, only the read timeout applies, so an upload that outlasts the connect timeout is + * not cut short. + */ +final class SshStdioSocket extends Socket { + + private static final Logger LOG = Logger.getLogger(SshStdioSocket.class); + + private static final byte[] END_OF_STREAM = new byte[0]; + private static final int CHUNK_SIZE = 16 * 1024; + private static final int MAX_STDERR_CHARS = 2048; + static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 30_000; + /** What {@code ssh} at {@code LogLevel=VERBOSE} writes once the login succeeded. */ + static final String AUTHENTICATED = "Authenticated to "; + private static final long CONNECTING_POLL_NANOS = TimeUnit.MILLISECONDS.toNanos(100); + + private final Process process; + private final LongSupplier nanoTime; + private final BlockingQueue chunks = new ArrayBlockingQueue<>(64); + private final StringBuilder stderr = new StringBuilder(); + private final InputStream input = new QueueInputStream(); + private final OutputStream output; + private final Thread outputPump; + private volatile int soTimeoutMillis; + private volatile long connectDeadlineNanos; + private volatile boolean established; + private volatile boolean closed; + private volatile boolean inputShutdown; + private volatile boolean outputShutdown; + + private SshStdioSocket(Process process, LongSupplier nanoTime) { + this.process = process; + this.nanoTime = nanoTime; + this.output = new ProcessOutputStream(process.getOutputStream()); + this.connectDeadlineNanos = nanoTime.getAsLong() + TimeUnit.MILLISECONDS.toNanos(DEFAULT_CONNECT_TIMEOUT_MILLIS); + this.outputPump = Thread.ofVirtual().name("docker-ssh-stdout").start(this::pumpOutput); + Thread.ofVirtual().name("docker-ssh-stderr").start(this::pumpErrors); + } + + /** Starts {@code command}, which must relay the daemon's API over its standard input and output. */ + static SshStdioSocket open(List command) throws IOException { + return open(command, System::nanoTime); + } + + static SshStdioSocket open(List command, LongSupplier nanoTime) throws IOException { + Process process; + try { + process = new ProcessBuilder(command).start(); + } catch (IOException e) { + throw new IOException("Could not run the ssh client to reach the Docker daemon; is OpenSSH on the PATH? " + + e.getMessage(), e); + } + return new SshStdioSocket(process, nanoTime); + } + + private void pumpOutput() { + try { + try (InputStream stdout = process.getInputStream()) { + byte[] buffer = new byte[CHUNK_SIZE]; + int read; + while ((read = stdout.read(buffer)) >= 0) { + if (read > 0) { + chunks.put(Arrays.copyOf(buffer, read)); + } + } + } catch (IOException e) { + LOG.debugv("Stopped reading the Docker SSH session''s output: {0}", e.getMessage()); + } + // Waits for room like the output before it, so a slow reader still gets every byte before the end. + chunks.put(END_OF_STREAM); + } catch (InterruptedException e) { + // close() interrupts the pump so it never stays parked on a full queue nobody reads any more. + Thread.currentThread().interrupt(); + } + } + + private void pumpErrors() { + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + LOG.debugv("ssh: {0}", line); + if (line.startsWith(AUTHENTICATED)) { + established = true; + } + synchronized (stderr) { + if (stderr.length() < MAX_STDERR_CHARS) { + stderr.append(stderr.isEmpty() ? "" : " | ").append(line); + } + } + } + } catch (IOException e) { + LOG.debugv("Stopped reading the Docker SSH session''s errors: {0}", e.getMessage()); + } + } + + /** + * The failure to report when the stream ends: an SSH session that exited with an error before the daemon sent + * anything failed to connect, and its error output says why. + */ + private IOException sessionFailure() { + try { + if (!process.waitFor(1, TimeUnit.SECONDS) || process.exitValue() == 0) { + return null; + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return null; + } + synchronized (stderr) { + return new SocketException("SSH session to the Docker daemon exited with status " + process.exitValue() + + ": " + (stderr.isEmpty() ? "no error output" : stderr)); + } + } + + @Override + public void connect(SocketAddress endpoint) { + // Connected by open(): httpclient5 calls this on the socket its factory returned. + } + + /** The process is already started; {@code timeout} bounds the SSH login that follows. */ + @Override + public void connect(SocketAddress endpoint, int timeout) { + if (timeout > 0) { + connectDeadlineNanos = nanoTime.getAsLong() + TimeUnit.MILLISECONDS.toNanos(timeout); + } + } + + @Override + public InputStream getInputStream() throws IOException { + ensureOpen(); + if (inputShutdown) { + throw new SocketException("Socket input is shutdown"); + } + return input; + } + + @Override + public OutputStream getOutputStream() throws IOException { + ensureOpen(); + if (outputShutdown) { + throw new SocketException("Socket output is shutdown"); + } + return output; + } + + @Override + public void setSoTimeout(int timeout) { + if (timeout < 0) { + throw new IllegalArgumentException("timeout can't be negative"); + } + soTimeoutMillis = timeout; + } + + @Override + public int getSoTimeout() { + return soTimeoutMillis; + } + + @Override + public void shutdownInput() throws IOException { + ensureOpen(); + inputShutdown = true; + } + + /** Closes the session's standard input, which {@code dial-stdio} passes on to the daemon as a half-close. */ + @Override + public void shutdownOutput() throws IOException { + ensureOpen(); + outputShutdown = true; + process.getOutputStream().close(); + } + + @Override + public void close() { + if (closed) { + return; + } + closed = true; + process.destroy(); + outputPump.interrupt(); + // Unread output is of no use once closed; the end marker wakes a read still waiting on the queue. + chunks.clear(); + chunks.offer(END_OF_STREAM); + } + + @Override + public boolean isConnected() { + return true; + } + + @Override + public boolean isBound() { + return true; + } + + @Override + public boolean isClosed() { + return closed; + } + + @Override + public boolean isInputShutdown() { + return inputShutdown; + } + + @Override + public boolean isOutputShutdown() { + return outputShutdown; + } + + @Override + public SocketAddress getLocalSocketAddress() { + return null; + } + + @Override + public SocketAddress getRemoteSocketAddress() { + return null; + } + + @Override + public InetAddress getInetAddress() { + return null; + } + + @Override + public InetAddress getLocalAddress() { + return null; + } + + /** Whether the thread copying the session's output is still running. */ + boolean isOutputPumpAlive() { + return outputPump.isAlive(); + } + + boolean isOutputPumpBlockedOnQueue() { + return chunks.remainingCapacity() == 0 && outputPump.getState() == Thread.State.WAITING; + } + + boolean hasQueuedChunks() { + return !chunks.isEmpty(); + } + + boolean isEstablished() { + return established; + } + + boolean awaitProcessExit(Duration timeout) throws InterruptedException { + return process.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS); + } + + void awaitOutputPumpExit(Duration timeout) throws InterruptedException { + outputPump.join(timeout); + } + + private void ensureOpen() throws SocketException { + if (closed) { + throw new SocketException("Socket is closed"); + } + } + + private final class QueueInputStream extends InputStream { + + private byte[] current; + private int position; + private boolean anyRead; + private boolean ended; + + @Override + public int read() throws IOException { + byte[] single = new byte[1]; + int read = read(single, 0, 1); + return read < 0 ? -1 : single[0] & 0xFF; + } + + @Override + public synchronized int read(byte[] bytes, int offset, int length) throws IOException { + if (length == 0) { + return 0; + } + if (current == null || position == current.length) { + if (ended) { + return -1; + } + byte[] next = take(); + if (next == END_OF_STREAM) { + ended = true; + ensureOpen(); + IOException failure = anyRead ? null : sessionFailure(); + if (failure != null) { + throw failure; + } + return -1; + } + current = next; + position = 0; + anyRead = true; + } + int count = Math.min(length, current.length - position); + System.arraycopy(current, position, bytes, offset, count); + position += count; + return count; + } + + private byte[] take() throws IOException { + ensureOpen(); + long readTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(soTimeoutMillis); + long started = nanoTime.getAsLong(); + try { + while (isConnecting()) { + long waited = nanoTime.getAsLong() - started; + if (readTimeoutNanos > 0 && waited >= readTimeoutNanos) { + throw readTimeout(); + } + long remainingConnect = connectDeadlineNanos - nanoTime.getAsLong(); + long wait = remainingConnect <= 0 ? 0 : Math.min(CONNECTING_POLL_NANOS, remainingConnect); + if (readTimeoutNanos > 0) { + wait = Math.min(wait, readTimeoutNanos - waited); + } + // Output already queued wins over an expired deadline. + byte[] next = wait > 0 ? chunks.poll(wait, TimeUnit.NANOSECONDS) : chunks.poll(); + if (next != null) { + return next; + } + if (isConnecting() && nanoTime.getAsLong() - connectDeadlineNanos >= 0) { + throw connectTimeout(); + } + } + if (readTimeoutNanos == 0) { + return chunks.take(); + } + long left = readTimeoutNanos - (nanoTime.getAsLong() - started); + byte[] next = left > 0 ? chunks.poll(left, TimeUnit.NANOSECONDS) : chunks.poll(); + if (next == null) { + throw readTimeout(); + } + return next; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + close(); + throw new SocketException("Interrupted while reading from the Docker SSH session"); + } + } + + private boolean isConnecting() { + return !anyRead && !established; + } + + private SocketTimeoutException readTimeout() { + return new SocketTimeoutException("Read timed out after " + soTimeoutMillis + " ms"); + } + + private SocketTimeoutException connectTimeout() { + synchronized (stderr) { + return new SocketTimeoutException("SSH session to the Docker daemon did not log in within the connect" + + " timeout" + (stderr.isEmpty() ? "" : ": " + stderr)); + } + } + + @Override + public int available() { + return current == null ? 0 : current.length - position; + } + } + + /** Flushes each write, since the process's standard input is buffered and a request must reach the daemon whole. */ + private final class ProcessOutputStream extends OutputStream { + + private final OutputStream stdin; + + ProcessOutputStream(OutputStream stdin) { + this.stdin = stdin; + } + + @Override + public void write(int value) throws IOException { + write(new byte[] {(byte) value}, 0, 1); + } + + @Override + public void write(byte[] bytes, int offset, int length) throws IOException { + ensureOpen(); + stdin.write(bytes, offset, length); + stdin.flush(); + } + + @Override + public void flush() throws IOException { + stdin.flush(); + } + + @Override + public void close() { + SshStdioSocket.this.close(); + } + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 3deff930aa..bce9ef836a 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -402,6 +402,12 @@ floci: log-max-size: "10m" log-max-file: "3" docker-host: unix:///var/run/docker.sock + # FLOCI_DOCKER_ALLOW_SSH_HOST: opt-in; allow an ssh:// Docker host (from docker-host, + # DOCKER_HOST, or the active Docker context). Off by default because each Docker connection + # runs an ssh process; an ssh:// host is refused at startup until this is true. Keep in step + # with the @WithDefault on EmulatorConfig.DockerConfig.allowSshHost: a value set here WINS + # over the annotation. + allow-ssh-host: false # FLOCI_DOCKER_MAX_CONNECTIONS: connection pool size for Floci's short Docker calls. Past the # limit, create/start/stop/remove wait for a free connection and the emulator stalls. Keep in step # with the @WithDefault on EmulatorConfig.DockerConfig.maxConnections: a value set here WINS diff --git a/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java b/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java index 3d495cabf8..0fd15a4f25 100644 --- a/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java +++ b/src/test/java/io/floci/aws/config/ApplicationDefaultsTest.java @@ -315,4 +315,16 @@ class ApplicationDefaultsTest { assertEquals("12201", EmulatorConfig.DockerConfig.class.getMethod("logDriverPort") .getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml"); } + + // Catches: allow-ssh-host switched on by default so Floci spawns ssh processes without opt-in, + // or the yml and the @WithDefault disagreeing. + @Test + void productionConfigKeepsAllowSshHostOff() throws IOException, NoSuchMethodException { + JsonNode flag = productionConfig().path("floci").path("docker").path("allow-ssh-host"); + + assertFalse(flag.isMissingNode(), "allow-ssh-host should be declared in application.yml"); + assertFalse(flag.asBoolean(true)); + assertEquals("false", EmulatorConfig.DockerConfig.class.getMethod("allowSshHost") + .getAnnotation(WithDefault.class).value(), "the @WithDefault must match application.yml"); + } } diff --git a/src/test/java/io/floci/aws/core/common/docker/DockerClientProducerTest.java b/src/test/java/io/floci/aws/core/common/docker/DockerClientProducerTest.java index 69f79dfbe7..e1a6d12290 100644 --- a/src/test/java/io/floci/aws/core/common/docker/DockerClientProducerTest.java +++ b/src/test/java/io/floci/aws/core/common/docker/DockerClientProducerTest.java @@ -103,7 +103,9 @@ class DockerClientProducerTest { "tcp://10.37.124.101:2375", "tcp://localhost:2375", "unix:///var/run/docker.sock", - "npipe:////./pipe/docker_engine" + "npipe:////./pipe/docker_engine", + "ssh://remote-docker", + "ssh://ubuntu@10.0.0.5:2222" ); } @@ -111,7 +113,7 @@ class DockerClientProducerTest { * 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 + * (tcp://, unix://, npipe://, ssh://), normalizeDockerHost should return the value * unchanged, preserving all existing Docker client initialization behavior. */ @ParameterizedTest @@ -263,6 +265,15 @@ class DockerClientProducerTest { "An explicitly-configured docker-host should take priority over the Windows named-pipe fallback"); } + private static EmulatorConfig mockConfig(String dockerHost, Path dockerConfigDir) { + EmulatorConfig config = mock(EmulatorConfig.class); + EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class); + when(config.docker()).thenReturn(docker); + when(docker.dockerHost()).thenReturn(dockerHost); + when(docker.dockerConfigPath()).thenReturn(Optional.ofNullable(dockerConfigDir).map(Path::toString)); + return config; + } + // Control-plane calls (create/start/stop/remove/copyArchive) and long-lived streaming // calls (log-follow, exec output streams) must not share one connection pool: a // container's whole-lifetime streams would otherwise occupy pool slots that @@ -271,12 +282,9 @@ class DockerClientProducerTest { // therefore be genuinely separate DockerClient instances (and thus separate pools), // not the same instance handed out under two qualifiers. @Test - void dockerClientAndStreamingDockerClient_areDistinctInstances() throws IOException { - EmulatorConfig config = mock(EmulatorConfig.class); - EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class); - when(config.docker()).thenReturn(docker); - when(docker.dockerHost()).thenReturn("unix:///var/run/docker.sock"); - when(docker.dockerConfigPath()).thenReturn(Optional.empty()); + void dockerClientAndStreamingDockerClient_areDistinctInstances(@TempDir Path dockerConfigDir) throws IOException { + EmulatorConfig config = mockConfig("unix:///var/run/docker.sock", dockerConfigDir); + EmulatorConfig.DockerConfig docker = config.docker(); when(docker.maxConnections()).thenReturn(100); when(docker.streamingMaxConnections()).thenReturn(512); when(docker.connectionRequestTimeoutSeconds()).thenReturn(30); @@ -782,11 +790,8 @@ class DockerClientProducerTest { acceptor.setDaemon(true); acceptor.start(); - EmulatorConfig config = mock(EmulatorConfig.class); - EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class); - when(config.docker()).thenReturn(docker); - when(docker.dockerHost()).thenReturn("tcp://127.0.0.1:" + daemon.getLocalPort()); - when(docker.dockerConfigPath()).thenReturn(Optional.empty()); + EmulatorConfig config = mockConfig("tcp://127.0.0.1:" + daemon.getLocalPort(), null); + EmulatorConfig.DockerConfig docker = config.docker(); when(docker.maxConnections()).thenReturn(2); when(docker.connectionRequestTimeoutSeconds()).thenReturn(1); when(docker.apiTimeoutSeconds()).thenReturn(300); @@ -858,4 +863,66 @@ class DockerClientProducerTest { assertEquals("tcp://127.0.0.1:2375", plainConfig.getDockerHost().toString()); } } + + @ParameterizedTest + @ValueSource(strings = {"ssh://remote-docker", "SSH://ubuntu@10.0.0.5:2222"}) + void requireSshOptIn_refusesSshHostWhenOff_namingTheSetting(String sshHost) { + IllegalStateException e = assertThrows(IllegalStateException.class, + () -> DockerClientProducer.requireSshOptIn(sshHost, false)); + + assertThat(e.getMessage(), containsString(sshHost)); + assertThat(e.getMessage(), containsString("floci.docker.allow-ssh-host")); + assertThat(e.getMessage(), containsString("FLOCI_DOCKER_ALLOW_SSH_HOST")); + } + + @Test + void requireSshOptIn_allowsSshHostWhenOn_andAllowsNonSshHostsWhenOff() { + assertDoesNotThrow(() -> DockerClientProducer.requireSshOptIn("ssh://remote-docker", true)); + assertDoesNotThrow(() -> DockerClientProducer.requireSshOptIn("unix:///var/run/docker.sock", false)); + assertDoesNotThrow(() -> DockerClientProducer.requireSshOptIn("tcp://127.0.0.1:2375", false)); + assertDoesNotThrow(() -> DockerClientProducer.requireSshOptIn("npipe:////./pipe/docker_engine", false)); + assertDoesNotThrow(() -> DockerClientProducer.requireSshOptIn(null, false)); + } + + @Test + void validateDockerHostAtStartup_refusesSshHostUntilOptInIsOn() { + EmulatorConfig config = mockConfig("ssh://remote-docker", null); + EmulatorConfig.DockerConfig docker = config.docker(); + DockerClientProducer producer = new DockerClientProducer(config); + + IllegalStateException startupFailure = assertThrows(IllegalStateException.class, + () -> producer.validateDockerHostAtStartup(name -> null)); + assertThat(startupFailure.getMessage(), containsString("floci.docker.allow-ssh-host")); + assertThat(startupFailure.getMessage(), containsString("FLOCI_DOCKER_ALLOW_SSH_HOST")); + + IllegalStateException clientFailure = assertThrows(IllegalStateException.class, producer::dockerClient); + assertThat(clientFailure.getMessage(), containsString("floci.docker.allow-ssh-host")); + + when(docker.allowSshHost()).thenReturn(true); + assertDoesNotThrow(() -> producer.validateDockerHostAtStartup(name -> null)); + } + + @Test + void validateDockerHostAtStartup_ignoresIncompleteContextTlsMaterial(@TempDir Path tempDir) throws IOException { + writeContextFixture(tempDir, "remote-tls", "tcp://remote-docker:2376"); + writeContextTlsFixture(tempDir, "remote-tls", true, false, false); + + DockerClientProducer producer = new DockerClientProducer(mockConfig("unix:///var/run/docker.sock", tempDir)); + + assertDoesNotThrow(() -> producer.validateDockerHostAtStartup(name -> null), + "Unrelated Docker context TLS errors must not block startup"); + } + + @Test + void validateDockerHostAtStartup_stillRefusesSshContextWithIncompleteTlsMaterial(@TempDir Path tempDir) + throws IOException { + writeContextFixture(tempDir, "remote-ssh", "ssh://remote-docker"); + writeContextTlsFixture(tempDir, "remote-ssh", true, false, false); + + DockerClientProducer producer = new DockerClientProducer(mockConfig("unix:///var/run/docker.sock", tempDir)); + + IllegalStateException startupFailure = assertThrows(IllegalStateException.class, + () -> producer.validateDockerHostAtStartup(name -> null)); + assertThat(startupFailure.getMessage(), containsString("floci.docker.allow-ssh-host")); + } } diff --git a/src/test/java/io/floci/aws/core/common/docker/SshDockerEndpointTest.java b/src/test/java/io/floci/aws/core/common/docker/SshDockerEndpointTest.java new file mode 100644 index 0000000000..fa583355fe --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/docker/SshDockerEndpointTest.java @@ -0,0 +1,167 @@ +package io.floci.aws.core.common.docker; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SshDockerEndpointTest { + + @Test + void dialStdioCommandRunsTheDockerRelayOnTheRemoteHost() { + assertThat(SshDockerEndpoint.dialStdioCommand(URI.create("ssh://remote-docker")), contains("ssh", + "-o", "BatchMode=yes", + "-o", "ConnectTimeout=30", + "-o", "LogLevel=VERBOSE", + "-o", "ServerAliveInterval=30", + "remote-docker", "docker", "system", "dial-stdio")); + } + + @Test + void destinationPassesUserAndPortAsSshOptions() { + assertThat(SshDockerEndpoint.destination(URI.create("ssh://ubuntu@10.0.0.5:2222")), + contains("-l", "ubuntu", "-p", "2222", "10.0.0.5")); + } + + @Test + void destinationKeepsAnAliasThatIsNotAValidHostName() { + assertThat(SshDockerEndpoint.destination(URI.create("ssh://docker_box")), contains("docker_box")); + } + + @Test + void destinationRejectsAnEndpointWithNoHost() { + assertThrows(IllegalArgumentException.class, () -> SshDockerEndpoint.destination(URI.create("ssh:///path"))); + } + + @Test + void hostNameFromConfigReadsTheResolvedAddressOfAnAlias() { + assertThat(SshDockerEndpoint.hostNameFromConfig("user ubuntu\nhostname 100.110.111.77\nport 22\n"), + equalTo("100.110.111.77")); + } + + @Test + void hostNameFromConfigIsNullWithoutAHostNameLine() { + assertThat(SshDockerEndpoint.hostNameFromConfig("user ubuntu\r\nport 22\r\n"), is(nullValue())); + } + + @Test + void publishedPortHostIsTheAddressSshResolvesTheAliasTo() { + AtomicInteger lookups = new AtomicInteger(); + SshDockerEndpoint endpoint = new SshDockerEndpoint(() -> "ssh://ubuntu@remote-docker", command -> { + lookups.incrementAndGet(); + assertThat(command, contains("ssh", "-G", "-l", "ubuntu", "remote-docker")); + return "user ubuntu\nhostname 100.110.111.77\n"; + }); + + assertThat(endpoint.publishedPortHost(), equalTo("100.110.111.77")); + assertThat(endpoint.publishedPortHost(), equalTo("100.110.111.77")); + assertThat(lookups.get(), equalTo(1)); + } + + @Test + void publishedPortHostFallsBackToTheHostAsWrittenWhenSshCannotResolveIt() { + SshDockerEndpoint endpoint = new SshDockerEndpoint(() -> "ssh://remote-docker:2222", command -> null); + + assertThat(endpoint.publishedPortHost(), equalTo("remote-docker")); + } + + @Test + void publishedPortHostIsLocalhostForADaemonNotReachedOverSsh() { + SshDockerEndpoint endpoint = new SshDockerEndpoint(() -> "unix:///var/run/docker.sock", command -> { + throw new AssertionError("ssh must not run for a local daemon"); + }); + + assertThat(endpoint.publishedPortHost(), equalTo("localhost")); + assertThat(SshDockerEndpoint.none().publishedPortHost(), equalTo("localhost")); + } + + @Test + void runForOutputGivesUpOnACommandThatOutlastsTheTimeout() throws IOException { + StalledProcess stalled = new StalledProcess(); + + String output = SshDockerEndpoint.runForOutput(stalled, List.of("ssh", "-G", "remote"), Duration.ofSeconds(10)); + + assertThat(output, is(nullValue())); + assertThat(stalled.destroyed, is(true)); + } + + @Test + void isSshHostMatchesTheSchemeInAnyCase() { + assertThat(SshDockerEndpoint.isSshHost("SSH://remote"), is(true)); + assertThat(SshDockerEndpoint.isSshHost("tcp://ssh:2375"), is(false)); + assertThat(SshDockerEndpoint.isSshHost(null), is(false)); + } + + /** Holds its output open and never exits within the wait, as a stalled {@code ssh -G} would. */ + private static final class StalledProcess extends Process { + + private final PipedOutputStream stdoutWriter = new PipedOutputStream(); + private final PipedInputStream stdout; + private volatile boolean destroyed; + + StalledProcess() throws IOException { + this.stdout = new PipedInputStream(stdoutWriter); + } + + @Override + public OutputStream getOutputStream() { + return OutputStream.nullOutputStream(); + } + + @Override + public InputStream getInputStream() { + return stdout; + } + + @Override + public InputStream getErrorStream() { + return InputStream.nullInputStream(); + } + + @Override + public int waitFor() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean waitFor(long timeout, TimeUnit unit) { + return false; + } + + @Override + public int exitValue() { + throw new IllegalThreadStateException("process has not exited"); + } + + @Override + public void destroy() { + destroyForcibly(); + } + + @Override + public Process destroyForcibly() { + destroyed = true; + try { + stdoutWriter.close(); + } catch (IOException ignored) { + // Closing the pipe releases the reader thread; a second close is harmless. + } + return this; + } + } +} diff --git a/src/test/java/io/floci/aws/core/common/docker/SshStdioSocketTest.java b/src/test/java/io/floci/aws/core/common/docker/SshStdioSocketTest.java new file mode 100644 index 0000000000..59880f730e --- /dev/null +++ b/src/test/java/io/floci/aws/core/common/docker/SshStdioSocketTest.java @@ -0,0 +1,250 @@ +package io.floci.aws.core.common.docker; + +import io.floci.aws.testing.ThreadStates; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import java.util.EnumSet; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; + +import static org.awaitility.Awaitility.await; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SshStdioSocketTest { + + private static final Duration AWAIT_TIMEOUT = Duration.ofSeconds(10); + + private static List javaMain(Class main) { + String java = Path.of(System.getProperty("java.home"), "bin", "java").toString(); + return List.of(java, "-cp", testClasses(main), main.getName()); + } + + /** Only the test classes, since the whole test class path is too long for a Windows command line. */ + private static String testClasses(Class main) { + try { + return Path.of(main.getProtectionDomain().getCodeSource().getLocation().toURI()).toString(); + } catch (URISyntaxException e) { + throw new IllegalStateException(e); + } + } + + @Test + void bytesWrittenComeBackThroughTheProcess() throws IOException { + try (SshStdioSocket socket = SshStdioSocket.open(javaMain(Echo.class))) { + socket.setSoTimeout(30_000); + socket.getOutputStream().write("GET /_ping HTTP/1.1\r\n".getBytes(StandardCharsets.UTF_8)); + + byte[] echoed = socket.getInputStream().readNBytes(21); + + assertThat(new String(echoed, StandardCharsets.UTF_8), equalTo("GET /_ping HTTP/1.1\r\n")); + } + } + + @Test + void aReadWithNoDataFailsAfterTheSoTimeout() throws IOException { + AtomicLong clock = new AtomicLong(); + try (SshStdioSocket socket = SshStdioSocket.open( + javaMain(Echo.class), () -> clock.addAndGet(Duration.ofSeconds(1).toNanos()))) { + socket.setSoTimeout(200); + + assertThrows(SocketTimeoutException.class, () -> socket.getInputStream().read()); + assertThat(socket.isClosed(), is(false)); + } + } + + @Test + void aSessionThatFailsToConnectReportsItsErrorOutput() throws IOException { + try (SshStdioSocket socket = SshStdioSocket.open(javaMain(FailToConnect.class))) { + socket.setSoTimeout(30_000); + InputStream in = socket.getInputStream(); + + SocketException failure = assertThrows(SocketException.class, in::read); + + assertThat(failure.getMessage(), containsString("exited with status 255")); + assertThat(failure.getMessage(), containsString("Connection refused")); + } + } + + @Test + void closingTheSocketEndsAWaitingRead() throws Exception { + SshStdioSocket socket = SshStdioSocket.open(javaMain(Echo.class)); + Thread reader = Thread.currentThread(); + Thread closer = Thread.ofVirtual().start(() -> { + ThreadStates.awaitState(reader, EnumSet.of(Thread.State.WAITING, Thread.State.TIMED_WAITING), + AWAIT_TIMEOUT, "reader waiting on queue"); + socket.close(); + }); + + assertThrows(SocketException.class, () -> socket.getInputStream().read()); + closer.join(); + assertThat(socket.isClosed(), is(true)); + } + + @Test + void shutdownOutputEndsTheSessionInput() throws IOException { + try (SshStdioSocket socket = SshStdioSocket.open(javaMain(Echo.class))) { + socket.setSoTimeout(30_000); + socket.getOutputStream().write('x'); + socket.shutdownOutput(); + InputStream in = socket.getInputStream(); + + assertThat(in.read(), equalTo((int) 'x')); + assertThat(in.read(), equalTo(-1)); + } + } + + @Test + void aSlowReaderGetsEveryByteOfASessionThatAlreadyEnded() throws Exception { + try (SshStdioSocket socket = SshStdioSocket.open(javaMain(WriteThenExit.class))) { + socket.setSoTimeout(30_000); + InputStream in = socket.getInputStream(); + in.read(); + assertThat(socket.awaitProcessExit(AWAIT_TIMEOUT), is(true)); + socket.awaitOutputPumpExit(AWAIT_TIMEOUT); + + byte[] rest = in.readAllBytes(); + + assertThat(1 + rest.length, equalTo(WriteThenExit.BYTES)); + } + } + + @Test + void aSessionThatNeverAnswersFailsAtTheConnectTimeoutEvenWithoutAReadTimeout() throws IOException { + AtomicLong clock = new AtomicLong(); + try (SshStdioSocket socket = SshStdioSocket.open(javaMain(Echo.class), clock::get)) { + socket.connect(null, 500); + socket.setSoTimeout(0); + clock.addAndGet(Duration.ofSeconds(1).toNanos()); + + SocketTimeoutException failure = + assertThrows(SocketTimeoutException.class, () -> socket.getInputStream().read()); + + assertThat(failure.getMessage(), containsString("did not log in within the connect timeout")); + } + } + + @Test + void theConnectTimeoutNoLongerAppliesOnceTheSessionAnswered() throws Exception { + AtomicLong clock = new AtomicLong(); + try (SshStdioSocket socket = SshStdioSocket.open(javaMain(Echo.class), clock::get)) { + socket.connect(null, 300); + socket.setSoTimeout(30_000); + socket.getOutputStream().write('a'); + InputStream in = socket.getInputStream(); + assertThat(in.read(), equalTo((int) 'a')); + clock.addAndGet(Duration.ofSeconds(1).toNanos()); + socket.getOutputStream().write('b'); + + assertThat(in.read(), equalTo((int) 'b')); + } + } + + @Test + void anAnswerAlreadyQueuedIsReadEvenAfterTheConnectDeadlinePassed() throws Exception { + AtomicLong clock = new AtomicLong(); + try (SshStdioSocket socket = SshStdioSocket.open(javaMain(Echo.class), clock::get)) { + socket.connect(null, 300); + socket.setSoTimeout(30_000); + socket.getOutputStream().write('a'); + await().atMost(AWAIT_TIMEOUT).until(socket::hasQueuedChunks); + clock.addAndGet(Duration.ofSeconds(1).toNanos()); + + assertThat(socket.getInputStream().read(), equalTo((int) 'a')); + } + } + + @Test + void aSlowUploadAfterLoginIsNotCutShortByTheConnectTimeout() throws Exception { + AtomicLong clock = new AtomicLong(); + try (SshStdioSocket socket = SshStdioSocket.open(javaMain(LoggedInEcho.class), clock::get)) { + socket.connect(null, 300); + socket.setSoTimeout(30_000); + await().atMost(AWAIT_TIMEOUT).until(socket::isEstablished); + // The request body is still being sent well past the connect timeout. + for (int i = 0; i < 4; i++) { + clock.addAndGet(Duration.ofMillis(250).toNanos()); + socket.getOutputStream().write('u'); + } + + byte[] answer = socket.getInputStream().readNBytes(4); + + assertThat(new String(answer, StandardCharsets.UTF_8), equalTo("uuuu")); + } + } + + @Test + void closingReleasesTheOutputPumpBlockedOnAFullQueue() throws Exception { + SshStdioSocket socket = SshStdioSocket.open(javaMain(WriteManyThenExit.class)); + await().atMost(AWAIT_TIMEOUT).until(socket::isOutputPumpBlockedOnQueue); + assertThat(socket.isOutputPumpAlive(), is(true)); + + socket.close(); + + socket.awaitOutputPumpExit(AWAIT_TIMEOUT); + assertThat(socket.isOutputPumpAlive(), is(false)); + } + + /** Copies its input to its output, as {@code docker system dial-stdio} relays the daemon's socket. */ + public static final class Echo { + public static void main(String[] args) throws IOException { + byte[] buffer = new byte[1024]; + int read; + while ((read = System.in.read(buffer)) >= 0) { + System.out.write(buffer, 0, read); + System.out.flush(); + } + } + } + + /** Reports a finished login as {@code ssh} at {@code LogLevel=VERBOSE} does, then relays like {@link Echo}. */ + public static final class LoggedInEcho { + public static void main(String[] args) throws IOException { + System.err.println(SshStdioSocket.AUTHENTICATED + "remote-docker ([10.0.0.5]:22) using \"publickey\"."); + System.err.flush(); + Echo.main(args); + } + } + + /** Writes multiple chunks that fit in the queue unread, then exits. */ + public static final class WriteThenExit { + static final int BYTES = 64 * 1024; + + public static void main(String[] args) throws IOException { + System.out.write(new byte[BYTES]); + System.out.flush(); + } + } + + /** Writes more than the socket queues unread, then exits. */ + public static final class WriteManyThenExit { + static final int BYTES = 4 * 1024 * 1024; + + public static void main(String[] args) throws IOException { + byte[] chunk = new byte[64 * 1024]; + for (int written = 0; written < BYTES; written += chunk.length) { + System.out.write(chunk); + } + System.out.flush(); + } + } + + /** Exits as {@code ssh} does when it cannot reach the host. */ + public static final class FailToConnect { + public static void main(String[] args) { + System.err.println("ssh: connect to host remote-docker port 22: Connection refused"); + System.exit(255); + } + } +}