diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java index f8812cd0b1..37e3fe63ca 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManager.java @@ -217,11 +217,16 @@ public class Ec2ContainerManager { portForwardManager.reconcile(instance, appPorts); } - // Inject SSH public key + // Inject SSH public key, if one was provided if (publicKey != null && !publicKey.isBlank()) { injectSshKey(containerId, publicKey); - startSshd(containerId, instanceId); } + // sshd runs on every instance regardless of whether a key pair was supplied, + // matching real AWS AMIs (which start it as part of normal boot, independent of + // key-pair association) - starting it only when a key was present meant + // run-instances without --key-name produced a "connection refused" instead of AWS's + // actual behavior: a running daemon with simply nothing to authenticate against. + startSshd(containerId, instanceId); // Execute UserData String userData = instance.getUserData(); @@ -454,18 +459,40 @@ public class Ec2ContainerManager { private void startSshd(String containerId, String instanceId) { try { - // Install openssh-server if absent - execInContainer(containerId, new String[]{"sh", "-c", + // Install openssh-server if absent. The trailing "command -v sshd" makes the script's + // own exit code the source of truth for whether sshd is actually available afterward - + // without it, a shell if/elif chain with no matching branch (no dnf/apt-get/apk found) or + // whose install command itself failed (e.g. no network yet, apt lock held) still exits 0 + // by bash convention, so every later step here would silently no-op against a daemon that + // was never installed while still logging success. + ContainerExecResult install = execInContainerForResult(containerId, new String[]{"sh", "-c", "if ! command -v sshd >/dev/null 2>&1; then" + " if command -v dnf >/dev/null 2>&1; then dnf install -y openssh-server >/dev/null 2>&1;" + " elif command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server >/dev/null 2>&1;" + " elif command -v apk >/dev/null 2>&1; then apk add --no-cache openssh >/dev/null 2>&1;" + " fi;" + - "fi"}, 120); + "fi;" + + "command -v sshd >/dev/null 2>&1"}, 120); + if (install.exitCode() != 0) { + LOG.warnv("Could not install openssh-server for EC2 instance {0}: {1}", + instanceId, install.summary()); + return; + } // Generate host keys - execInContainer(containerId, new String[]{"ssh-keygen", "-A"}, 10); - // Start sshd without -D so it daemonizes itself and survives this exec session - execInContainer(containerId, new String[]{"/usr/sbin/sshd"}, 5); + ContainerExecResult keygen = execInContainerForResult(containerId, new String[]{"ssh-keygen", "-A"}, 10); + if (keygen.exitCode() != 0) { + LOG.warnv("Could not generate SSH host keys for EC2 instance {0}: {1}", + instanceId, keygen.summary()); + return; + } + // Start sshd without -D so it daemonizes itself and survives this exec session. Resolved + // via PATH (like ssh-keygen above) rather than hardcoded to /usr/sbin/sshd, since not + // every image installs it to that exact path. + ContainerExecResult start = execInContainerForResult(containerId, new String[]{"sshd"}, 5); + if (start.exitCode() != 0) { + LOG.warnv("Could not start sshd for EC2 instance {0}: {1}", instanceId, start.summary()); + return; + } LOG.infov("Started sshd in EC2 instance {0}", instanceId); } catch (Exception e) { LOG.warnv("Could not start sshd in EC2 instance {0}: {1}", instanceId, e.getMessage()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java index 8d8fd43c27..6229c651ac 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2ContainerManagerTest.java @@ -370,6 +370,103 @@ class Ec2ContainerManagerTest { awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2)); } + @Test + void launchWithoutKeyPairStillStartsSshd() throws Exception { + // Regression for #2184: sshd previously only started when a key pair was supplied, so + // run-instances without --key-name left no daemon listening at all ("connection refused") + // instead of matching real AWS AMIs, which run sshd as part of normal boot regardless of + // whether a key pair is attached to the instance. + LaunchHarness harness = launchHarness(); + InspectContainerCmd inspect = mock(InspectContainerCmd.class); + InspectContainerResponse withIp = inspectResponse("172.18.0.20"); + when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect); + when(inspect.exec()).thenReturn(withIp); + harness.stubSuccessfulExecs(new CountDownLatch(0), new CountDownLatch(0)); + Instance instance = instance("i-nokeypair"); + + harness.manager.launch(instance, "ubuntu:24.04", null, "us-west-2"); + + awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2)); + ExecCreateCmd execCreate = harness.dockerClient.execCreateCmd(TEST_CONTAINER_ID); + verify(execCreate, timeout(2000)).withCmd(eq(new String[]{"sshd"})); + // No key pair was supplied, so nothing should have been written to authorized_keys. + verify(harness.dockerClient, never()).copyArchiveToContainerCmd(TEST_CONTAINER_ID); + } + + private static final String[] SSHD_INSTALL_PROBE_CMD = {"sh", "-c", + "if ! command -v sshd >/dev/null 2>&1; then" + + " if command -v dnf >/dev/null 2>&1; then dnf install -y openssh-server >/dev/null 2>&1;" + + " elif command -v apt-get >/dev/null 2>&1; then DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server >/dev/null 2>&1;" + + " elif command -v apk >/dev/null 2>&1; then apk add --no-cache openssh >/dev/null 2>&1;" + + " fi;" + + "fi;" + + "command -v sshd >/dev/null 2>&1"}; + + @Test + void launchWhenSshdInstallFails_doesNotAttemptKeygenOrStart() throws Exception { + // Regression reported as a follow-up on #2245 (duytanisme): sshd not starting even when a + // key pair IS provided. Root cause: execInContainer() discards exit codes entirely, so a + // shell if/elif chain with no matching package manager - or whose install command itself + // failed (no network yet, apt lock held, etc.) - still exits 0 by bash convention with no + // final check, meaning startSshd() proceeded to ssh-keygen and sshd regardless and still + // logged success. This forces the install probe to report failure and asserts the later + // steps are never even attempted, rather than running against a daemon that was never + // installed. + LaunchHarness harness = launchHarness(); + InspectContainerCmd inspect = mock(InspectContainerCmd.class); + InspectContainerResponse withIp = inspectResponse("172.18.0.21"); + when(harness.dockerClient.inspectContainerCmd(TEST_CONTAINER_ID)).thenReturn(inspect); + when(inspect.exec()).thenReturn(withIp); + + ExecCreateCmd execCreate = mock(ExecCreateCmd.class, withSettings().defaultAnswer(RETURNS_SELF)); + when(harness.dockerClient.execCreateCmd(TEST_CONTAINER_ID)).thenReturn(execCreate); + AtomicReference currentCommand = new AtomicReference<>(); + when(execCreate.withCmd(any(String[].class))).thenAnswer(invocation -> { + Object[] args = invocation.getArguments(); + currentCommand.set(args.length == 1 && args[0] instanceof String[] cmd + ? cmd : Arrays.copyOf(args, args.length, String[].class)); + return execCreate; + }); + ExecCreateCmdResponse execResponse = mock(ExecCreateCmdResponse.class); + when(execResponse.getId()).thenReturn("exec-1"); + when(execCreate.exec()).thenReturn(execResponse); + + when(harness.dockerClient.execStartCmd(anyString())).thenAnswer(invocation -> { + ExecStartCmd execStart = mock(ExecStartCmd.class); + when(execStart.exec(any())).thenAnswer(startInvocation -> { + @SuppressWarnings("unchecked") + ResultCallback callback = startInvocation.getArgument(0); + callback.onComplete(); + return callback; + }); + return execStart; + }); + + // Every exec succeeds except the sshd-install probe script, simulating an image with none + // of dnf/apt-get/apk, or whose install command itself failed. + InspectExecCmd inspectExec = mock(InspectExecCmd.class); + when(harness.dockerClient.inspectExecCmd(anyString())).thenReturn(inspectExec); + when(inspectExec.exec()).thenAnswer(invocation -> { + InspectExecResponse response = mock(InspectExecResponse.class); + boolean isSshdInstallProbe = Arrays.equals(currentCommand.get(), SSHD_INSTALL_PROBE_CMD); + when(response.getExitCodeLong()).thenReturn(isSshdInstallProbe ? 1L : 0L); + return response; + }); + + CopyArchiveToContainerCmd copy = mock(CopyArchiveToContainerCmd.class, withSettings().defaultAnswer(RETURNS_SELF)); + when(harness.dockerClient.copyArchiveToContainerCmd(TEST_CONTAINER_ID)).thenReturn(copy); + when(copy.withTarInputStream(any(InputStream.class))).thenReturn(copy); + + Instance instance = instance("i-sshdinstallfail"); + + harness.manager.launch(instance, "ubuntu:24.04", "ssh-ed25519 AAAAtest", "us-west-2"); + + awaitUntil(() -> "running".equals(instance.getState().getName()), Duration.ofSeconds(2)); + verify(execCreate, timeout(2000)).withCmd(eq(SSHD_INSTALL_PROBE_CMD)); + verify(execCreate, never()).withCmd(eq(new String[]{"ssh-keygen", "-A"})); + verify(execCreate, never()).withCmd(eq(new String[]{"sshd"})); + } + private static LaunchHarness launchHarness() { ContainerBuilder containerBuilder = mock(ContainerBuilder.class); ContainerBuilder.Builder builder = mock(ContainerBuilder.Builder.class, withSettings().defaultAnswer(RETURNS_SELF));